]> rtime.felk.cvut.cz Git - l4.git/blob - l4/pkg/sqlite/lib/contrib/sqlite3.c
update
[l4.git] / l4 / pkg / sqlite / lib / contrib / sqlite3.c
1 /******************************************************************************
2 ** This file is an amalgamation of many separate C source files from SQLite
3 ** version 3.7.17.  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.17"
682 #define SQLITE_VERSION_NUMBER 3007017
683 #define SQLITE_SOURCE_ID      "2013-05-20 00:56:22 118a3b35693b134d56ebd780123b7fd6f1497668"
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_NOTICE      27   /* Notifications from sqlite3_log() */
1000 #define SQLITE_WARNING     28   /* Warnings from sqlite3_log() */
1001 #define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
1002 #define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
1003 /* end-of-error-codes */
1004
1005 /*
1006 ** CAPI3REF: Extended Result Codes
1007 ** KEYWORDS: {extended error code} {extended error codes}
1008 ** KEYWORDS: {extended result code} {extended result codes}
1009 **
1010 ** In its default configuration, SQLite API routines return one of 26 integer
1011 ** [SQLITE_OK | result codes].  However, experience has shown that many of
1012 ** these result codes are too coarse-grained.  They do not provide as
1013 ** much information about problems as programmers might like.  In an effort to
1014 ** address this, newer versions of SQLite (version 3.3.8 and later) include
1015 ** support for additional result codes that provide more detailed information
1016 ** about errors. The extended result codes are enabled or disabled
1017 ** on a per database connection basis using the
1018 ** [sqlite3_extended_result_codes()] API.
1019 **
1020 ** Some of the available extended result codes are listed here.
1021 ** One may expect the number of extended result codes will be expand
1022 ** over time.  Software that uses extended result codes should expect
1023 ** to see new result codes in future releases of SQLite.
1024 **
1025 ** The SQLITE_OK result code will never be extended.  It will always
1026 ** be exactly zero.
1027 */
1028 #define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
1029 #define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
1030 #define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
1031 #define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
1032 #define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
1033 #define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
1034 #define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))
1035 #define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))
1036 #define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))
1037 #define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))
1038 #define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))
1039 #define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))
1040 #define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))
1041 #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
1042 #define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
1043 #define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))
1044 #define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))
1045 #define SQLITE_IOERR_SHMOPEN           (SQLITE_IOERR | (18<<8))
1046 #define SQLITE_IOERR_SHMSIZE           (SQLITE_IOERR | (19<<8))
1047 #define SQLITE_IOERR_SHMLOCK           (SQLITE_IOERR | (20<<8))
1048 #define SQLITE_IOERR_SHMMAP            (SQLITE_IOERR | (21<<8))
1049 #define SQLITE_IOERR_SEEK              (SQLITE_IOERR | (22<<8))
1050 #define SQLITE_IOERR_DELETE_NOENT      (SQLITE_IOERR | (23<<8))
1051 #define SQLITE_IOERR_MMAP              (SQLITE_IOERR | (24<<8))
1052 #define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED |  (1<<8))
1053 #define SQLITE_BUSY_RECOVERY           (SQLITE_BUSY   |  (1<<8))
1054 #define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))
1055 #define SQLITE_CANTOPEN_ISDIR          (SQLITE_CANTOPEN | (2<<8))
1056 #define SQLITE_CANTOPEN_FULLPATH       (SQLITE_CANTOPEN | (3<<8))
1057 #define SQLITE_CORRUPT_VTAB            (SQLITE_CORRUPT | (1<<8))
1058 #define SQLITE_READONLY_RECOVERY       (SQLITE_READONLY | (1<<8))
1059 #define SQLITE_READONLY_CANTLOCK       (SQLITE_READONLY | (2<<8))
1060 #define SQLITE_READONLY_ROLLBACK       (SQLITE_READONLY | (3<<8))
1061 #define SQLITE_ABORT_ROLLBACK          (SQLITE_ABORT | (2<<8))
1062 #define SQLITE_CONSTRAINT_CHECK        (SQLITE_CONSTRAINT | (1<<8))
1063 #define SQLITE_CONSTRAINT_COMMITHOOK   (SQLITE_CONSTRAINT | (2<<8))
1064 #define SQLITE_CONSTRAINT_FOREIGNKEY   (SQLITE_CONSTRAINT | (3<<8))
1065 #define SQLITE_CONSTRAINT_FUNCTION     (SQLITE_CONSTRAINT | (4<<8))
1066 #define SQLITE_CONSTRAINT_NOTNULL      (SQLITE_CONSTRAINT | (5<<8))
1067 #define SQLITE_CONSTRAINT_PRIMARYKEY   (SQLITE_CONSTRAINT | (6<<8))
1068 #define SQLITE_CONSTRAINT_TRIGGER      (SQLITE_CONSTRAINT | (7<<8))
1069 #define SQLITE_CONSTRAINT_UNIQUE       (SQLITE_CONSTRAINT | (8<<8))
1070 #define SQLITE_CONSTRAINT_VTAB         (SQLITE_CONSTRAINT | (9<<8))
1071 #define SQLITE_NOTICE_RECOVER_WAL      (SQLITE_NOTICE | (1<<8))
1072 #define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
1073
1074 /*
1075 ** CAPI3REF: Flags For File Open Operations
1076 **
1077 ** These bit values are intended for use in the
1078 ** 3rd parameter to the [sqlite3_open_v2()] interface and
1079 ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
1080 */
1081 #define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */
1082 #define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */
1083 #define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */
1084 #define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */
1085 #define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */
1086 #define SQLITE_OPEN_AUTOPROXY        0x00000020  /* VFS only */
1087 #define SQLITE_OPEN_URI              0x00000040  /* Ok for sqlite3_open_v2() */
1088 #define SQLITE_OPEN_MEMORY           0x00000080  /* Ok for sqlite3_open_v2() */
1089 #define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */
1090 #define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */
1091 #define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */
1092 #define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */
1093 #define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */
1094 #define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */
1095 #define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
1096 #define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */
1097 #define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
1098 #define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
1099 #define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
1100 #define SQLITE_OPEN_WAL              0x00080000  /* VFS only */
1101
1102 /* Reserved:                         0x00F00000 */
1103
1104 /*
1105 ** CAPI3REF: Device Characteristics
1106 **
1107 ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
1108 ** object returns an integer which is a vector of these
1109 ** bit values expressing I/O characteristics of the mass storage
1110 ** device that holds the file that the [sqlite3_io_methods]
1111 ** refers to.
1112 **
1113 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
1114 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1115 ** mean that writes of blocks that are nnn bytes in size and
1116 ** are aligned to an address which is an integer multiple of
1117 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1118 ** that when data is appended to a file, the data is appended
1119 ** first then the size of the file is extended, never the other
1120 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1121 ** information is written to disk in the same order as calls
1122 ** to xWrite().  The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
1123 ** after reboot following a crash or power loss, the only bytes in a
1124 ** file that were written at the application level might have changed
1125 ** and that adjacent bytes, even bytes within the same sector are
1126 ** guaranteed to be unchanged.
1127 */
1128 #define SQLITE_IOCAP_ATOMIC                 0x00000001
1129 #define SQLITE_IOCAP_ATOMIC512              0x00000002
1130 #define SQLITE_IOCAP_ATOMIC1K               0x00000004
1131 #define SQLITE_IOCAP_ATOMIC2K               0x00000008
1132 #define SQLITE_IOCAP_ATOMIC4K               0x00000010
1133 #define SQLITE_IOCAP_ATOMIC8K               0x00000020
1134 #define SQLITE_IOCAP_ATOMIC16K              0x00000040
1135 #define SQLITE_IOCAP_ATOMIC32K              0x00000080
1136 #define SQLITE_IOCAP_ATOMIC64K              0x00000100
1137 #define SQLITE_IOCAP_SAFE_APPEND            0x00000200
1138 #define SQLITE_IOCAP_SEQUENTIAL             0x00000400
1139 #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN  0x00000800
1140 #define SQLITE_IOCAP_POWERSAFE_OVERWRITE    0x00001000
1141
1142 /*
1143 ** CAPI3REF: File Locking Levels
1144 **
1145 ** SQLite uses one of these integer values as the second
1146 ** argument to calls it makes to the xLock() and xUnlock() methods
1147 ** of an [sqlite3_io_methods] object.
1148 */
1149 #define SQLITE_LOCK_NONE          0
1150 #define SQLITE_LOCK_SHARED        1
1151 #define SQLITE_LOCK_RESERVED      2
1152 #define SQLITE_LOCK_PENDING       3
1153 #define SQLITE_LOCK_EXCLUSIVE     4
1154
1155 /*
1156 ** CAPI3REF: Synchronization Type Flags
1157 **
1158 ** When SQLite invokes the xSync() method of an
1159 ** [sqlite3_io_methods] object it uses a combination of
1160 ** these integer values as the second argument.
1161 **
1162 ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
1163 ** sync operation only needs to flush data to mass storage.  Inode
1164 ** information need not be flushed. If the lower four bits of the flag
1165 ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
1166 ** If the lower four bits equal SQLITE_SYNC_FULL, that means
1167 ** to use Mac OS X style fullsync instead of fsync().
1168 **
1169 ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
1170 ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
1171 ** settings.  The [synchronous pragma] determines when calls to the
1172 ** xSync VFS method occur and applies uniformly across all platforms.
1173 ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
1174 ** energetic or rigorous or forceful the sync operations are and
1175 ** only make a difference on Mac OSX for the default SQLite code.
1176 ** (Third-party VFS implementations might also make the distinction
1177 ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
1178 ** operating systems natively supported by SQLite, only Mac OSX
1179 ** cares about the difference.)
1180 */
1181 #define SQLITE_SYNC_NORMAL        0x00002
1182 #define SQLITE_SYNC_FULL          0x00003
1183 #define SQLITE_SYNC_DATAONLY      0x00010
1184
1185 /*
1186 ** CAPI3REF: OS Interface Open File Handle
1187 **
1188 ** An [sqlite3_file] object represents an open file in the 
1189 ** [sqlite3_vfs | OS interface layer].  Individual OS interface
1190 ** implementations will
1191 ** want to subclass this object by appending additional fields
1192 ** for their own use.  The pMethods entry is a pointer to an
1193 ** [sqlite3_io_methods] object that defines methods for performing
1194 ** I/O operations on the open file.
1195 */
1196 typedef struct sqlite3_file sqlite3_file;
1197 struct sqlite3_file {
1198   const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
1199 };
1200
1201 /*
1202 ** CAPI3REF: OS Interface File Virtual Methods Object
1203 **
1204 ** Every file opened by the [sqlite3_vfs.xOpen] method populates an
1205 ** [sqlite3_file] object (or, more commonly, a subclass of the
1206 ** [sqlite3_file] object) with a pointer to an instance of this object.
1207 ** This object defines the methods used to perform various operations
1208 ** against the open file represented by the [sqlite3_file] object.
1209 **
1210 ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element 
1211 ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
1212 ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed.  The
1213 ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
1214 ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
1215 ** to NULL.
1216 **
1217 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
1218 ** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
1219 ** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]
1220 ** flag may be ORed in to indicate that only the data of the file
1221 ** and not its inode needs to be synced.
1222 **
1223 ** The integer values to xLock() and xUnlock() are one of
1224 ** <ul>
1225 ** <li> [SQLITE_LOCK_NONE],
1226 ** <li> [SQLITE_LOCK_SHARED],
1227 ** <li> [SQLITE_LOCK_RESERVED],
1228 ** <li> [SQLITE_LOCK_PENDING], or
1229 ** <li> [SQLITE_LOCK_EXCLUSIVE].
1230 ** </ul>
1231 ** xLock() increases the lock. xUnlock() decreases the lock.
1232 ** The xCheckReservedLock() method checks whether any database connection,
1233 ** either in this process or in some other process, is holding a RESERVED,
1234 ** PENDING, or EXCLUSIVE lock on the file.  It returns true
1235 ** if such a lock exists and false otherwise.
1236 **
1237 ** The xFileControl() method is a generic interface that allows custom
1238 ** VFS implementations to directly control an open file using the
1239 ** [sqlite3_file_control()] interface.  The second "op" argument is an
1240 ** integer opcode.  The third argument is a generic pointer intended to
1241 ** point to a structure that may contain arguments or space in which to
1242 ** write return values.  Potential uses for xFileControl() might be
1243 ** functions to enable blocking locks with timeouts, to change the
1244 ** locking strategy (for example to use dot-file locks), to inquire
1245 ** about the status of a lock, or to break stale locks.  The SQLite
1246 ** core reserves all opcodes less than 100 for its own use.
1247 ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
1248 ** Applications that define a custom xFileControl method should use opcodes
1249 ** greater than 100 to avoid conflicts.  VFS implementations should
1250 ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
1251 ** recognize.
1252 **
1253 ** The xSectorSize() method returns the sector size of the
1254 ** device that underlies the file.  The sector size is the
1255 ** minimum write that can be performed without disturbing
1256 ** other bytes in the file.  The xDeviceCharacteristics()
1257 ** method returns a bit vector describing behaviors of the
1258 ** underlying device:
1259 **
1260 ** <ul>
1261 ** <li> [SQLITE_IOCAP_ATOMIC]
1262 ** <li> [SQLITE_IOCAP_ATOMIC512]
1263 ** <li> [SQLITE_IOCAP_ATOMIC1K]
1264 ** <li> [SQLITE_IOCAP_ATOMIC2K]
1265 ** <li> [SQLITE_IOCAP_ATOMIC4K]
1266 ** <li> [SQLITE_IOCAP_ATOMIC8K]
1267 ** <li> [SQLITE_IOCAP_ATOMIC16K]
1268 ** <li> [SQLITE_IOCAP_ATOMIC32K]
1269 ** <li> [SQLITE_IOCAP_ATOMIC64K]
1270 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
1271 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
1272 ** </ul>
1273 **
1274 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
1275 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1276 ** mean that writes of blocks that are nnn bytes in size and
1277 ** are aligned to an address which is an integer multiple of
1278 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1279 ** that when data is appended to a file, the data is appended
1280 ** first then the size of the file is extended, never the other
1281 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1282 ** information is written to disk in the same order as calls
1283 ** to xWrite().
1284 **
1285 ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
1286 ** in the unread portions of the buffer with zeros.  A VFS that
1287 ** fails to zero-fill short reads might seem to work.  However,
1288 ** failure to zero-fill short reads will eventually lead to
1289 ** database corruption.
1290 */
1291 typedef struct sqlite3_io_methods sqlite3_io_methods;
1292 struct sqlite3_io_methods {
1293   int iVersion;
1294   int (*xClose)(sqlite3_file*);
1295   int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
1296   int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
1297   int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
1298   int (*xSync)(sqlite3_file*, int flags);
1299   int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
1300   int (*xLock)(sqlite3_file*, int);
1301   int (*xUnlock)(sqlite3_file*, int);
1302   int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
1303   int (*xFileControl)(sqlite3_file*, int op, void *pArg);
1304   int (*xSectorSize)(sqlite3_file*);
1305   int (*xDeviceCharacteristics)(sqlite3_file*);
1306   /* Methods above are valid for version 1 */
1307   int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
1308   int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
1309   void (*xShmBarrier)(sqlite3_file*);
1310   int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
1311   /* Methods above are valid for version 2 */
1312   int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
1313   int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
1314   /* Methods above are valid for version 3 */
1315   /* Additional methods may be added in future releases */
1316 };
1317
1318 /*
1319 ** CAPI3REF: Standard File Control Opcodes
1320 **
1321 ** These integer constants are opcodes for the xFileControl method
1322 ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
1323 ** interface.
1324 **
1325 ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
1326 ** opcode causes the xFileControl method to write the current state of
1327 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
1328 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
1329 ** into an integer that the pArg argument points to. This capability
1330 ** is used during testing and only needs to be supported when SQLITE_TEST
1331 ** is defined.
1332 ** <ul>
1333 ** <li>[[SQLITE_FCNTL_SIZE_HINT]]
1334 ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
1335 ** layer a hint of how large the database file will grow to be during the
1336 ** current transaction.  This hint is not guaranteed to be accurate but it
1337 ** is often close.  The underlying VFS might choose to preallocate database
1338 ** file space based on this hint in order to help writes to the database
1339 ** file run faster.
1340 **
1341 ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
1342 ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
1343 ** extends and truncates the database file in chunks of a size specified
1344 ** by the user. The fourth argument to [sqlite3_file_control()] should 
1345 ** point to an integer (type int) containing the new chunk-size to use
1346 ** for the nominated database. Allocating database file space in large
1347 ** chunks (say 1MB at a time), may reduce file-system fragmentation and
1348 ** improve performance on some systems.
1349 **
1350 ** <li>[[SQLITE_FCNTL_FILE_POINTER]]
1351 ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
1352 ** to the [sqlite3_file] object associated with a particular database
1353 ** connection.  See the [sqlite3_file_control()] documentation for
1354 ** additional information.
1355 **
1356 ** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
1357 ** ^(The [SQLITE_FCNTL_SYNC_OMITTED] opcode is generated internally by
1358 ** SQLite and sent to all VFSes in place of a call to the xSync method
1359 ** when the database connection has [PRAGMA synchronous] set to OFF.)^
1360 ** Some specialized VFSes need this signal in order to operate correctly
1361 ** when [PRAGMA synchronous | PRAGMA synchronous=OFF] is set, but most 
1362 ** VFSes do not need this signal and should silently ignore this opcode.
1363 ** Applications should not call [sqlite3_file_control()] with this
1364 ** opcode as doing so may disrupt the operation of the specialized VFSes
1365 ** that do require it.  
1366 **
1367 ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
1368 ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
1369 ** retry counts and intervals for certain disk I/O operations for the
1370 ** windows [VFS] in order to provide robustness in the presence of
1371 ** anti-virus programs.  By default, the windows VFS will retry file read,
1372 ** file write, and file delete operations up to 10 times, with a delay
1373 ** of 25 milliseconds before the first retry and with the delay increasing
1374 ** by an additional 25 milliseconds with each subsequent retry.  This
1375 ** opcode allows these two values (10 retries and 25 milliseconds of delay)
1376 ** to be adjusted.  The values are changed for all database connections
1377 ** within the same process.  The argument is a pointer to an array of two
1378 ** integers where the first integer i the new retry count and the second
1379 ** integer is the delay.  If either integer is negative, then the setting
1380 ** is not changed but instead the prior value of that setting is written
1381 ** into the array entry, allowing the current retry settings to be
1382 ** interrogated.  The zDbName parameter is ignored.
1383 **
1384 ** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
1385 ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
1386 ** persistent [WAL | Write Ahead Log] setting.  By default, the auxiliary
1387 ** write ahead log and shared memory files used for transaction control
1388 ** are automatically deleted when the latest connection to the database
1389 ** closes.  Setting persistent WAL mode causes those files to persist after
1390 ** close.  Persisting the files is useful when other processes that do not
1391 ** have write permission on the directory containing the database file want
1392 ** to read the database file, as the WAL and shared memory files must exist
1393 ** in order for the database to be readable.  The fourth parameter to
1394 ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1395 ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
1396 ** WAL mode.  If the integer is -1, then it is overwritten with the current
1397 ** WAL persistence setting.
1398 **
1399 ** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
1400 ** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
1401 ** persistent "powersafe-overwrite" or "PSOW" setting.  The PSOW setting
1402 ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
1403 ** xDeviceCharacteristics methods. The fourth parameter to
1404 ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1405 ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
1406 ** mode.  If the integer is -1, then it is overwritten with the current
1407 ** zero-damage mode setting.
1408 **
1409 ** <li>[[SQLITE_FCNTL_OVERWRITE]]
1410 ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
1411 ** a write transaction to indicate that, unless it is rolled back for some
1412 ** reason, the entire database file will be overwritten by the current 
1413 ** transaction. This is used by VACUUM operations.
1414 **
1415 ** <li>[[SQLITE_FCNTL_VFSNAME]]
1416 ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
1417 ** all [VFSes] in the VFS stack.  The names are of all VFS shims and the
1418 ** final bottom-level VFS are written into memory obtained from 
1419 ** [sqlite3_malloc()] and the result is stored in the char* variable
1420 ** that the fourth parameter of [sqlite3_file_control()] points to.
1421 ** The caller is responsible for freeing the memory when done.  As with
1422 ** all file-control actions, there is no guarantee that this will actually
1423 ** do anything.  Callers should initialize the char* variable to a NULL
1424 ** pointer in case this file-control is not implemented.  This file-control
1425 ** is intended for diagnostic use only.
1426 **
1427 ** <li>[[SQLITE_FCNTL_PRAGMA]]
1428 ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA] 
1429 ** file control is sent to the open [sqlite3_file] object corresponding
1430 ** to the database file to which the pragma statement refers. ^The argument
1431 ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
1432 ** pointers to strings (char**) in which the second element of the array
1433 ** is the name of the pragma and the third element is the argument to the
1434 ** pragma or NULL if the pragma has no argument.  ^The handler for an
1435 ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
1436 ** of the char** argument point to a string obtained from [sqlite3_mprintf()]
1437 ** or the equivalent and that string will become the result of the pragma or
1438 ** the error message if the pragma fails. ^If the
1439 ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal 
1440 ** [PRAGMA] processing continues.  ^If the [SQLITE_FCNTL_PRAGMA]
1441 ** file control returns [SQLITE_OK], then the parser assumes that the
1442 ** VFS has handled the PRAGMA itself and the parser generates a no-op
1443 ** prepared statement.  ^If the [SQLITE_FCNTL_PRAGMA] file control returns
1444 ** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
1445 ** that the VFS encountered an error while handling the [PRAGMA] and the
1446 ** compilation of the PRAGMA fails with an error.  ^The [SQLITE_FCNTL_PRAGMA]
1447 ** file control occurs at the beginning of pragma statement analysis and so
1448 ** it is able to override built-in [PRAGMA] statements.
1449 **
1450 ** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
1451 ** ^The [SQLITE_FCNTL_BUSYHANDLER]
1452 ** file-control may be invoked by SQLite on the database file handle
1453 ** shortly after it is opened in order to provide a custom VFS with access
1454 ** to the connections busy-handler callback. The argument is of type (void **)
1455 ** - an array of two (void *) values. The first (void *) actually points
1456 ** to a function of type (int (*)(void *)). In order to invoke the connections
1457 ** busy-handler, this function should be invoked with the second (void *) in
1458 ** the array as the only argument. If it returns non-zero, then the operation
1459 ** should be retried. If it returns zero, the custom VFS should abandon the
1460 ** current operation.
1461 **
1462 ** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
1463 ** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
1464 ** to have SQLite generate a
1465 ** temporary filename using the same algorithm that is followed to generate
1466 ** temporary filenames for TEMP tables and other internal uses.  The
1467 ** argument should be a char** which will be filled with the filename
1468 ** written into memory obtained from [sqlite3_malloc()].  The caller should
1469 ** invoke [sqlite3_free()] on the result to avoid a memory leak.
1470 **
1471 ** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
1472 ** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
1473 ** maximum number of bytes that will be used for memory-mapped I/O.
1474 ** The argument is a pointer to a value of type sqlite3_int64 that
1475 ** is an advisory maximum number of bytes in the file to memory map.  The
1476 ** pointer is overwritten with the old value.  The limit is not changed if
1477 ** the value originally pointed to is negative, and so the current limit 
1478 ** can be queried by passing in a pointer to a negative number.  This
1479 ** file-control is used internally to implement [PRAGMA mmap_size].
1480 **
1481 ** </ul>
1482 */
1483 #define SQLITE_FCNTL_LOCKSTATE               1
1484 #define SQLITE_GET_LOCKPROXYFILE             2
1485 #define SQLITE_SET_LOCKPROXYFILE             3
1486 #define SQLITE_LAST_ERRNO                    4
1487 #define SQLITE_FCNTL_SIZE_HINT               5
1488 #define SQLITE_FCNTL_CHUNK_SIZE              6
1489 #define SQLITE_FCNTL_FILE_POINTER            7
1490 #define SQLITE_FCNTL_SYNC_OMITTED            8
1491 #define SQLITE_FCNTL_WIN32_AV_RETRY          9
1492 #define SQLITE_FCNTL_PERSIST_WAL            10
1493 #define SQLITE_FCNTL_OVERWRITE              11
1494 #define SQLITE_FCNTL_VFSNAME                12
1495 #define SQLITE_FCNTL_POWERSAFE_OVERWRITE    13
1496 #define SQLITE_FCNTL_PRAGMA                 14
1497 #define SQLITE_FCNTL_BUSYHANDLER            15
1498 #define SQLITE_FCNTL_TEMPFILENAME           16
1499 #define SQLITE_FCNTL_MMAP_SIZE              18
1500
1501 /*
1502 ** CAPI3REF: Mutex Handle
1503 **
1504 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
1505 ** abstract type for a mutex object.  The SQLite core never looks
1506 ** at the internal representation of an [sqlite3_mutex].  It only
1507 ** deals with pointers to the [sqlite3_mutex] object.
1508 **
1509 ** Mutexes are created using [sqlite3_mutex_alloc()].
1510 */
1511 typedef struct sqlite3_mutex sqlite3_mutex;
1512
1513 /*
1514 ** CAPI3REF: OS Interface Object
1515 **
1516 ** An instance of the sqlite3_vfs object defines the interface between
1517 ** the SQLite core and the underlying operating system.  The "vfs"
1518 ** in the name of the object stands for "virtual file system".  See
1519 ** the [VFS | VFS documentation] for further information.
1520 **
1521 ** The value of the iVersion field is initially 1 but may be larger in
1522 ** future versions of SQLite.  Additional fields may be appended to this
1523 ** object when the iVersion value is increased.  Note that the structure
1524 ** of the sqlite3_vfs object changes in the transaction between
1525 ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
1526 ** modified.
1527 **
1528 ** The szOsFile field is the size of the subclassed [sqlite3_file]
1529 ** structure used by this VFS.  mxPathname is the maximum length of
1530 ** a pathname in this VFS.
1531 **
1532 ** Registered sqlite3_vfs objects are kept on a linked list formed by
1533 ** the pNext pointer.  The [sqlite3_vfs_register()]
1534 ** and [sqlite3_vfs_unregister()] interfaces manage this list
1535 ** in a thread-safe way.  The [sqlite3_vfs_find()] interface
1536 ** searches the list.  Neither the application code nor the VFS
1537 ** implementation should use the pNext pointer.
1538 **
1539 ** The pNext field is the only field in the sqlite3_vfs
1540 ** structure that SQLite will ever modify.  SQLite will only access
1541 ** or modify this field while holding a particular static mutex.
1542 ** The application should never modify anything within the sqlite3_vfs
1543 ** object once the object has been registered.
1544 **
1545 ** The zName field holds the name of the VFS module.  The name must
1546 ** be unique across all VFS modules.
1547 **
1548 ** [[sqlite3_vfs.xOpen]]
1549 ** ^SQLite guarantees that the zFilename parameter to xOpen
1550 ** is either a NULL pointer or string obtained
1551 ** from xFullPathname() with an optional suffix added.
1552 ** ^If a suffix is added to the zFilename parameter, it will
1553 ** consist of a single "-" character followed by no more than
1554 ** 11 alphanumeric and/or "-" characters.
1555 ** ^SQLite further guarantees that
1556 ** the string will be valid and unchanged until xClose() is
1557 ** called. Because of the previous sentence,
1558 ** the [sqlite3_file] can safely store a pointer to the
1559 ** filename if it needs to remember the filename for some reason.
1560 ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
1561 ** must invent its own temporary name for the file.  ^Whenever the 
1562 ** xFilename parameter is NULL it will also be the case that the
1563 ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1564 **
1565 ** The flags argument to xOpen() includes all bits set in
1566 ** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
1567 ** or [sqlite3_open16()] is used, then flags includes at least
1568 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. 
1569 ** If xOpen() opens a file read-only then it sets *pOutFlags to
1570 ** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
1571 **
1572 ** ^(SQLite will also add one of the following flags to the xOpen()
1573 ** call, depending on the object being opened:
1574 **
1575 ** <ul>
1576 ** <li>  [SQLITE_OPEN_MAIN_DB]
1577 ** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
1578 ** <li>  [SQLITE_OPEN_TEMP_DB]
1579 ** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
1580 ** <li>  [SQLITE_OPEN_TRANSIENT_DB]
1581 ** <li>  [SQLITE_OPEN_SUBJOURNAL]
1582 ** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
1583 ** <li>  [SQLITE_OPEN_WAL]
1584 ** </ul>)^
1585 **
1586 ** The file I/O implementation can use the object type flags to
1587 ** change the way it deals with files.  For example, an application
1588 ** that does not care about crash recovery or rollback might make
1589 ** the open of a journal file a no-op.  Writes to this journal would
1590 ** also be no-ops, and any attempt to read the journal would return
1591 ** SQLITE_IOERR.  Or the implementation might recognize that a database
1592 ** file will be doing page-aligned sector reads and writes in a random
1593 ** order and set up its I/O subsystem accordingly.
1594 **
1595 ** SQLite might also add one of the following flags to the xOpen method:
1596 **
1597 ** <ul>
1598 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
1599 ** <li> [SQLITE_OPEN_EXCLUSIVE]
1600 ** </ul>
1601 **
1602 ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1603 ** deleted when it is closed.  ^The [SQLITE_OPEN_DELETEONCLOSE]
1604 ** will be set for TEMP databases and their journals, transient
1605 ** databases, and subjournals.
1606 **
1607 ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
1608 ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
1609 ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
1610 ** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the 
1611 ** SQLITE_OPEN_CREATE, is used to indicate that file should always
1612 ** be created, and that it is an error if it already exists.
1613 ** It is <i>not</i> used to indicate the file should be opened 
1614 ** for exclusive access.
1615 **
1616 ** ^At least szOsFile bytes of memory are allocated by SQLite
1617 ** to hold the  [sqlite3_file] structure passed as the third
1618 ** argument to xOpen.  The xOpen method does not have to
1619 ** allocate the structure; it should just fill it in.  Note that
1620 ** the xOpen method must set the sqlite3_file.pMethods to either
1621 ** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do
1622 ** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods
1623 ** element will be valid after xOpen returns regardless of the success
1624 ** or failure of the xOpen call.
1625 **
1626 ** [[sqlite3_vfs.xAccess]]
1627 ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1628 ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1629 ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1630 ** to test whether a file is at least readable.   The file can be a
1631 ** directory.
1632 **
1633 ** ^SQLite will always allocate at least mxPathname+1 bytes for the
1634 ** output buffer xFullPathname.  The exact size of the output buffer
1635 ** is also passed as a parameter to both  methods. If the output buffer
1636 ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1637 ** handled as a fatal error by SQLite, vfs implementations should endeavor
1638 ** to prevent this by setting mxPathname to a sufficiently large value.
1639 **
1640 ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
1641 ** interfaces are not strictly a part of the filesystem, but they are
1642 ** included in the VFS structure for completeness.
1643 ** The xRandomness() function attempts to return nBytes bytes
1644 ** of good-quality randomness into zOut.  The return value is
1645 ** the actual number of bytes of randomness obtained.
1646 ** The xSleep() method causes the calling thread to sleep for at
1647 ** least the number of microseconds given.  ^The xCurrentTime()
1648 ** method returns a Julian Day Number for the current date and time as
1649 ** a floating point value.
1650 ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
1651 ** Day Number multiplied by 86400000 (the number of milliseconds in 
1652 ** a 24-hour day).  
1653 ** ^SQLite will use the xCurrentTimeInt64() method to get the current
1654 ** date and time if that method is available (if iVersion is 2 or 
1655 ** greater and the function pointer is not NULL) and will fall back
1656 ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
1657 **
1658 ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
1659 ** are not used by the SQLite core.  These optional interfaces are provided
1660 ** by some VFSes to facilitate testing of the VFS code. By overriding 
1661 ** system calls with functions under its control, a test program can
1662 ** simulate faults and error conditions that would otherwise be difficult
1663 ** or impossible to induce.  The set of system calls that can be overridden
1664 ** varies from one VFS to another, and from one version of the same VFS to the
1665 ** next.  Applications that use these interfaces must be prepared for any
1666 ** or all of these interfaces to be NULL or for their behavior to change
1667 ** from one release to the next.  Applications must not attempt to access
1668 ** any of these methods if the iVersion of the VFS is less than 3.
1669 */
1670 typedef struct sqlite3_vfs sqlite3_vfs;
1671 typedef void (*sqlite3_syscall_ptr)(void);
1672 struct sqlite3_vfs {
1673   int iVersion;            /* Structure version number (currently 3) */
1674   int szOsFile;            /* Size of subclassed sqlite3_file */
1675   int mxPathname;          /* Maximum file pathname length */
1676   sqlite3_vfs *pNext;      /* Next registered VFS */
1677   const char *zName;       /* Name of this virtual file system */
1678   void *pAppData;          /* Pointer to application-specific data */
1679   int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
1680                int flags, int *pOutFlags);
1681   int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1682   int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
1683   int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1684   void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1685   void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1686   void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
1687   void (*xDlClose)(sqlite3_vfs*, void*);
1688   int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1689   int (*xSleep)(sqlite3_vfs*, int microseconds);
1690   int (*xCurrentTime)(sqlite3_vfs*, double*);
1691   int (*xGetLastError)(sqlite3_vfs*, int, char *);
1692   /*
1693   ** The methods above are in version 1 of the sqlite_vfs object
1694   ** definition.  Those that follow are added in version 2 or later
1695   */
1696   int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
1697   /*
1698   ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
1699   ** Those below are for version 3 and greater.
1700   */
1701   int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
1702   sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
1703   const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
1704   /*
1705   ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
1706   ** New fields may be appended in figure versions.  The iVersion
1707   ** value will increment whenever this happens. 
1708   */
1709 };
1710
1711 /*
1712 ** CAPI3REF: Flags for the xAccess VFS method
1713 **
1714 ** These integer constants can be used as the third parameter to
1715 ** the xAccess method of an [sqlite3_vfs] object.  They determine
1716 ** what kind of permissions the xAccess method is looking for.
1717 ** With SQLITE_ACCESS_EXISTS, the xAccess method
1718 ** simply checks whether the file exists.
1719 ** With SQLITE_ACCESS_READWRITE, the xAccess method
1720 ** checks whether the named directory is both readable and writable
1721 ** (in other words, if files can be added, removed, and renamed within
1722 ** the directory).
1723 ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
1724 ** [temp_store_directory pragma], though this could change in a future
1725 ** release of SQLite.
1726 ** With SQLITE_ACCESS_READ, the xAccess method
1727 ** checks whether the file is readable.  The SQLITE_ACCESS_READ constant is
1728 ** currently unused, though it might be used in a future release of
1729 ** SQLite.
1730 */
1731 #define SQLITE_ACCESS_EXISTS    0
1732 #define SQLITE_ACCESS_READWRITE 1   /* Used by PRAGMA temp_store_directory */
1733 #define SQLITE_ACCESS_READ      2   /* Unused */
1734
1735 /*
1736 ** CAPI3REF: Flags for the xShmLock VFS method
1737 **
1738 ** These integer constants define the various locking operations
1739 ** allowed by the xShmLock method of [sqlite3_io_methods].  The
1740 ** following are the only legal combinations of flags to the
1741 ** xShmLock method:
1742 **
1743 ** <ul>
1744 ** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
1745 ** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
1746 ** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
1747 ** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
1748 ** </ul>
1749 **
1750 ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
1751 ** was given no the corresponding lock.  
1752 **
1753 ** The xShmLock method can transition between unlocked and SHARED or
1754 ** between unlocked and EXCLUSIVE.  It cannot transition between SHARED
1755 ** and EXCLUSIVE.
1756 */
1757 #define SQLITE_SHM_UNLOCK       1
1758 #define SQLITE_SHM_LOCK         2
1759 #define SQLITE_SHM_SHARED       4
1760 #define SQLITE_SHM_EXCLUSIVE    8
1761
1762 /*
1763 ** CAPI3REF: Maximum xShmLock index
1764 **
1765 ** The xShmLock method on [sqlite3_io_methods] may use values
1766 ** between 0 and this upper bound as its "offset" argument.
1767 ** The SQLite core will never attempt to acquire or release a
1768 ** lock outside of this range
1769 */
1770 #define SQLITE_SHM_NLOCK        8
1771
1772
1773 /*
1774 ** CAPI3REF: Initialize The SQLite Library
1775 **
1776 ** ^The sqlite3_initialize() routine initializes the
1777 ** SQLite library.  ^The sqlite3_shutdown() routine
1778 ** deallocates any resources that were allocated by sqlite3_initialize().
1779 ** These routines are designed to aid in process initialization and
1780 ** shutdown on embedded systems.  Workstation applications using
1781 ** SQLite normally do not need to invoke either of these routines.
1782 **
1783 ** A call to sqlite3_initialize() is an "effective" call if it is
1784 ** the first time sqlite3_initialize() is invoked during the lifetime of
1785 ** the process, or if it is the first time sqlite3_initialize() is invoked
1786 ** following a call to sqlite3_shutdown().  ^(Only an effective call
1787 ** of sqlite3_initialize() does any initialization.  All other calls
1788 ** are harmless no-ops.)^
1789 **
1790 ** A call to sqlite3_shutdown() is an "effective" call if it is the first
1791 ** call to sqlite3_shutdown() since the last sqlite3_initialize().  ^(Only
1792 ** an effective call to sqlite3_shutdown() does any deinitialization.
1793 ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
1794 **
1795 ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
1796 ** is not.  The sqlite3_shutdown() interface must only be called from a
1797 ** single thread.  All open [database connections] must be closed and all
1798 ** other SQLite resources must be deallocated prior to invoking
1799 ** sqlite3_shutdown().
1800 **
1801 ** Among other things, ^sqlite3_initialize() will invoke
1802 ** sqlite3_os_init().  Similarly, ^sqlite3_shutdown()
1803 ** will invoke sqlite3_os_end().
1804 **
1805 ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
1806 ** ^If for some reason, sqlite3_initialize() is unable to initialize
1807 ** the library (perhaps it is unable to allocate a needed resource such
1808 ** as a mutex) it returns an [error code] other than [SQLITE_OK].
1809 **
1810 ** ^The sqlite3_initialize() routine is called internally by many other
1811 ** SQLite interfaces so that an application usually does not need to
1812 ** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
1813 ** calls sqlite3_initialize() so the SQLite library will be automatically
1814 ** initialized when [sqlite3_open()] is called if it has not be initialized
1815 ** already.  ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
1816 ** compile-time option, then the automatic calls to sqlite3_initialize()
1817 ** are omitted and the application must call sqlite3_initialize() directly
1818 ** prior to using any other SQLite interface.  For maximum portability,
1819 ** it is recommended that applications always invoke sqlite3_initialize()
1820 ** directly prior to using any other SQLite interface.  Future releases
1821 ** of SQLite may require this.  In other words, the behavior exhibited
1822 ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
1823 ** default behavior in some future release of SQLite.
1824 **
1825 ** The sqlite3_os_init() routine does operating-system specific
1826 ** initialization of the SQLite library.  The sqlite3_os_end()
1827 ** routine undoes the effect of sqlite3_os_init().  Typical tasks
1828 ** performed by these routines include allocation or deallocation
1829 ** of static resources, initialization of global variables,
1830 ** setting up a default [sqlite3_vfs] module, or setting up
1831 ** a default configuration using [sqlite3_config()].
1832 **
1833 ** The application should never invoke either sqlite3_os_init()
1834 ** or sqlite3_os_end() directly.  The application should only invoke
1835 ** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
1836 ** interface is called automatically by sqlite3_initialize() and
1837 ** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
1838 ** implementations for sqlite3_os_init() and sqlite3_os_end()
1839 ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
1840 ** When [custom builds | built for other platforms]
1841 ** (using the [SQLITE_OS_OTHER=1] compile-time
1842 ** option) the application must supply a suitable implementation for
1843 ** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
1844 ** implementation of sqlite3_os_init() or sqlite3_os_end()
1845 ** must return [SQLITE_OK] on success and some other [error code] upon
1846 ** failure.
1847 */
1848 SQLITE_API int sqlite3_initialize(void);
1849 SQLITE_API int sqlite3_shutdown(void);
1850 SQLITE_API int sqlite3_os_init(void);
1851 SQLITE_API int sqlite3_os_end(void);
1852
1853 /*
1854 ** CAPI3REF: Configuring The SQLite Library
1855 **
1856 ** The sqlite3_config() interface is used to make global configuration
1857 ** changes to SQLite in order to tune SQLite to the specific needs of
1858 ** the application.  The default configuration is recommended for most
1859 ** applications and so this routine is usually not necessary.  It is
1860 ** provided to support rare applications with unusual needs.
1861 **
1862 ** The sqlite3_config() interface is not threadsafe.  The application
1863 ** must insure that no other SQLite interfaces are invoked by other
1864 ** threads while sqlite3_config() is running.  Furthermore, sqlite3_config()
1865 ** may only be invoked prior to library initialization using
1866 ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
1867 ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
1868 ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
1869 ** Note, however, that ^sqlite3_config() can be called as part of the
1870 ** implementation of an application-defined [sqlite3_os_init()].
1871 **
1872 ** The first argument to sqlite3_config() is an integer
1873 ** [configuration option] that determines
1874 ** what property of SQLite is to be configured.  Subsequent arguments
1875 ** vary depending on the [configuration option]
1876 ** in the first argument.
1877 **
1878 ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
1879 ** ^If the option is unknown or SQLite is unable to set the option
1880 ** then this routine returns a non-zero [error code].
1881 */
1882 SQLITE_API int sqlite3_config(int, ...);
1883
1884 /*
1885 ** CAPI3REF: Configure database connections
1886 **
1887 ** The sqlite3_db_config() interface is used to make configuration
1888 ** changes to a [database connection].  The interface is similar to
1889 ** [sqlite3_config()] except that the changes apply to a single
1890 ** [database connection] (specified in the first argument).
1891 **
1892 ** The second argument to sqlite3_db_config(D,V,...)  is the
1893 ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code 
1894 ** that indicates what aspect of the [database connection] is being configured.
1895 ** Subsequent arguments vary depending on the configuration verb.
1896 **
1897 ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
1898 ** the call is considered successful.
1899 */
1900 SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
1901
1902 /*
1903 ** CAPI3REF: Memory Allocation Routines
1904 **
1905 ** An instance of this object defines the interface between SQLite
1906 ** and low-level memory allocation routines.
1907 **
1908 ** This object is used in only one place in the SQLite interface.
1909 ** A pointer to an instance of this object is the argument to
1910 ** [sqlite3_config()] when the configuration option is
1911 ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].  
1912 ** By creating an instance of this object
1913 ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
1914 ** during configuration, an application can specify an alternative
1915 ** memory allocation subsystem for SQLite to use for all of its
1916 ** dynamic memory needs.
1917 **
1918 ** Note that SQLite comes with several [built-in memory allocators]
1919 ** that are perfectly adequate for the overwhelming majority of applications
1920 ** and that this object is only useful to a tiny minority of applications
1921 ** with specialized memory allocation requirements.  This object is
1922 ** also used during testing of SQLite in order to specify an alternative
1923 ** memory allocator that simulates memory out-of-memory conditions in
1924 ** order to verify that SQLite recovers gracefully from such
1925 ** conditions.
1926 **
1927 ** The xMalloc, xRealloc, and xFree methods must work like the
1928 ** malloc(), realloc() and free() functions from the standard C library.
1929 ** ^SQLite guarantees that the second argument to
1930 ** xRealloc is always a value returned by a prior call to xRoundup.
1931 **
1932 ** xSize should return the allocated size of a memory allocation
1933 ** previously obtained from xMalloc or xRealloc.  The allocated size
1934 ** is always at least as big as the requested size but may be larger.
1935 **
1936 ** The xRoundup method returns what would be the allocated size of
1937 ** a memory allocation given a particular requested size.  Most memory
1938 ** allocators round up memory allocations at least to the next multiple
1939 ** of 8.  Some allocators round up to a larger multiple or to a power of 2.
1940 ** Every memory allocation request coming in through [sqlite3_malloc()]
1941 ** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0, 
1942 ** that causes the corresponding memory allocation to fail.
1943 **
1944 ** The xInit method initializes the memory allocator.  (For example,
1945 ** it might allocate any require mutexes or initialize internal data
1946 ** structures.  The xShutdown method is invoked (indirectly) by
1947 ** [sqlite3_shutdown()] and should deallocate any resources acquired
1948 ** by xInit.  The pAppData pointer is used as the only parameter to
1949 ** xInit and xShutdown.
1950 **
1951 ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
1952 ** the xInit method, so the xInit method need not be threadsafe.  The
1953 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
1954 ** not need to be threadsafe either.  For all other methods, SQLite
1955 ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
1956 ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
1957 ** it is by default) and so the methods are automatically serialized.
1958 ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
1959 ** methods must be threadsafe or else make their own arrangements for
1960 ** serialization.
1961 **
1962 ** SQLite will never invoke xInit() more than once without an intervening
1963 ** call to xShutdown().
1964 */
1965 typedef struct sqlite3_mem_methods sqlite3_mem_methods;
1966 struct sqlite3_mem_methods {
1967   void *(*xMalloc)(int);         /* Memory allocation function */
1968   void (*xFree)(void*);          /* Free a prior allocation */
1969   void *(*xRealloc)(void*,int);  /* Resize an allocation */
1970   int (*xSize)(void*);           /* Return the size of an allocation */
1971   int (*xRoundup)(int);          /* Round up request size to allocation size */
1972   int (*xInit)(void*);           /* Initialize the memory allocator */
1973   void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
1974   void *pAppData;                /* Argument to xInit() and xShutdown() */
1975 };
1976
1977 /*
1978 ** CAPI3REF: Configuration Options
1979 ** KEYWORDS: {configuration option}
1980 **
1981 ** These constants are the available integer configuration options that
1982 ** can be passed as the first argument to the [sqlite3_config()] interface.
1983 **
1984 ** New configuration options may be added in future releases of SQLite.
1985 ** Existing configuration options might be discontinued.  Applications
1986 ** should check the return code from [sqlite3_config()] to make sure that
1987 ** the call worked.  The [sqlite3_config()] interface will return a
1988 ** non-zero [error code] if a discontinued or unsupported configuration option
1989 ** is invoked.
1990 **
1991 ** <dl>
1992 ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
1993 ** <dd>There are no arguments to this option.  ^This option sets the
1994 ** [threading mode] to Single-thread.  In other words, it disables
1995 ** all mutexing and puts SQLite into a mode where it can only be used
1996 ** by a single thread.   ^If SQLite is compiled with
1997 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1998 ** it is not possible to change the [threading mode] from its default
1999 ** value of Single-thread and so [sqlite3_config()] will return 
2000 ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
2001 ** configuration option.</dd>
2002 **
2003 ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
2004 ** <dd>There are no arguments to this option.  ^This option sets the
2005 ** [threading mode] to Multi-thread.  In other words, it disables
2006 ** mutexing on [database connection] and [prepared statement] objects.
2007 ** The application is responsible for serializing access to
2008 ** [database connections] and [prepared statements].  But other mutexes
2009 ** are enabled so that SQLite will be safe to use in a multi-threaded
2010 ** environment as long as no two threads attempt to use the same
2011 ** [database connection] at the same time.  ^If SQLite is compiled with
2012 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2013 ** it is not possible to set the Multi-thread [threading mode] and
2014 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
2015 ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
2016 **
2017 ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
2018 ** <dd>There are no arguments to this option.  ^This option sets the
2019 ** [threading mode] to Serialized. In other words, this option enables
2020 ** all mutexes including the recursive
2021 ** mutexes on [database connection] and [prepared statement] objects.
2022 ** In this mode (which is the default when SQLite is compiled with
2023 ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
2024 ** to [database connections] and [prepared statements] so that the
2025 ** application is free to use the same [database connection] or the
2026 ** same [prepared statement] in different threads at the same time.
2027 ** ^If SQLite is compiled with
2028 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2029 ** it is not possible to set the Serialized [threading mode] and
2030 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
2031 ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
2032 **
2033 ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
2034 ** <dd> ^(This option takes a single argument which is a pointer to an
2035 ** instance of the [sqlite3_mem_methods] structure.  The argument specifies
2036 ** alternative low-level memory allocation routines to be used in place of
2037 ** the memory allocation routines built into SQLite.)^ ^SQLite makes
2038 ** its own private copy of the content of the [sqlite3_mem_methods] structure
2039 ** before the [sqlite3_config()] call returns.</dd>
2040 **
2041 ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
2042 ** <dd> ^(This option takes a single argument which is a pointer to an
2043 ** instance of the [sqlite3_mem_methods] structure.  The [sqlite3_mem_methods]
2044 ** structure is filled with the currently defined memory allocation routines.)^
2045 ** This option can be used to overload the default memory allocation
2046 ** routines with a wrapper that simulations memory allocation failure or
2047 ** tracks memory usage, for example. </dd>
2048 **
2049 ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
2050 ** <dd> ^This option takes single argument of type int, interpreted as a 
2051 ** boolean, which enables or disables the collection of memory allocation 
2052 ** statistics. ^(When memory allocation statistics are disabled, the 
2053 ** following SQLite interfaces become non-operational:
2054 **   <ul>
2055 **   <li> [sqlite3_memory_used()]
2056 **   <li> [sqlite3_memory_highwater()]
2057 **   <li> [sqlite3_soft_heap_limit64()]
2058 **   <li> [sqlite3_status()]
2059 **   </ul>)^
2060 ** ^Memory allocation statistics are enabled by default unless SQLite is
2061 ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
2062 ** allocation statistics are disabled by default.
2063 ** </dd>
2064 **
2065 ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
2066 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
2067 ** scratch memory.  There are three arguments:  A pointer an 8-byte
2068 ** aligned memory buffer from which the scratch allocations will be
2069 ** drawn, the size of each scratch allocation (sz),
2070 ** and the maximum number of scratch allocations (N).  The sz
2071 ** argument must be a multiple of 16.
2072 ** The first argument must be a pointer to an 8-byte aligned buffer
2073 ** of at least sz*N bytes of memory.
2074 ** ^SQLite will use no more than two scratch buffers per thread.  So
2075 ** N should be set to twice the expected maximum number of threads.
2076 ** ^SQLite will never require a scratch buffer that is more than 6
2077 ** times the database page size. ^If SQLite needs needs additional
2078 ** scratch memory beyond what is provided by this configuration option, then 
2079 ** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
2080 **
2081 ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
2082 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
2083 ** the database page cache with the default page cache implementation.  
2084 ** This configuration should not be used if an application-define page
2085 ** cache implementation is loaded using the SQLITE_CONFIG_PCACHE2 option.
2086 ** There are three arguments to this option: A pointer to 8-byte aligned
2087 ** memory, the size of each page buffer (sz), and the number of pages (N).
2088 ** The sz argument should be the size of the largest database page
2089 ** (a power of two between 512 and 32768) plus a little extra for each
2090 ** page header.  ^The page header size is 20 to 40 bytes depending on
2091 ** the host architecture.  ^It is harmless, apart from the wasted memory,
2092 ** to make sz a little too large.  The first
2093 ** argument should point to an allocation of at least sz*N bytes of memory.
2094 ** ^SQLite will use the memory provided by the first argument to satisfy its
2095 ** memory needs for the first N pages that it adds to cache.  ^If additional
2096 ** page cache memory is needed beyond what is provided by this option, then
2097 ** SQLite goes to [sqlite3_malloc()] for the additional storage space.
2098 ** The pointer in the first argument must
2099 ** be aligned to an 8-byte boundary or subsequent behavior of SQLite
2100 ** will be undefined.</dd>
2101 **
2102 ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
2103 ** <dd> ^This option specifies a static memory buffer that SQLite will use
2104 ** for all of its dynamic memory allocation needs beyond those provided
2105 ** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
2106 ** There are three arguments: An 8-byte aligned pointer to the memory,
2107 ** the number of bytes in the memory buffer, and the minimum allocation size.
2108 ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
2109 ** to using its default memory allocator (the system malloc() implementation),
2110 ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the
2111 ** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
2112 ** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
2113 ** allocator is engaged to handle all of SQLites memory allocation needs.
2114 ** The first pointer (the memory pointer) must be aligned to an 8-byte
2115 ** boundary or subsequent behavior of SQLite will be undefined.
2116 ** The minimum allocation size is capped at 2**12. Reasonable values
2117 ** for the minimum allocation size are 2**5 through 2**8.</dd>
2118 **
2119 ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
2120 ** <dd> ^(This option takes a single argument which is a pointer to an
2121 ** instance of the [sqlite3_mutex_methods] structure.  The argument specifies
2122 ** alternative low-level mutex routines to be used in place
2123 ** the mutex routines built into SQLite.)^  ^SQLite makes a copy of the
2124 ** content of the [sqlite3_mutex_methods] structure before the call to
2125 ** [sqlite3_config()] returns. ^If SQLite is compiled with
2126 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2127 ** the entire mutexing subsystem is omitted from the build and hence calls to
2128 ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
2129 ** return [SQLITE_ERROR].</dd>
2130 **
2131 ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
2132 ** <dd> ^(This option takes a single argument which is a pointer to an
2133 ** instance of the [sqlite3_mutex_methods] structure.  The
2134 ** [sqlite3_mutex_methods]
2135 ** structure is filled with the currently defined mutex routines.)^
2136 ** This option can be used to overload the default mutex allocation
2137 ** routines with a wrapper used to track mutex usage for performance
2138 ** profiling or testing, for example.   ^If SQLite is compiled with
2139 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2140 ** the entire mutexing subsystem is omitted from the build and hence calls to
2141 ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
2142 ** return [SQLITE_ERROR].</dd>
2143 **
2144 ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
2145 ** <dd> ^(This option takes two arguments that determine the default
2146 ** memory allocation for the lookaside memory allocator on each
2147 ** [database connection].  The first argument is the
2148 ** size of each lookaside buffer slot and the second is the number of
2149 ** slots allocated to each database connection.)^  ^(This option sets the
2150 ** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
2151 ** verb to [sqlite3_db_config()] can be used to change the lookaside
2152 ** configuration on individual connections.)^ </dd>
2153 **
2154 ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
2155 ** <dd> ^(This option takes a single argument which is a pointer to
2156 ** an [sqlite3_pcache_methods2] object.  This object specifies the interface
2157 ** to a custom page cache implementation.)^  ^SQLite makes a copy of the
2158 ** object and uses it for page cache memory allocations.</dd>
2159 **
2160 ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
2161 ** <dd> ^(This option takes a single argument which is a pointer to an
2162 ** [sqlite3_pcache_methods2] object.  SQLite copies of the current
2163 ** page cache implementation into that object.)^ </dd>
2164 **
2165 ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
2166 ** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
2167 ** global [error log].
2168 ** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
2169 ** function with a call signature of void(*)(void*,int,const char*), 
2170 ** and a pointer to void. ^If the function pointer is not NULL, it is
2171 ** invoked by [sqlite3_log()] to process each logging event.  ^If the
2172 ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
2173 ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
2174 ** passed through as the first parameter to the application-defined logger
2175 ** function whenever that function is invoked.  ^The second parameter to
2176 ** the logger function is a copy of the first parameter to the corresponding
2177 ** [sqlite3_log()] call and is intended to be a [result code] or an
2178 ** [extended result code].  ^The third parameter passed to the logger is
2179 ** log message after formatting via [sqlite3_snprintf()].
2180 ** The SQLite logging interface is not reentrant; the logger function
2181 ** supplied by the application must not invoke any SQLite interface.
2182 ** In a multi-threaded application, the application-defined logger
2183 ** function must be threadsafe. </dd>
2184 **
2185 ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
2186 ** <dd> This option takes a single argument of type int. If non-zero, then
2187 ** URI handling is globally enabled. If the parameter is zero, then URI handling
2188 ** is globally disabled. If URI handling is globally enabled, all filenames
2189 ** passed to [sqlite3_open()], [sqlite3_open_v2()], [sqlite3_open16()] or
2190 ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
2191 ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
2192 ** connection is opened. If it is globally disabled, filenames are
2193 ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
2194 ** database connection is opened. By default, URI handling is globally
2195 ** disabled. The default value may be changed by compiling with the
2196 ** [SQLITE_USE_URI] symbol defined.
2197 **
2198 ** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
2199 ** <dd> This option takes a single integer argument which is interpreted as
2200 ** a boolean in order to enable or disable the use of covering indices for
2201 ** full table scans in the query optimizer.  The default setting is determined
2202 ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
2203 ** if that compile-time option is omitted.
2204 ** The ability to disable the use of covering indices for full table scans
2205 ** is because some incorrectly coded legacy applications might malfunction
2206 ** malfunction when the optimization is enabled.  Providing the ability to
2207 ** disable the optimization allows the older, buggy application code to work
2208 ** without change even with newer versions of SQLite.
2209 **
2210 ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
2211 ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
2212 ** <dd> These options are obsolete and should not be used by new code.
2213 ** They are retained for backwards compatibility but are now no-ops.
2214 ** </dd>
2215 **
2216 ** [[SQLITE_CONFIG_SQLLOG]]
2217 ** <dt>SQLITE_CONFIG_SQLLOG
2218 ** <dd>This option is only available if sqlite is compiled with the
2219 ** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
2220 ** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
2221 ** The second should be of type (void*). The callback is invoked by the library
2222 ** in three separate circumstances, identified by the value passed as the
2223 ** fourth parameter. If the fourth parameter is 0, then the database connection
2224 ** passed as the second argument has just been opened. The third argument
2225 ** points to a buffer containing the name of the main database file. If the
2226 ** fourth parameter is 1, then the SQL statement that the third parameter
2227 ** points to has just been executed. Or, if the fourth parameter is 2, then
2228 ** the connection being passed as the second parameter is being closed. The
2229 ** third parameter is passed NULL In this case.  An example of using this
2230 ** configuration option can be seen in the "test_sqllog.c" source file in
2231 ** the canonical SQLite source tree.</dd>
2232 **
2233 ** [[SQLITE_CONFIG_MMAP_SIZE]]
2234 ** <dt>SQLITE_CONFIG_MMAP_SIZE
2235 ** <dd>SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
2236 ** that are the default mmap size limit (the default setting for
2237 ** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
2238 ** The default setting can be overridden by each database connection using
2239 ** either the [PRAGMA mmap_size] command, or by using the
2240 ** [SQLITE_FCNTL_MMAP_SIZE] file control.  The maximum allowed mmap size
2241 ** cannot be changed at run-time.  Nor may the maximum allowed mmap size
2242 ** exceed the compile-time maximum mmap size set by the
2243 ** [SQLITE_MAX_MMAP_SIZE] compile-time option.  
2244 ** If either argument to this option is negative, then that argument is
2245 ** changed to its compile-time default.
2246 ** </dl>
2247 */
2248 #define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
2249 #define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
2250 #define SQLITE_CONFIG_SERIALIZED    3  /* nil */
2251 #define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
2252 #define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
2253 #define SQLITE_CONFIG_SCRATCH       6  /* void*, int sz, int N */
2254 #define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
2255 #define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
2256 #define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
2257 #define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
2258 #define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
2259 /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ 
2260 #define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
2261 #define SQLITE_CONFIG_PCACHE       14  /* no-op */
2262 #define SQLITE_CONFIG_GETPCACHE    15  /* no-op */
2263 #define SQLITE_CONFIG_LOG          16  /* xFunc, void* */
2264 #define SQLITE_CONFIG_URI          17  /* int */
2265 #define SQLITE_CONFIG_PCACHE2      18  /* sqlite3_pcache_methods2* */
2266 #define SQLITE_CONFIG_GETPCACHE2   19  /* sqlite3_pcache_methods2* */
2267 #define SQLITE_CONFIG_COVERING_INDEX_SCAN 20  /* int */
2268 #define SQLITE_CONFIG_SQLLOG       21  /* xSqllog, void* */
2269 #define SQLITE_CONFIG_MMAP_SIZE    22  /* sqlite3_int64, sqlite3_int64 */
2270
2271 /*
2272 ** CAPI3REF: Database Connection Configuration Options
2273 **
2274 ** These constants are the available integer configuration options that
2275 ** can be passed as the second argument to the [sqlite3_db_config()] interface.
2276 **
2277 ** New configuration options may be added in future releases of SQLite.
2278 ** Existing configuration options might be discontinued.  Applications
2279 ** should check the return code from [sqlite3_db_config()] to make sure that
2280 ** the call worked.  ^The [sqlite3_db_config()] interface will return a
2281 ** non-zero [error code] if a discontinued or unsupported configuration option
2282 ** is invoked.
2283 **
2284 ** <dl>
2285 ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
2286 ** <dd> ^This option takes three additional arguments that determine the 
2287 ** [lookaside memory allocator] configuration for the [database connection].
2288 ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
2289 ** pointer to a memory buffer to use for lookaside memory.
2290 ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
2291 ** may be NULL in which case SQLite will allocate the
2292 ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
2293 ** size of each lookaside buffer slot.  ^The third argument is the number of
2294 ** slots.  The size of the buffer in the first argument must be greater than
2295 ** or equal to the product of the second and third arguments.  The buffer
2296 ** must be aligned to an 8-byte boundary.  ^If the second argument to
2297 ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
2298 ** rounded down to the next smaller multiple of 8.  ^(The lookaside memory
2299 ** configuration for a database connection can only be changed when that
2300 ** connection is not currently using lookaside memory, or in other words
2301 ** when the "current value" returned by
2302 ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
2303 ** Any attempt to change the lookaside memory configuration when lookaside
2304 ** memory is in use leaves the configuration unchanged and returns 
2305 ** [SQLITE_BUSY].)^</dd>
2306 **
2307 ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
2308 ** <dd> ^This option is used to enable or disable the enforcement of
2309 ** [foreign key constraints].  There should be two additional arguments.
2310 ** The first argument is an integer which is 0 to disable FK enforcement,
2311 ** positive to enable FK enforcement or negative to leave FK enforcement
2312 ** unchanged.  The second parameter is a pointer to an integer into which
2313 ** is written 0 or 1 to indicate whether FK enforcement is off or on
2314 ** following this call.  The second parameter may be a NULL pointer, in
2315 ** which case the FK enforcement setting is not reported back. </dd>
2316 **
2317 ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
2318 ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
2319 ** There should be two additional arguments.
2320 ** The first argument is an integer which is 0 to disable triggers,
2321 ** positive to enable triggers or negative to leave the setting unchanged.
2322 ** The second parameter is a pointer to an integer into which
2323 ** is written 0 or 1 to indicate whether triggers are disabled or enabled
2324 ** following this call.  The second parameter may be a NULL pointer, in
2325 ** which case the trigger setting is not reported back. </dd>
2326 **
2327 ** </dl>
2328 */
2329 #define SQLITE_DBCONFIG_LOOKASIDE       1001  /* void* int int */
2330 #define SQLITE_DBCONFIG_ENABLE_FKEY     1002  /* int int* */
2331 #define SQLITE_DBCONFIG_ENABLE_TRIGGER  1003  /* int int* */
2332
2333
2334 /*
2335 ** CAPI3REF: Enable Or Disable Extended Result Codes
2336 **
2337 ** ^The sqlite3_extended_result_codes() routine enables or disables the
2338 ** [extended result codes] feature of SQLite. ^The extended result
2339 ** codes are disabled by default for historical compatibility.
2340 */
2341 SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
2342
2343 /*
2344 ** CAPI3REF: Last Insert Rowid
2345 **
2346 ** ^Each entry in an SQLite table has a unique 64-bit signed
2347 ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
2348 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
2349 ** names are not also used by explicitly declared columns. ^If
2350 ** the table has a column of type [INTEGER PRIMARY KEY] then that column
2351 ** is another alias for the rowid.
2352 **
2353 ** ^This routine returns the [rowid] of the most recent
2354 ** successful [INSERT] into the database from the [database connection]
2355 ** in the first argument.  ^As of SQLite version 3.7.7, this routines
2356 ** records the last insert rowid of both ordinary tables and [virtual tables].
2357 ** ^If no successful [INSERT]s
2358 ** have ever occurred on that database connection, zero is returned.
2359 **
2360 ** ^(If an [INSERT] occurs within a trigger or within a [virtual table]
2361 ** method, then this routine will return the [rowid] of the inserted
2362 ** row as long as the trigger or virtual table method is running.
2363 ** But once the trigger or virtual table method ends, the value returned 
2364 ** by this routine reverts to what it was before the trigger or virtual
2365 ** table method began.)^
2366 **
2367 ** ^An [INSERT] that fails due to a constraint violation is not a
2368 ** successful [INSERT] and does not change the value returned by this
2369 ** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
2370 ** and INSERT OR ABORT make no changes to the return value of this
2371 ** routine when their insertion fails.  ^(When INSERT OR REPLACE
2372 ** encounters a constraint violation, it does not fail.  The
2373 ** INSERT continues to completion after deleting rows that caused
2374 ** the constraint problem so INSERT OR REPLACE will always change
2375 ** the return value of this interface.)^
2376 **
2377 ** ^For the purposes of this routine, an [INSERT] is considered to
2378 ** be successful even if it is subsequently rolled back.
2379 **
2380 ** This function is accessible to SQL statements via the
2381 ** [last_insert_rowid() SQL function].
2382 **
2383 ** If a separate thread performs a new [INSERT] on the same
2384 ** database connection while the [sqlite3_last_insert_rowid()]
2385 ** function is running and thus changes the last insert [rowid],
2386 ** then the value returned by [sqlite3_last_insert_rowid()] is
2387 ** unpredictable and might not equal either the old or the new
2388 ** last insert [rowid].
2389 */
2390 SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
2391
2392 /*
2393 ** CAPI3REF: Count The Number Of Rows Modified
2394 **
2395 ** ^This function returns the number of database rows that were changed
2396 ** or inserted or deleted by the most recently completed SQL statement
2397 ** on the [database connection] specified by the first parameter.
2398 ** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
2399 ** or [DELETE] statement are counted.  Auxiliary changes caused by
2400 ** triggers or [foreign key actions] are not counted.)^ Use the
2401 ** [sqlite3_total_changes()] function to find the total number of changes
2402 ** including changes caused by triggers and foreign key actions.
2403 **
2404 ** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
2405 ** are not counted.  Only real table changes are counted.
2406 **
2407 ** ^(A "row change" is a change to a single row of a single table
2408 ** caused by an INSERT, DELETE, or UPDATE statement.  Rows that
2409 ** are changed as side effects of [REPLACE] constraint resolution,
2410 ** rollback, ABORT processing, [DROP TABLE], or by any other
2411 ** mechanisms do not count as direct row changes.)^
2412 **
2413 ** A "trigger context" is a scope of execution that begins and
2414 ** ends with the script of a [CREATE TRIGGER | trigger]. 
2415 ** Most SQL statements are
2416 ** evaluated outside of any trigger.  This is the "top level"
2417 ** trigger context.  If a trigger fires from the top level, a
2418 ** new trigger context is entered for the duration of that one
2419 ** trigger.  Subtriggers create subcontexts for their duration.
2420 **
2421 ** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
2422 ** not create a new trigger context.
2423 **
2424 ** ^This function returns the number of direct row changes in the
2425 ** most recent INSERT, UPDATE, or DELETE statement within the same
2426 ** trigger context.
2427 **
2428 ** ^Thus, when called from the top level, this function returns the
2429 ** number of changes in the most recent INSERT, UPDATE, or DELETE
2430 ** that also occurred at the top level.  ^(Within the body of a trigger,
2431 ** the sqlite3_changes() interface can be called to find the number of
2432 ** changes in the most recently completed INSERT, UPDATE, or DELETE
2433 ** statement within the body of the same trigger.
2434 ** However, the number returned does not include changes
2435 ** caused by subtriggers since those have their own context.)^
2436 **
2437 ** See also the [sqlite3_total_changes()] interface, the
2438 ** [count_changes pragma], and the [changes() SQL function].
2439 **
2440 ** If a separate thread makes changes on the same database connection
2441 ** while [sqlite3_changes()] is running then the value returned
2442 ** is unpredictable and not meaningful.
2443 */
2444 SQLITE_API int sqlite3_changes(sqlite3*);
2445
2446 /*
2447 ** CAPI3REF: Total Number Of Rows Modified
2448 **
2449 ** ^This function returns the number of row changes caused by [INSERT],
2450 ** [UPDATE] or [DELETE] statements since the [database connection] was opened.
2451 ** ^(The count returned by sqlite3_total_changes() includes all changes
2452 ** from all [CREATE TRIGGER | trigger] contexts and changes made by
2453 ** [foreign key actions]. However,
2454 ** the count does not include changes used to implement [REPLACE] constraints,
2455 ** do rollbacks or ABORT processing, or [DROP TABLE] processing.  The
2456 ** count does not include rows of views that fire an [INSTEAD OF trigger],
2457 ** though if the INSTEAD OF trigger makes changes of its own, those changes 
2458 ** are counted.)^
2459 ** ^The sqlite3_total_changes() function counts the changes as soon as
2460 ** the statement that makes them is completed (when the statement handle
2461 ** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).
2462 **
2463 ** See also the [sqlite3_changes()] interface, the
2464 ** [count_changes pragma], and the [total_changes() SQL function].
2465 **
2466 ** If a separate thread makes changes on the same database connection
2467 ** while [sqlite3_total_changes()] is running then the value
2468 ** returned is unpredictable and not meaningful.
2469 */
2470 SQLITE_API int sqlite3_total_changes(sqlite3*);
2471
2472 /*
2473 ** CAPI3REF: Interrupt A Long-Running Query
2474 **
2475 ** ^This function causes any pending database operation to abort and
2476 ** return at its earliest opportunity. This routine is typically
2477 ** called in response to a user action such as pressing "Cancel"
2478 ** or Ctrl-C where the user wants a long query operation to halt
2479 ** immediately.
2480 **
2481 ** ^It is safe to call this routine from a thread different from the
2482 ** thread that is currently running the database operation.  But it
2483 ** is not safe to call this routine with a [database connection] that
2484 ** is closed or might close before sqlite3_interrupt() returns.
2485 **
2486 ** ^If an SQL operation is very nearly finished at the time when
2487 ** sqlite3_interrupt() is called, then it might not have an opportunity
2488 ** to be interrupted and might continue to completion.
2489 **
2490 ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
2491 ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
2492 ** that is inside an explicit transaction, then the entire transaction
2493 ** will be rolled back automatically.
2494 **
2495 ** ^The sqlite3_interrupt(D) call is in effect until all currently running
2496 ** SQL statements on [database connection] D complete.  ^Any new SQL statements
2497 ** that are started after the sqlite3_interrupt() call and before the 
2498 ** running statements reaches zero are interrupted as if they had been
2499 ** running prior to the sqlite3_interrupt() call.  ^New SQL statements
2500 ** that are started after the running statement count reaches zero are
2501 ** not effected by the sqlite3_interrupt().
2502 ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
2503 ** SQL statements is a no-op and has no effect on SQL statements
2504 ** that are started after the sqlite3_interrupt() call returns.
2505 **
2506 ** If the database connection closes while [sqlite3_interrupt()]
2507 ** is running then bad things will likely happen.
2508 */
2509 SQLITE_API void sqlite3_interrupt(sqlite3*);
2510
2511 /*
2512 ** CAPI3REF: Determine If An SQL Statement Is Complete
2513 **
2514 ** These routines are useful during command-line input to determine if the
2515 ** currently entered text seems to form a complete SQL statement or
2516 ** if additional input is needed before sending the text into
2517 ** SQLite for parsing.  ^These routines return 1 if the input string
2518 ** appears to be a complete SQL statement.  ^A statement is judged to be
2519 ** complete if it ends with a semicolon token and is not a prefix of a
2520 ** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within
2521 ** string literals or quoted identifier names or comments are not
2522 ** independent tokens (they are part of the token in which they are
2523 ** embedded) and thus do not count as a statement terminator.  ^Whitespace
2524 ** and comments that follow the final semicolon are ignored.
2525 **
2526 ** ^These routines return 0 if the statement is incomplete.  ^If a
2527 ** memory allocation fails, then SQLITE_NOMEM is returned.
2528 **
2529 ** ^These routines do not parse the SQL statements thus
2530 ** will not detect syntactically incorrect SQL.
2531 **
2532 ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior 
2533 ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
2534 ** automatically by sqlite3_complete16().  If that initialization fails,
2535 ** then the return value from sqlite3_complete16() will be non-zero
2536 ** regardless of whether or not the input SQL is complete.)^
2537 **
2538 ** The input to [sqlite3_complete()] must be a zero-terminated
2539 ** UTF-8 string.
2540 **
2541 ** The input to [sqlite3_complete16()] must be a zero-terminated
2542 ** UTF-16 string in native byte order.
2543 */
2544 SQLITE_API int sqlite3_complete(const char *sql);
2545 SQLITE_API int sqlite3_complete16(const void *sql);
2546
2547 /*
2548 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
2549 **
2550 ** ^This routine sets a callback function that might be invoked whenever
2551 ** an attempt is made to open a database table that another thread
2552 ** or process has locked.
2553 **
2554 ** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
2555 ** is returned immediately upon encountering the lock.  ^If the busy callback
2556 ** is not NULL, then the callback might be invoked with two arguments.
2557 **
2558 ** ^The first argument to the busy handler is a copy of the void* pointer which
2559 ** is the third argument to sqlite3_busy_handler().  ^The second argument to
2560 ** the busy handler callback is the number of times that the busy handler has
2561 ** been invoked for this locking event.  ^If the
2562 ** busy callback returns 0, then no additional attempts are made to
2563 ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
2564 ** ^If the callback returns non-zero, then another attempt
2565 ** is made to open the database for reading and the cycle repeats.
2566 **
2567 ** The presence of a busy handler does not guarantee that it will be invoked
2568 ** when there is lock contention. ^If SQLite determines that invoking the busy
2569 ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
2570 ** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
2571 ** Consider a scenario where one process is holding a read lock that
2572 ** it is trying to promote to a reserved lock and
2573 ** a second process is holding a reserved lock that it is trying
2574 ** to promote to an exclusive lock.  The first process cannot proceed
2575 ** because it is blocked by the second and the second process cannot
2576 ** proceed because it is blocked by the first.  If both processes
2577 ** invoke the busy handlers, neither will make any progress.  Therefore,
2578 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
2579 ** will induce the first process to release its read lock and allow
2580 ** the second process to proceed.
2581 **
2582 ** ^The default busy callback is NULL.
2583 **
2584 ** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
2585 ** when SQLite is in the middle of a large transaction where all the
2586 ** changes will not fit into the in-memory cache.  SQLite will
2587 ** already hold a RESERVED lock on the database file, but it needs
2588 ** to promote this lock to EXCLUSIVE so that it can spill cache
2589 ** pages into the database file without harm to concurrent
2590 ** readers.  ^If it is unable to promote the lock, then the in-memory
2591 ** cache will be left in an inconsistent state and so the error
2592 ** code is promoted from the relatively benign [SQLITE_BUSY] to
2593 ** the more severe [SQLITE_IOERR_BLOCKED].  ^This error code promotion
2594 ** forces an automatic rollback of the changes.  See the
2595 ** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
2596 ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
2597 ** this is important.
2598 **
2599 ** ^(There can only be a single busy handler defined for each
2600 ** [database connection].  Setting a new busy handler clears any
2601 ** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]
2602 ** will also set or clear the busy handler.
2603 **
2604 ** The busy callback should not take any actions which modify the
2605 ** database connection that invoked the busy handler.  Any such actions
2606 ** result in undefined behavior.
2607 ** 
2608 ** A busy handler must not close the database connection
2609 ** or [prepared statement] that invoked the busy handler.
2610 */
2611 SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
2612
2613 /*
2614 ** CAPI3REF: Set A Busy Timeout
2615 **
2616 ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
2617 ** for a specified amount of time when a table is locked.  ^The handler
2618 ** will sleep multiple times until at least "ms" milliseconds of sleeping
2619 ** have accumulated.  ^After at least "ms" milliseconds of sleeping,
2620 ** the handler returns 0 which causes [sqlite3_step()] to return
2621 ** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
2622 **
2623 ** ^Calling this routine with an argument less than or equal to zero
2624 ** turns off all busy handlers.
2625 **
2626 ** ^(There can only be a single busy handler for a particular
2627 ** [database connection] any any given moment.  If another busy handler
2628 ** was defined  (using [sqlite3_busy_handler()]) prior to calling
2629 ** this routine, that other busy handler is cleared.)^
2630 */
2631 SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
2632
2633 /*
2634 ** CAPI3REF: Convenience Routines For Running Queries
2635 **
2636 ** This is a legacy interface that is preserved for backwards compatibility.
2637 ** Use of this interface is not recommended.
2638 **
2639 ** Definition: A <b>result table</b> is memory data structure created by the
2640 ** [sqlite3_get_table()] interface.  A result table records the
2641 ** complete query results from one or more queries.
2642 **
2643 ** The table conceptually has a number of rows and columns.  But
2644 ** these numbers are not part of the result table itself.  These
2645 ** numbers are obtained separately.  Let N be the number of rows
2646 ** and M be the number of columns.
2647 **
2648 ** A result table is an array of pointers to zero-terminated UTF-8 strings.
2649 ** There are (N+1)*M elements in the array.  The first M pointers point
2650 ** to zero-terminated strings that  contain the names of the columns.
2651 ** The remaining entries all point to query results.  NULL values result
2652 ** in NULL pointers.  All other values are in their UTF-8 zero-terminated
2653 ** string representation as returned by [sqlite3_column_text()].
2654 **
2655 ** A result table might consist of one or more memory allocations.
2656 ** It is not safe to pass a result table directly to [sqlite3_free()].
2657 ** A result table should be deallocated using [sqlite3_free_table()].
2658 **
2659 ** ^(As an example of the result table format, suppose a query result
2660 ** is as follows:
2661 **
2662 ** <blockquote><pre>
2663 **        Name        | Age
2664 **        -----------------------
2665 **        Alice       | 43
2666 **        Bob         | 28
2667 **        Cindy       | 21
2668 ** </pre></blockquote>
2669 **
2670 ** There are two column (M==2) and three rows (N==3).  Thus the
2671 ** result table has 8 entries.  Suppose the result table is stored
2672 ** in an array names azResult.  Then azResult holds this content:
2673 **
2674 ** <blockquote><pre>
2675 **        azResult&#91;0] = "Name";
2676 **        azResult&#91;1] = "Age";
2677 **        azResult&#91;2] = "Alice";
2678 **        azResult&#91;3] = "43";
2679 **        azResult&#91;4] = "Bob";
2680 **        azResult&#91;5] = "28";
2681 **        azResult&#91;6] = "Cindy";
2682 **        azResult&#91;7] = "21";
2683 ** </pre></blockquote>)^
2684 **
2685 ** ^The sqlite3_get_table() function evaluates one or more
2686 ** semicolon-separated SQL statements in the zero-terminated UTF-8
2687 ** string of its 2nd parameter and returns a result table to the
2688 ** pointer given in its 3rd parameter.
2689 **
2690 ** After the application has finished with the result from sqlite3_get_table(),
2691 ** it must pass the result table pointer to sqlite3_free_table() in order to
2692 ** release the memory that was malloced.  Because of the way the
2693 ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
2694 ** function must not try to call [sqlite3_free()] directly.  Only
2695 ** [sqlite3_free_table()] is able to release the memory properly and safely.
2696 **
2697 ** The sqlite3_get_table() interface is implemented as a wrapper around
2698 ** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
2699 ** to any internal data structures of SQLite.  It uses only the public
2700 ** interface defined here.  As a consequence, errors that occur in the
2701 ** wrapper layer outside of the internal [sqlite3_exec()] call are not
2702 ** reflected in subsequent calls to [sqlite3_errcode()] or
2703 ** [sqlite3_errmsg()].
2704 */
2705 SQLITE_API int sqlite3_get_table(
2706   sqlite3 *db,          /* An open database */
2707   const char *zSql,     /* SQL to be evaluated */
2708   char ***pazResult,    /* Results of the query */
2709   int *pnRow,           /* Number of result rows written here */
2710   int *pnColumn,        /* Number of result columns written here */
2711   char **pzErrmsg       /* Error msg written here */
2712 );
2713 SQLITE_API void sqlite3_free_table(char **result);
2714
2715 /*
2716 ** CAPI3REF: Formatted String Printing Functions
2717 **
2718 ** These routines are work-alikes of the "printf()" family of functions
2719 ** from the standard C library.
2720 **
2721 ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
2722 ** results into memory obtained from [sqlite3_malloc()].
2723 ** The strings returned by these two routines should be
2724 ** released by [sqlite3_free()].  ^Both routines return a
2725 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
2726 ** memory to hold the resulting string.
2727 **
2728 ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
2729 ** the standard C library.  The result is written into the
2730 ** buffer supplied as the second parameter whose size is given by
2731 ** the first parameter. Note that the order of the
2732 ** first two parameters is reversed from snprintf().)^  This is an
2733 ** historical accident that cannot be fixed without breaking
2734 ** backwards compatibility.  ^(Note also that sqlite3_snprintf()
2735 ** returns a pointer to its buffer instead of the number of
2736 ** characters actually written into the buffer.)^  We admit that
2737 ** the number of characters written would be a more useful return
2738 ** value but we cannot change the implementation of sqlite3_snprintf()
2739 ** now without breaking compatibility.
2740 **
2741 ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
2742 ** guarantees that the buffer is always zero-terminated.  ^The first
2743 ** parameter "n" is the total size of the buffer, including space for
2744 ** the zero terminator.  So the longest string that can be completely
2745 ** written will be n-1 characters.
2746 **
2747 ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
2748 **
2749 ** These routines all implement some additional formatting
2750 ** options that are useful for constructing SQL statements.
2751 ** All of the usual printf() formatting options apply.  In addition, there
2752 ** is are "%q", "%Q", and "%z" options.
2753 **
2754 ** ^(The %q option works like %s in that it substitutes a nul-terminated
2755 ** string from the argument list.  But %q also doubles every '\'' character.
2756 ** %q is designed for use inside a string literal.)^  By doubling each '\''
2757 ** character it escapes that character and allows it to be inserted into
2758 ** the string.
2759 **
2760 ** For example, assume the string variable zText contains text as follows:
2761 **
2762 ** <blockquote><pre>
2763 **  char *zText = "It's a happy day!";
2764 ** </pre></blockquote>
2765 **
2766 ** One can use this text in an SQL statement as follows:
2767 **
2768 ** <blockquote><pre>
2769 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
2770 **  sqlite3_exec(db, zSQL, 0, 0, 0);
2771 **  sqlite3_free(zSQL);
2772 ** </pre></blockquote>
2773 **
2774 ** Because the %q format string is used, the '\'' character in zText
2775 ** is escaped and the SQL generated is as follows:
2776 **
2777 ** <blockquote><pre>
2778 **  INSERT INTO table1 VALUES('It''s a happy day!')
2779 ** </pre></blockquote>
2780 **
2781 ** This is correct.  Had we used %s instead of %q, the generated SQL
2782 ** would have looked like this:
2783 **
2784 ** <blockquote><pre>
2785 **  INSERT INTO table1 VALUES('It's a happy day!');
2786 ** </pre></blockquote>
2787 **
2788 ** This second example is an SQL syntax error.  As a general rule you should
2789 ** always use %q instead of %s when inserting text into a string literal.
2790 **
2791 ** ^(The %Q option works like %q except it also adds single quotes around
2792 ** the outside of the total string.  Additionally, if the parameter in the
2793 ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
2794 ** single quotes).)^  So, for example, one could say:
2795 **
2796 ** <blockquote><pre>
2797 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
2798 **  sqlite3_exec(db, zSQL, 0, 0, 0);
2799 **  sqlite3_free(zSQL);
2800 ** </pre></blockquote>
2801 **
2802 ** The code above will render a correct SQL statement in the zSQL
2803 ** variable even if the zText variable is a NULL pointer.
2804 **
2805 ** ^(The "%z" formatting option works like "%s" but with the
2806 ** addition that after the string has been read and copied into
2807 ** the result, [sqlite3_free()] is called on the input string.)^
2808 */
2809 SQLITE_API char *sqlite3_mprintf(const char*,...);
2810 SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
2811 SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
2812 SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
2813
2814 /*
2815 ** CAPI3REF: Memory Allocation Subsystem
2816 **
2817 ** The SQLite core uses these three routines for all of its own
2818 ** internal memory allocation needs. "Core" in the previous sentence
2819 ** does not include operating-system specific VFS implementation.  The
2820 ** Windows VFS uses native malloc() and free() for some operations.
2821 **
2822 ** ^The sqlite3_malloc() routine returns a pointer to a block
2823 ** of memory at least N bytes in length, where N is the parameter.
2824 ** ^If sqlite3_malloc() is unable to obtain sufficient free
2825 ** memory, it returns a NULL pointer.  ^If the parameter N to
2826 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
2827 ** a NULL pointer.
2828 **
2829 ** ^Calling sqlite3_free() with a pointer previously returned
2830 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
2831 ** that it might be reused.  ^The sqlite3_free() routine is
2832 ** a no-op if is called with a NULL pointer.  Passing a NULL pointer
2833 ** to sqlite3_free() is harmless.  After being freed, memory
2834 ** should neither be read nor written.  Even reading previously freed
2835 ** memory might result in a segmentation fault or other severe error.
2836 ** Memory corruption, a segmentation fault, or other severe error
2837 ** might result if sqlite3_free() is called with a non-NULL pointer that
2838 ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
2839 **
2840 ** ^(The sqlite3_realloc() interface attempts to resize a
2841 ** prior memory allocation to be at least N bytes, where N is the
2842 ** second parameter.  The memory allocation to be resized is the first
2843 ** parameter.)^ ^ If the first parameter to sqlite3_realloc()
2844 ** is a NULL pointer then its behavior is identical to calling
2845 ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
2846 ** ^If the second parameter to sqlite3_realloc() is zero or
2847 ** negative then the behavior is exactly the same as calling
2848 ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
2849 ** ^sqlite3_realloc() returns a pointer to a memory allocation
2850 ** of at least N bytes in size or NULL if sufficient memory is unavailable.
2851 ** ^If M is the size of the prior allocation, then min(N,M) bytes
2852 ** of the prior allocation are copied into the beginning of buffer returned
2853 ** by sqlite3_realloc() and the prior allocation is freed.
2854 ** ^If sqlite3_realloc() returns NULL, then the prior allocation
2855 ** is not freed.
2856 **
2857 ** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
2858 ** is always aligned to at least an 8 byte boundary, or to a
2859 ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
2860 ** option is used.
2861 **
2862 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
2863 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
2864 ** implementation of these routines to be omitted.  That capability
2865 ** is no longer provided.  Only built-in memory allocators can be used.
2866 **
2867 ** Prior to SQLite version 3.7.10, the Windows OS interface layer called
2868 ** the system malloc() and free() directly when converting
2869 ** filenames between the UTF-8 encoding used by SQLite
2870 ** and whatever filename encoding is used by the particular Windows
2871 ** installation.  Memory allocation errors were detected, but
2872 ** they were reported back as [SQLITE_CANTOPEN] or
2873 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
2874 **
2875 ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
2876 ** must be either NULL or else pointers obtained from a prior
2877 ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
2878 ** not yet been released.
2879 **
2880 ** The application must not read or write any part of
2881 ** a block of memory after it has been released using
2882 ** [sqlite3_free()] or [sqlite3_realloc()].
2883 */
2884 SQLITE_API void *sqlite3_malloc(int);
2885 SQLITE_API void *sqlite3_realloc(void*, int);
2886 SQLITE_API void sqlite3_free(void*);
2887
2888 /*
2889 ** CAPI3REF: Memory Allocator Statistics
2890 **
2891 ** SQLite provides these two interfaces for reporting on the status
2892 ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
2893 ** routines, which form the built-in memory allocation subsystem.
2894 **
2895 ** ^The [sqlite3_memory_used()] routine returns the number of bytes
2896 ** of memory currently outstanding (malloced but not freed).
2897 ** ^The [sqlite3_memory_highwater()] routine returns the maximum
2898 ** value of [sqlite3_memory_used()] since the high-water mark
2899 ** was last reset.  ^The values returned by [sqlite3_memory_used()] and
2900 ** [sqlite3_memory_highwater()] include any overhead
2901 ** added by SQLite in its implementation of [sqlite3_malloc()],
2902 ** but not overhead added by the any underlying system library
2903 ** routines that [sqlite3_malloc()] may call.
2904 **
2905 ** ^The memory high-water mark is reset to the current value of
2906 ** [sqlite3_memory_used()] if and only if the parameter to
2907 ** [sqlite3_memory_highwater()] is true.  ^The value returned
2908 ** by [sqlite3_memory_highwater(1)] is the high-water mark
2909 ** prior to the reset.
2910 */
2911 SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
2912 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
2913
2914 /*
2915 ** CAPI3REF: Pseudo-Random Number Generator
2916 **
2917 ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
2918 ** select random [ROWID | ROWIDs] when inserting new records into a table that
2919 ** already uses the largest possible [ROWID].  The PRNG is also used for
2920 ** the build-in random() and randomblob() SQL functions.  This interface allows
2921 ** applications to access the same PRNG for other purposes.
2922 **
2923 ** ^A call to this routine stores N bytes of randomness into buffer P.
2924 **
2925 ** ^The first time this routine is invoked (either internally or by
2926 ** the application) the PRNG is seeded using randomness obtained
2927 ** from the xRandomness method of the default [sqlite3_vfs] object.
2928 ** ^On all subsequent invocations, the pseudo-randomness is generated
2929 ** internally and without recourse to the [sqlite3_vfs] xRandomness
2930 ** method.
2931 */
2932 SQLITE_API void sqlite3_randomness(int N, void *P);
2933
2934 /*
2935 ** CAPI3REF: Compile-Time Authorization Callbacks
2936 **
2937 ** ^This routine registers an authorizer callback with a particular
2938 ** [database connection], supplied in the first argument.
2939 ** ^The authorizer callback is invoked as SQL statements are being compiled
2940 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
2941 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  ^At various
2942 ** points during the compilation process, as logic is being created
2943 ** to perform various actions, the authorizer callback is invoked to
2944 ** see if those actions are allowed.  ^The authorizer callback should
2945 ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
2946 ** specific action but allow the SQL statement to continue to be
2947 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
2948 ** rejected with an error.  ^If the authorizer callback returns
2949 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
2950 ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
2951 ** the authorizer will fail with an error message.
2952 **
2953 ** When the callback returns [SQLITE_OK], that means the operation
2954 ** requested is ok.  ^When the callback returns [SQLITE_DENY], the
2955 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
2956 ** authorizer will fail with an error message explaining that
2957 ** access is denied. 
2958 **
2959 ** ^The first parameter to the authorizer callback is a copy of the third
2960 ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
2961 ** to the callback is an integer [SQLITE_COPY | action code] that specifies
2962 ** the particular action to be authorized. ^The third through sixth parameters
2963 ** to the callback are zero-terminated strings that contain additional
2964 ** details about the action to be authorized.
2965 **
2966 ** ^If the action code is [SQLITE_READ]
2967 ** and the callback returns [SQLITE_IGNORE] then the
2968 ** [prepared statement] statement is constructed to substitute
2969 ** a NULL value in place of the table column that would have
2970 ** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
2971 ** return can be used to deny an untrusted user access to individual
2972 ** columns of a table.
2973 ** ^If the action code is [SQLITE_DELETE] and the callback returns
2974 ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
2975 ** [truncate optimization] is disabled and all rows are deleted individually.
2976 **
2977 ** An authorizer is used when [sqlite3_prepare | preparing]
2978 ** SQL statements from an untrusted source, to ensure that the SQL statements
2979 ** do not try to access data they are not allowed to see, or that they do not
2980 ** try to execute malicious statements that damage the database.  For
2981 ** example, an application may allow a user to enter arbitrary
2982 ** SQL queries for evaluation by a database.  But the application does
2983 ** not want the user to be able to make arbitrary changes to the
2984 ** database.  An authorizer could then be put in place while the
2985 ** user-entered SQL is being [sqlite3_prepare | prepared] that
2986 ** disallows everything except [SELECT] statements.
2987 **
2988 ** Applications that need to process SQL from untrusted sources
2989 ** might also consider lowering resource limits using [sqlite3_limit()]
2990 ** and limiting database size using the [max_page_count] [PRAGMA]
2991 ** in addition to using an authorizer.
2992 **
2993 ** ^(Only a single authorizer can be in place on a database connection
2994 ** at a time.  Each call to sqlite3_set_authorizer overrides the
2995 ** previous call.)^  ^Disable the authorizer by installing a NULL callback.
2996 ** The authorizer is disabled by default.
2997 **
2998 ** The authorizer callback must not do anything that will modify
2999 ** the database connection that invoked the authorizer callback.
3000 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
3001 ** database connections for the meaning of "modify" in this paragraph.
3002 **
3003 ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
3004 ** statement might be re-prepared during [sqlite3_step()] due to a 
3005 ** schema change.  Hence, the application should ensure that the
3006 ** correct authorizer callback remains in place during the [sqlite3_step()].
3007 **
3008 ** ^Note that the authorizer callback is invoked only during
3009 ** [sqlite3_prepare()] or its variants.  Authorization is not
3010 ** performed during statement evaluation in [sqlite3_step()], unless
3011 ** as stated in the previous paragraph, sqlite3_step() invokes
3012 ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
3013 */
3014 SQLITE_API int sqlite3_set_authorizer(
3015   sqlite3*,
3016   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
3017   void *pUserData
3018 );
3019
3020 /*
3021 ** CAPI3REF: Authorizer Return Codes
3022 **
3023 ** The [sqlite3_set_authorizer | authorizer callback function] must
3024 ** return either [SQLITE_OK] or one of these two constants in order
3025 ** to signal SQLite whether or not the action is permitted.  See the
3026 ** [sqlite3_set_authorizer | authorizer documentation] for additional
3027 ** information.
3028 **
3029 ** Note that SQLITE_IGNORE is also used as a [SQLITE_ROLLBACK | return code]
3030 ** from the [sqlite3_vtab_on_conflict()] interface.
3031 */
3032 #define SQLITE_DENY   1   /* Abort the SQL statement with an error */
3033 #define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
3034
3035 /*
3036 ** CAPI3REF: Authorizer Action Codes
3037 **
3038 ** The [sqlite3_set_authorizer()] interface registers a callback function
3039 ** that is invoked to authorize certain SQL statement actions.  The
3040 ** second parameter to the callback is an integer code that specifies
3041 ** what action is being authorized.  These are the integer action codes that
3042 ** the authorizer callback may be passed.
3043 **
3044 ** These action code values signify what kind of operation is to be
3045 ** authorized.  The 3rd and 4th parameters to the authorization
3046 ** callback function will be parameters or NULL depending on which of these
3047 ** codes is used as the second parameter.  ^(The 5th parameter to the
3048 ** authorizer callback is the name of the database ("main", "temp",
3049 ** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback
3050 ** is the name of the inner-most trigger or view that is responsible for
3051 ** the access attempt or NULL if this access attempt is directly from
3052 ** top-level SQL code.
3053 */
3054 /******************************************* 3rd ************ 4th ***********/
3055 #define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
3056 #define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
3057 #define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
3058 #define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
3059 #define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
3060 #define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
3061 #define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
3062 #define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
3063 #define SQLITE_DELETE                9   /* Table Name      NULL            */
3064 #define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
3065 #define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
3066 #define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
3067 #define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
3068 #define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
3069 #define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
3070 #define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
3071 #define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
3072 #define SQLITE_INSERT               18   /* Table Name      NULL            */
3073 #define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
3074 #define SQLITE_READ                 20   /* Table Name      Column Name     */
3075 #define SQLITE_SELECT               21   /* NULL            NULL            */
3076 #define SQLITE_TRANSACTION          22   /* Operation       NULL            */
3077 #define SQLITE_UPDATE               23   /* Table Name      Column Name     */
3078 #define SQLITE_ATTACH               24   /* Filename        NULL            */
3079 #define SQLITE_DETACH               25   /* Database Name   NULL            */
3080 #define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
3081 #define SQLITE_REINDEX              27   /* Index Name      NULL            */
3082 #define SQLITE_ANALYZE              28   /* Table Name      NULL            */
3083 #define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
3084 #define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
3085 #define SQLITE_FUNCTION             31   /* NULL            Function Name   */
3086 #define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */
3087 #define SQLITE_COPY                  0   /* No longer used */
3088
3089 /*
3090 ** CAPI3REF: Tracing And Profiling Functions
3091 **
3092 ** These routines register callback functions that can be used for
3093 ** tracing and profiling the execution of SQL statements.
3094 **
3095 ** ^The callback function registered by sqlite3_trace() is invoked at
3096 ** various times when an SQL statement is being run by [sqlite3_step()].
3097 ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
3098 ** SQL statement text as the statement first begins executing.
3099 ** ^(Additional sqlite3_trace() callbacks might occur
3100 ** as each triggered subprogram is entered.  The callbacks for triggers
3101 ** contain a UTF-8 SQL comment that identifies the trigger.)^
3102 **
3103 ** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
3104 ** the length of [bound parameter] expansion in the output of sqlite3_trace().
3105 **
3106 ** ^The callback function registered by sqlite3_profile() is invoked
3107 ** as each SQL statement finishes.  ^The profile callback contains
3108 ** the original statement text and an estimate of wall-clock time
3109 ** of how long that statement took to run.  ^The profile callback
3110 ** time is in units of nanoseconds, however the current implementation
3111 ** is only capable of millisecond resolution so the six least significant
3112 ** digits in the time are meaningless.  Future versions of SQLite
3113 ** might provide greater resolution on the profiler callback.  The
3114 ** sqlite3_profile() function is considered experimental and is
3115 ** subject to change in future versions of SQLite.
3116 */
3117 SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
3118 SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
3119    void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
3120
3121 /*
3122 ** CAPI3REF: Query Progress Callbacks
3123 **
3124 ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
3125 ** function X to be invoked periodically during long running calls to
3126 ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
3127 ** database connection D.  An example use for this
3128 ** interface is to keep a GUI updated during a large query.
3129 **
3130 ** ^The parameter P is passed through as the only parameter to the 
3131 ** callback function X.  ^The parameter N is the number of 
3132 ** [virtual machine instructions] that are evaluated between successive
3133 ** invocations of the callback X.
3134 **
3135 ** ^Only a single progress handler may be defined at one time per
3136 ** [database connection]; setting a new progress handler cancels the
3137 ** old one.  ^Setting parameter X to NULL disables the progress handler.
3138 ** ^The progress handler is also disabled by setting N to a value less
3139 ** than 1.
3140 **
3141 ** ^If the progress callback returns non-zero, the operation is
3142 ** interrupted.  This feature can be used to implement a
3143 ** "Cancel" button on a GUI progress dialog box.
3144 **
3145 ** The progress handler callback must not do anything that will modify
3146 ** the database connection that invoked the progress handler.
3147 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
3148 ** database connections for the meaning of "modify" in this paragraph.
3149 **
3150 */
3151 SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
3152
3153 /*
3154 ** CAPI3REF: Opening A New Database Connection
3155 **
3156 ** ^These routines open an SQLite database file as specified by the 
3157 ** filename argument. ^The filename argument is interpreted as UTF-8 for
3158 ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
3159 ** order for sqlite3_open16(). ^(A [database connection] handle is usually
3160 ** returned in *ppDb, even if an error occurs.  The only exception is that
3161 ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
3162 ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
3163 ** object.)^ ^(If the database is opened (and/or created) successfully, then
3164 ** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.)^ ^The
3165 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
3166 ** an English language description of the error following a failure of any
3167 ** of the sqlite3_open() routines.
3168 **
3169 ** ^The default encoding for the database will be UTF-8 if
3170 ** sqlite3_open() or sqlite3_open_v2() is called and
3171 ** UTF-16 in the native byte order if sqlite3_open16() is used.
3172 **
3173 ** Whether or not an error occurs when it is opened, resources
3174 ** associated with the [database connection] handle should be released by
3175 ** passing it to [sqlite3_close()] when it is no longer required.
3176 **
3177 ** The sqlite3_open_v2() interface works like sqlite3_open()
3178 ** except that it accepts two additional parameters for additional control
3179 ** over the new database connection.  ^(The flags parameter to
3180 ** sqlite3_open_v2() can take one of
3181 ** the following three values, optionally combined with the 
3182 ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
3183 ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
3184 **
3185 ** <dl>
3186 ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
3187 ** <dd>The database is opened in read-only mode.  If the database does not
3188 ** already exist, an error is returned.</dd>)^
3189 **
3190 ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
3191 ** <dd>The database is opened for reading and writing if possible, or reading
3192 ** only if the file is write protected by the operating system.  In either
3193 ** case the database must already exist, otherwise an error is returned.</dd>)^
3194 **
3195 ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
3196 ** <dd>The database is opened for reading and writing, and is created if
3197 ** it does not already exist. This is the behavior that is always used for
3198 ** sqlite3_open() and sqlite3_open16().</dd>)^
3199 ** </dl>
3200 **
3201 ** If the 3rd parameter to sqlite3_open_v2() is not one of the
3202 ** combinations shown above optionally combined with other
3203 ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
3204 ** then the behavior is undefined.
3205 **
3206 ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
3207 ** opens in the multi-thread [threading mode] as long as the single-thread
3208 ** mode has not been set at compile-time or start-time.  ^If the
3209 ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
3210 ** in the serialized [threading mode] unless single-thread was
3211 ** previously selected at compile-time or start-time.
3212 ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
3213 ** eligible to use [shared cache mode], regardless of whether or not shared
3214 ** cache is enabled using [sqlite3_enable_shared_cache()].  ^The
3215 ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
3216 ** participate in [shared cache mode] even if it is enabled.
3217 **
3218 ** ^The fourth parameter to sqlite3_open_v2() is the name of the
3219 ** [sqlite3_vfs] object that defines the operating system interface that
3220 ** the new database connection should use.  ^If the fourth parameter is
3221 ** a NULL pointer then the default [sqlite3_vfs] object is used.
3222 **
3223 ** ^If the filename is ":memory:", then a private, temporary in-memory database
3224 ** is created for the connection.  ^This in-memory database will vanish when
3225 ** the database connection is closed.  Future versions of SQLite might
3226 ** make use of additional special filenames that begin with the ":" character.
3227 ** It is recommended that when a database filename actually does begin with
3228 ** a ":" character you should prefix the filename with a pathname such as
3229 ** "./" to avoid ambiguity.
3230 **
3231 ** ^If the filename is an empty string, then a private, temporary
3232 ** on-disk database will be created.  ^This private database will be
3233 ** automatically deleted as soon as the database connection is closed.
3234 **
3235 ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
3236 **
3237 ** ^If [URI filename] interpretation is enabled, and the filename argument
3238 ** begins with "file:", then the filename is interpreted as a URI. ^URI
3239 ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
3240 ** set in the fourth argument to sqlite3_open_v2(), or if it has
3241 ** been enabled globally using the [SQLITE_CONFIG_URI] option with the
3242 ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
3243 ** As of SQLite version 3.7.7, URI filename interpretation is turned off
3244 ** by default, but future releases of SQLite might enable URI filename
3245 ** interpretation by default.  See "[URI filenames]" for additional
3246 ** information.
3247 **
3248 ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
3249 ** authority, then it must be either an empty string or the string 
3250 ** "localhost". ^If the authority is not an empty string or "localhost", an 
3251 ** error is returned to the caller. ^The fragment component of a URI, if 
3252 ** present, is ignored.
3253 **
3254 ** ^SQLite uses the path component of the URI as the name of the disk file
3255 ** which contains the database. ^If the path begins with a '/' character, 
3256 ** then it is interpreted as an absolute path. ^If the path does not begin 
3257 ** with a '/' (meaning that the authority section is omitted from the URI)
3258 ** then the path is interpreted as a relative path. 
3259 ** ^On windows, the first component of an absolute path 
3260 ** is a drive specification (e.g. "C:").
3261 **
3262 ** [[core URI query parameters]]
3263 ** The query component of a URI may contain parameters that are interpreted
3264 ** either by SQLite itself, or by a [VFS | custom VFS implementation].
3265 ** SQLite interprets the following three query parameters:
3266 **
3267 ** <ul>
3268 **   <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
3269 **     a VFS object that provides the operating system interface that should
3270 **     be used to access the database file on disk. ^If this option is set to
3271 **     an empty string the default VFS object is used. ^Specifying an unknown
3272 **     VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
3273 **     present, then the VFS specified by the option takes precedence over
3274 **     the value passed as the fourth parameter to sqlite3_open_v2().
3275 **
3276 **   <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
3277 **     "rwc", or "memory". Attempting to set it to any other value is
3278 **     an error)^. 
3279 **     ^If "ro" is specified, then the database is opened for read-only 
3280 **     access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the 
3281 **     third argument to sqlite3_open_v2(). ^If the mode option is set to 
3282 **     "rw", then the database is opened for read-write (but not create) 
3283 **     access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had 
3284 **     been set. ^Value "rwc" is equivalent to setting both 
3285 **     SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE.  ^If the mode option is
3286 **     set to "memory" then a pure [in-memory database] that never reads
3287 **     or writes from disk is used. ^It is an error to specify a value for
3288 **     the mode parameter that is less restrictive than that specified by
3289 **     the flags passed in the third parameter to sqlite3_open_v2().
3290 **
3291 **   <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
3292 **     "private". ^Setting it to "shared" is equivalent to setting the
3293 **     SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
3294 **     sqlite3_open_v2(). ^Setting the cache parameter to "private" is 
3295 **     equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
3296 **     ^If sqlite3_open_v2() is used and the "cache" parameter is present in
3297 **     a URI filename, its value overrides any behavior requested by setting
3298 **     SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
3299 ** </ul>
3300 **
3301 ** ^Specifying an unknown parameter in the query component of a URI is not an
3302 ** error.  Future versions of SQLite might understand additional query
3303 ** parameters.  See "[query parameters with special meaning to SQLite]" for
3304 ** additional information.
3305 **
3306 ** [[URI filename examples]] <h3>URI filename examples</h3>
3307 **
3308 ** <table border="1" align=center cellpadding=5>
3309 ** <tr><th> URI filenames <th> Results
3310 ** <tr><td> file:data.db <td> 
3311 **          Open the file "data.db" in the current directory.
3312 ** <tr><td> file:/home/fred/data.db<br>
3313 **          file:///home/fred/data.db <br> 
3314 **          file://localhost/home/fred/data.db <br> <td> 
3315 **          Open the database file "/home/fred/data.db".
3316 ** <tr><td> file://darkstar/home/fred/data.db <td> 
3317 **          An error. "darkstar" is not a recognized authority.
3318 ** <tr><td style="white-space:nowrap"> 
3319 **          file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
3320 **     <td> Windows only: Open the file "data.db" on fred's desktop on drive
3321 **          C:. Note that the %20 escaping in this example is not strictly 
3322 **          necessary - space characters can be used literally
3323 **          in URI filenames.
3324 ** <tr><td> file:data.db?mode=ro&cache=private <td> 
3325 **          Open file "data.db" in the current directory for read-only access.
3326 **          Regardless of whether or not shared-cache mode is enabled by
3327 **          default, use a private cache.
3328 ** <tr><td> file:/home/fred/data.db?vfs=unix-nolock <td>
3329 **          Open file "/home/fred/data.db". Use the special VFS "unix-nolock".
3330 ** <tr><td> file:data.db?mode=readonly <td> 
3331 **          An error. "readonly" is not a valid option for the "mode" parameter.
3332 ** </table>
3333 **
3334 ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
3335 ** query components of a URI. A hexadecimal escape sequence consists of a
3336 ** percent sign - "%" - followed by exactly two hexadecimal digits 
3337 ** specifying an octet value. ^Before the path or query components of a
3338 ** URI filename are interpreted, they are encoded using UTF-8 and all 
3339 ** hexadecimal escape sequences replaced by a single byte containing the
3340 ** corresponding octet. If this process generates an invalid UTF-8 encoding,
3341 ** the results are undefined.
3342 **
3343 ** <b>Note to Windows users:</b>  The encoding used for the filename argument
3344 ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
3345 ** codepage is currently defined.  Filenames containing international
3346 ** characters must be converted to UTF-8 prior to passing them into
3347 ** sqlite3_open() or sqlite3_open_v2().
3348 **
3349 ** <b>Note to Windows Runtime users:</b>  The temporary directory must be set
3350 ** prior to calling sqlite3_open() or sqlite3_open_v2().  Otherwise, various
3351 ** features that require the use of temporary files may fail.
3352 **
3353 ** See also: [sqlite3_temp_directory]
3354 */
3355 SQLITE_API int sqlite3_open(
3356   const char *filename,   /* Database filename (UTF-8) */
3357   sqlite3 **ppDb          /* OUT: SQLite db handle */
3358 );
3359 SQLITE_API int sqlite3_open16(
3360   const void *filename,   /* Database filename (UTF-16) */
3361   sqlite3 **ppDb          /* OUT: SQLite db handle */
3362 );
3363 SQLITE_API int sqlite3_open_v2(
3364   const char *filename,   /* Database filename (UTF-8) */
3365   sqlite3 **ppDb,         /* OUT: SQLite db handle */
3366   int flags,              /* Flags */
3367   const char *zVfs        /* Name of VFS module to use */
3368 );
3369
3370 /*
3371 ** CAPI3REF: Obtain Values For URI Parameters
3372 **
3373 ** These are utility routines, useful to VFS implementations, that check
3374 ** to see if a database file was a URI that contained a specific query 
3375 ** parameter, and if so obtains the value of that query parameter.
3376 **
3377 ** If F is the database filename pointer passed into the xOpen() method of 
3378 ** a VFS implementation when the flags parameter to xOpen() has one or 
3379 ** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
3380 ** P is the name of the query parameter, then
3381 ** sqlite3_uri_parameter(F,P) returns the value of the P
3382 ** parameter if it exists or a NULL pointer if P does not appear as a 
3383 ** query parameter on F.  If P is a query parameter of F
3384 ** has no explicit value, then sqlite3_uri_parameter(F,P) returns
3385 ** a pointer to an empty string.
3386 **
3387 ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
3388 ** parameter and returns true (1) or false (0) according to the value
3389 ** of P.  The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
3390 ** value of query parameter P is one of "yes", "true", or "on" in any
3391 ** case or if the value begins with a non-zero number.  The 
3392 ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
3393 ** query parameter P is one of "no", "false", or "off" in any case or
3394 ** if the value begins with a numeric zero.  If P is not a query
3395 ** parameter on F or if the value of P is does not match any of the
3396 ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
3397 **
3398 ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
3399 ** 64-bit signed integer and returns that integer, or D if P does not
3400 ** exist.  If the value of P is something other than an integer, then
3401 ** zero is returned.
3402 ** 
3403 ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
3404 ** sqlite3_uri_boolean(F,P,B) returns B.  If F is not a NULL pointer and
3405 ** is not a database file pathname pointer that SQLite passed into the xOpen
3406 ** VFS method, then the behavior of this routine is undefined and probably
3407 ** undesirable.
3408 */
3409 SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
3410 SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
3411 SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
3412
3413
3414 /*
3415 ** CAPI3REF: Error Codes And Messages
3416 **
3417 ** ^The sqlite3_errcode() interface returns the numeric [result code] or
3418 ** [extended result code] for the most recent failed sqlite3_* API call
3419 ** associated with a [database connection]. If a prior API call failed
3420 ** but the most recent API call succeeded, the return value from
3421 ** sqlite3_errcode() is undefined.  ^The sqlite3_extended_errcode()
3422 ** interface is the same except that it always returns the 
3423 ** [extended result code] even when extended result codes are
3424 ** disabled.
3425 **
3426 ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
3427 ** text that describes the error, as either UTF-8 or UTF-16 respectively.
3428 ** ^(Memory to hold the error message string is managed internally.
3429 ** The application does not need to worry about freeing the result.
3430 ** However, the error string might be overwritten or deallocated by
3431 ** subsequent calls to other SQLite interface functions.)^
3432 **
3433 ** ^The sqlite3_errstr() interface returns the English-language text
3434 ** that describes the [result code], as UTF-8.
3435 ** ^(Memory to hold the error message string is managed internally
3436 ** and must not be freed by the application)^.
3437 **
3438 ** When the serialized [threading mode] is in use, it might be the
3439 ** case that a second error occurs on a separate thread in between
3440 ** the time of the first error and the call to these interfaces.
3441 ** When that happens, the second error will be reported since these
3442 ** interfaces always report the most recent result.  To avoid
3443 ** this, each thread can obtain exclusive use of the [database connection] D
3444 ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
3445 ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
3446 ** all calls to the interfaces listed here are completed.
3447 **
3448 ** If an interface fails with SQLITE_MISUSE, that means the interface
3449 ** was invoked incorrectly by the application.  In that case, the
3450 ** error code and message may or may not be set.
3451 */
3452 SQLITE_API int sqlite3_errcode(sqlite3 *db);
3453 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
3454 SQLITE_API const char *sqlite3_errmsg(sqlite3*);
3455 SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
3456 SQLITE_API const char *sqlite3_errstr(int);
3457
3458 /*
3459 ** CAPI3REF: SQL Statement Object
3460 ** KEYWORDS: {prepared statement} {prepared statements}
3461 **
3462 ** An instance of this object represents a single SQL statement.
3463 ** This object is variously known as a "prepared statement" or a
3464 ** "compiled SQL statement" or simply as a "statement".
3465 **
3466 ** The life of a statement object goes something like this:
3467 **
3468 ** <ol>
3469 ** <li> Create the object using [sqlite3_prepare_v2()] or a related
3470 **      function.
3471 ** <li> Bind values to [host parameters] using the sqlite3_bind_*()
3472 **      interfaces.
3473 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
3474 ** <li> Reset the statement using [sqlite3_reset()] then go back
3475 **      to step 2.  Do this zero or more times.
3476 ** <li> Destroy the object using [sqlite3_finalize()].
3477 ** </ol>
3478 **
3479 ** Refer to documentation on individual methods above for additional
3480 ** information.
3481 */
3482 typedef struct sqlite3_stmt sqlite3_stmt;
3483
3484 /*
3485 ** CAPI3REF: Run-time Limits
3486 **
3487 ** ^(This interface allows the size of various constructs to be limited
3488 ** on a connection by connection basis.  The first parameter is the
3489 ** [database connection] whose limit is to be set or queried.  The
3490 ** second parameter is one of the [limit categories] that define a
3491 ** class of constructs to be size limited.  The third parameter is the
3492 ** new limit for that construct.)^
3493 **
3494 ** ^If the new limit is a negative number, the limit is unchanged.
3495 ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a 
3496 ** [limits | hard upper bound]
3497 ** set at compile-time by a C preprocessor macro called
3498 ** [limits | SQLITE_MAX_<i>NAME</i>].
3499 ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
3500 ** ^Attempts to increase a limit above its hard upper bound are
3501 ** silently truncated to the hard upper bound.
3502 **
3503 ** ^Regardless of whether or not the limit was changed, the 
3504 ** [sqlite3_limit()] interface returns the prior value of the limit.
3505 ** ^Hence, to find the current value of a limit without changing it,
3506 ** simply invoke this interface with the third parameter set to -1.
3507 **
3508 ** Run-time limits are intended for use in applications that manage
3509 ** both their own internal database and also databases that are controlled
3510 ** by untrusted external sources.  An example application might be a
3511 ** web browser that has its own databases for storing history and
3512 ** separate databases controlled by JavaScript applications downloaded
3513 ** off the Internet.  The internal databases can be given the
3514 ** large, default limits.  Databases managed by external sources can
3515 ** be given much smaller limits designed to prevent a denial of service
3516 ** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
3517 ** interface to further control untrusted SQL.  The size of the database
3518 ** created by an untrusted script can be contained using the
3519 ** [max_page_count] [PRAGMA].
3520 **
3521 ** New run-time limit categories may be added in future releases.
3522 */
3523 SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
3524
3525 /*
3526 ** CAPI3REF: Run-Time Limit Categories
3527 ** KEYWORDS: {limit category} {*limit categories}
3528 **
3529 ** These constants define various performance limits
3530 ** that can be lowered at run-time using [sqlite3_limit()].
3531 ** The synopsis of the meanings of the various limits is shown below.
3532 ** Additional information is available at [limits | Limits in SQLite].
3533 **
3534 ** <dl>
3535 ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
3536 ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
3537 **
3538 ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
3539 ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
3540 **
3541 ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
3542 ** <dd>The maximum number of columns in a table definition or in the
3543 ** result set of a [SELECT] or the maximum number of columns in an index
3544 ** or in an ORDER BY or GROUP BY clause.</dd>)^
3545 **
3546 ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
3547 ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
3548 **
3549 ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
3550 ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
3551 **
3552 ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
3553 ** <dd>The maximum number of instructions in a virtual machine program
3554 ** used to implement an SQL statement.  This limit is not currently
3555 ** enforced, though that might be added in some future release of
3556 ** SQLite.</dd>)^
3557 **
3558 ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
3559 ** <dd>The maximum number of arguments on a function.</dd>)^
3560 **
3561 ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
3562 ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
3563 **
3564 ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
3565 ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
3566 ** <dd>The maximum length of the pattern argument to the [LIKE] or
3567 ** [GLOB] operators.</dd>)^
3568 **
3569 ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
3570 ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
3571 ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
3572 **
3573 ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
3574 ** <dd>The maximum depth of recursion for triggers.</dd>)^
3575 ** </dl>
3576 */
3577 #define SQLITE_LIMIT_LENGTH                    0
3578 #define SQLITE_LIMIT_SQL_LENGTH                1
3579 #define SQLITE_LIMIT_COLUMN                    2
3580 #define SQLITE_LIMIT_EXPR_DEPTH                3
3581 #define SQLITE_LIMIT_COMPOUND_SELECT           4
3582 #define SQLITE_LIMIT_VDBE_OP                   5
3583 #define SQLITE_LIMIT_FUNCTION_ARG              6
3584 #define SQLITE_LIMIT_ATTACHED                  7
3585 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
3586 #define SQLITE_LIMIT_VARIABLE_NUMBER           9
3587 #define SQLITE_LIMIT_TRIGGER_DEPTH            10
3588
3589 /*
3590 ** CAPI3REF: Compiling An SQL Statement
3591 ** KEYWORDS: {SQL statement compiler}
3592 **
3593 ** To execute an SQL query, it must first be compiled into a byte-code
3594 ** program using one of these routines.
3595 **
3596 ** The first argument, "db", is a [database connection] obtained from a
3597 ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
3598 ** [sqlite3_open16()].  The database connection must not have been closed.
3599 **
3600 ** The second argument, "zSql", is the statement to be compiled, encoded
3601 ** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
3602 ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
3603 ** use UTF-16.
3604 **
3605 ** ^If the nByte argument is less than zero, then zSql is read up to the
3606 ** first zero terminator. ^If nByte is non-negative, then it is the maximum
3607 ** number of  bytes read from zSql.  ^When nByte is non-negative, the
3608 ** zSql string ends at either the first '\000' or '\u0000' character or
3609 ** the nByte-th byte, whichever comes first. If the caller knows
3610 ** that the supplied string is nul-terminated, then there is a small
3611 ** performance advantage to be gained by passing an nByte parameter that
3612 ** is equal to the number of bytes in the input string <i>including</i>
3613 ** the nul-terminator bytes as this saves SQLite from having to
3614 ** make a copy of the input string.
3615 **
3616 ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
3617 ** past the end of the first SQL statement in zSql.  These routines only
3618 ** compile the first statement in zSql, so *pzTail is left pointing to
3619 ** what remains uncompiled.
3620 **
3621 ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
3622 ** executed using [sqlite3_step()].  ^If there is an error, *ppStmt is set
3623 ** to NULL.  ^If the input text contains no SQL (if the input is an empty
3624 ** string or a comment) then *ppStmt is set to NULL.
3625 ** The calling procedure is responsible for deleting the compiled
3626 ** SQL statement using [sqlite3_finalize()] after it has finished with it.
3627 ** ppStmt may not be NULL.
3628 **
3629 ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
3630 ** otherwise an [error code] is returned.
3631 **
3632 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
3633 ** recommended for all new programs. The two older interfaces are retained
3634 ** for backwards compatibility, but their use is discouraged.
3635 ** ^In the "v2" interfaces, the prepared statement
3636 ** that is returned (the [sqlite3_stmt] object) contains a copy of the
3637 ** original SQL text. This causes the [sqlite3_step()] interface to
3638 ** behave differently in three ways:
3639 **
3640 ** <ol>
3641 ** <li>
3642 ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
3643 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
3644 ** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
3645 ** retries will occur before sqlite3_step() gives up and returns an error.
3646 ** </li>
3647 **
3648 ** <li>
3649 ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
3650 ** [error codes] or [extended error codes].  ^The legacy behavior was that
3651 ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
3652 ** and the application would have to make a second call to [sqlite3_reset()]
3653 ** in order to find the underlying cause of the problem. With the "v2" prepare
3654 ** interfaces, the underlying reason for the error is returned immediately.
3655 ** </li>
3656 **
3657 ** <li>
3658 ** ^If the specific value bound to [parameter | host parameter] in the 
3659 ** WHERE clause might influence the choice of query plan for a statement,
3660 ** then the statement will be automatically recompiled, as if there had been 
3661 ** a schema change, on the first  [sqlite3_step()] call following any change
3662 ** to the [sqlite3_bind_text | bindings] of that [parameter]. 
3663 ** ^The specific value of WHERE-clause [parameter] might influence the 
3664 ** choice of query plan if the parameter is the left-hand side of a [LIKE]
3665 ** or [GLOB] operator or if the parameter is compared to an indexed column
3666 ** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
3667 ** the 
3668 ** </li>
3669 ** </ol>
3670 */
3671 SQLITE_API int sqlite3_prepare(
3672   sqlite3 *db,            /* Database handle */
3673   const char *zSql,       /* SQL statement, UTF-8 encoded */
3674   int nByte,              /* Maximum length of zSql in bytes. */
3675   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3676   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3677 );
3678 SQLITE_API int sqlite3_prepare_v2(
3679   sqlite3 *db,            /* Database handle */
3680   const char *zSql,       /* SQL statement, UTF-8 encoded */
3681   int nByte,              /* Maximum length of zSql in bytes. */
3682   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3683   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3684 );
3685 SQLITE_API int sqlite3_prepare16(
3686   sqlite3 *db,            /* Database handle */
3687   const void *zSql,       /* SQL statement, UTF-16 encoded */
3688   int nByte,              /* Maximum length of zSql in bytes. */
3689   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3690   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3691 );
3692 SQLITE_API int sqlite3_prepare16_v2(
3693   sqlite3 *db,            /* Database handle */
3694   const void *zSql,       /* SQL statement, UTF-16 encoded */
3695   int nByte,              /* Maximum length of zSql in bytes. */
3696   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3697   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3698 );
3699
3700 /*
3701 ** CAPI3REF: Retrieving Statement SQL
3702 **
3703 ** ^This interface can be used to retrieve a saved copy of the original
3704 ** SQL text used to create a [prepared statement] if that statement was
3705 ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
3706 */
3707 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
3708
3709 /*
3710 ** CAPI3REF: Determine If An SQL Statement Writes The Database
3711 **
3712 ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
3713 ** and only if the [prepared statement] X makes no direct changes to
3714 ** the content of the database file.
3715 **
3716 ** Note that [application-defined SQL functions] or
3717 ** [virtual tables] might change the database indirectly as a side effect.  
3718 ** ^(For example, if an application defines a function "eval()" that 
3719 ** calls [sqlite3_exec()], then the following SQL statement would
3720 ** change the database file through side-effects:
3721 **
3722 ** <blockquote><pre>
3723 **    SELECT eval('DELETE FROM t1') FROM t2;
3724 ** </pre></blockquote>
3725 **
3726 ** But because the [SELECT] statement does not change the database file
3727 ** directly, sqlite3_stmt_readonly() would still return true.)^
3728 **
3729 ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
3730 ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
3731 ** since the statements themselves do not actually modify the database but
3732 ** rather they control the timing of when other statements modify the 
3733 ** database.  ^The [ATTACH] and [DETACH] statements also cause
3734 ** sqlite3_stmt_readonly() to return true since, while those statements
3735 ** change the configuration of a database connection, they do not make 
3736 ** changes to the content of the database files on disk.
3737 */
3738 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
3739
3740 /*
3741 ** CAPI3REF: Determine If A Prepared Statement Has Been Reset
3742 **
3743 ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
3744 ** [prepared statement] S has been stepped at least once using 
3745 ** [sqlite3_step(S)] but has not run to completion and/or has not 
3746 ** been reset using [sqlite3_reset(S)].  ^The sqlite3_stmt_busy(S)
3747 ** interface returns false if S is a NULL pointer.  If S is not a 
3748 ** NULL pointer and is not a pointer to a valid [prepared statement]
3749 ** object, then the behavior is undefined and probably undesirable.
3750 **
3751 ** This interface can be used in combination [sqlite3_next_stmt()]
3752 ** to locate all prepared statements associated with a database 
3753 ** connection that are in need of being reset.  This can be used,
3754 ** for example, in diagnostic routines to search for prepared 
3755 ** statements that are holding a transaction open.
3756 */
3757 SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
3758
3759 /*
3760 ** CAPI3REF: Dynamically Typed Value Object
3761 ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
3762 **
3763 ** SQLite uses the sqlite3_value object to represent all values
3764 ** that can be stored in a database table. SQLite uses dynamic typing
3765 ** for the values it stores.  ^Values stored in sqlite3_value objects
3766 ** can be integers, floating point values, strings, BLOBs, or NULL.
3767 **
3768 ** An sqlite3_value object may be either "protected" or "unprotected".
3769 ** Some interfaces require a protected sqlite3_value.  Other interfaces
3770 ** will accept either a protected or an unprotected sqlite3_value.
3771 ** Every interface that accepts sqlite3_value arguments specifies
3772 ** whether or not it requires a protected sqlite3_value.
3773 **
3774 ** The terms "protected" and "unprotected" refer to whether or not
3775 ** a mutex is held.  An internal mutex is held for a protected
3776 ** sqlite3_value object but no mutex is held for an unprotected
3777 ** sqlite3_value object.  If SQLite is compiled to be single-threaded
3778 ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
3779 ** or if SQLite is run in one of reduced mutex modes 
3780 ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
3781 ** then there is no distinction between protected and unprotected
3782 ** sqlite3_value objects and they can be used interchangeably.  However,
3783 ** for maximum code portability it is recommended that applications
3784 ** still make the distinction between protected and unprotected
3785 ** sqlite3_value objects even when not strictly required.
3786 **
3787 ** ^The sqlite3_value objects that are passed as parameters into the
3788 ** implementation of [application-defined SQL functions] are protected.
3789 ** ^The sqlite3_value object returned by
3790 ** [sqlite3_column_value()] is unprotected.
3791 ** Unprotected sqlite3_value objects may only be used with
3792 ** [sqlite3_result_value()] and [sqlite3_bind_value()].
3793 ** The [sqlite3_value_blob | sqlite3_value_type()] family of
3794 ** interfaces require protected sqlite3_value objects.
3795 */
3796 typedef struct Mem sqlite3_value;
3797
3798 /*
3799 ** CAPI3REF: SQL Function Context Object
3800 **
3801 ** The context in which an SQL function executes is stored in an
3802 ** sqlite3_context object.  ^A pointer to an sqlite3_context object
3803 ** is always first parameter to [application-defined SQL functions].
3804 ** The application-defined SQL function implementation will pass this
3805 ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
3806 ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
3807 ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
3808 ** and/or [sqlite3_set_auxdata()].
3809 */
3810 typedef struct sqlite3_context sqlite3_context;
3811
3812 /*
3813 ** CAPI3REF: Binding Values To Prepared Statements
3814 ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
3815 ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
3816 **
3817 ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
3818 ** literals may be replaced by a [parameter] that matches one of following
3819 ** templates:
3820 **
3821 ** <ul>
3822 ** <li>  ?
3823 ** <li>  ?NNN
3824 ** <li>  :VVV
3825 ** <li>  @VVV
3826 ** <li>  $VVV
3827 ** </ul>
3828 **
3829 ** In the templates above, NNN represents an integer literal,
3830 ** and VVV represents an alphanumeric identifier.)^  ^The values of these
3831 ** parameters (also called "host parameter names" or "SQL parameters")
3832 ** can be set using the sqlite3_bind_*() routines defined here.
3833 **
3834 ** ^The first argument to the sqlite3_bind_*() routines is always
3835 ** a pointer to the [sqlite3_stmt] object returned from
3836 ** [sqlite3_prepare_v2()] or its variants.
3837 **
3838 ** ^The second argument is the index of the SQL parameter to be set.
3839 ** ^The leftmost SQL parameter has an index of 1.  ^When the same named
3840 ** SQL parameter is used more than once, second and subsequent
3841 ** occurrences have the same index as the first occurrence.
3842 ** ^The index for named parameters can be looked up using the
3843 ** [sqlite3_bind_parameter_index()] API if desired.  ^The index
3844 ** for "?NNN" parameters is the value of NNN.
3845 ** ^The NNN value must be between 1 and the [sqlite3_limit()]
3846 ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
3847 **
3848 ** ^The third argument is the value to bind to the parameter.
3849 ** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
3850 ** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
3851 ** is ignored and the end result is the same as sqlite3_bind_null().
3852 **
3853 ** ^(In those routines that have a fourth argument, its value is the
3854 ** number of bytes in the parameter.  To be clear: the value is the
3855 ** number of <u>bytes</u> in the value, not the number of characters.)^
3856 ** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
3857 ** is negative, then the length of the string is
3858 ** the number of bytes up to the first zero terminator.
3859 ** If the fourth parameter to sqlite3_bind_blob() is negative, then
3860 ** the behavior is undefined.
3861 ** If a non-negative fourth parameter is provided to sqlite3_bind_text()
3862 ** or sqlite3_bind_text16() then that parameter must be the byte offset
3863 ** where the NUL terminator would occur assuming the string were NUL
3864 ** terminated.  If any NUL characters occur at byte offsets less than 
3865 ** the value of the fourth parameter then the resulting string value will
3866 ** contain embedded NULs.  The result of expressions involving strings
3867 ** with embedded NULs is undefined.
3868 **
3869 ** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
3870 ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
3871 ** string after SQLite has finished with it.  ^The destructor is called
3872 ** to dispose of the BLOB or string even if the call to sqlite3_bind_blob(),
3873 ** sqlite3_bind_text(), or sqlite3_bind_text16() fails.  
3874 ** ^If the fifth argument is
3875 ** the special value [SQLITE_STATIC], then SQLite assumes that the
3876 ** information is in static, unmanaged space and does not need to be freed.
3877 ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
3878 ** SQLite makes its own private copy of the data immediately, before
3879 ** the sqlite3_bind_*() routine returns.
3880 **
3881 ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
3882 ** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory
3883 ** (just an integer to hold its size) while it is being processed.
3884 ** Zeroblobs are intended to serve as placeholders for BLOBs whose
3885 ** content is later written using
3886 ** [sqlite3_blob_open | incremental BLOB I/O] routines.
3887 ** ^A negative value for the zeroblob results in a zero-length BLOB.
3888 **
3889 ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
3890 ** for the [prepared statement] or with a prepared statement for which
3891 ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
3892 ** then the call will return [SQLITE_MISUSE].  If any sqlite3_bind_()
3893 ** routine is passed a [prepared statement] that has been finalized, the
3894 ** result is undefined and probably harmful.
3895 **
3896 ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
3897 ** ^Unbound parameters are interpreted as NULL.
3898 **
3899 ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
3900 ** [error code] if anything goes wrong.
3901 ** ^[SQLITE_RANGE] is returned if the parameter
3902 ** index is out of range.  ^[SQLITE_NOMEM] is returned if malloc() fails.
3903 **
3904 ** See also: [sqlite3_bind_parameter_count()],
3905 ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
3906 */
3907 SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
3908 SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
3909 SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
3910 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
3911 SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
3912 SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
3913 SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
3914 SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
3915 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
3916
3917 /*
3918 ** CAPI3REF: Number Of SQL Parameters
3919 **
3920 ** ^This routine can be used to find the number of [SQL parameters]
3921 ** in a [prepared statement].  SQL parameters are tokens of the
3922 ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
3923 ** placeholders for values that are [sqlite3_bind_blob | bound]
3924 ** to the parameters at a later time.
3925 **
3926 ** ^(This routine actually returns the index of the largest (rightmost)
3927 ** parameter. For all forms except ?NNN, this will correspond to the
3928 ** number of unique parameters.  If parameters of the ?NNN form are used,
3929 ** there may be gaps in the list.)^
3930 **
3931 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3932 ** [sqlite3_bind_parameter_name()], and
3933 ** [sqlite3_bind_parameter_index()].
3934 */
3935 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
3936
3937 /*
3938 ** CAPI3REF: Name Of A Host Parameter
3939 **
3940 ** ^The sqlite3_bind_parameter_name(P,N) interface returns
3941 ** the name of the N-th [SQL parameter] in the [prepared statement] P.
3942 ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
3943 ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
3944 ** respectively.
3945 ** In other words, the initial ":" or "$" or "@" or "?"
3946 ** is included as part of the name.)^
3947 ** ^Parameters of the form "?" without a following integer have no name
3948 ** and are referred to as "nameless" or "anonymous parameters".
3949 **
3950 ** ^The first host parameter has an index of 1, not 0.
3951 **
3952 ** ^If the value N is out of range or if the N-th parameter is
3953 ** nameless, then NULL is returned.  ^The returned string is
3954 ** always in UTF-8 encoding even if the named parameter was
3955 ** originally specified as UTF-16 in [sqlite3_prepare16()] or
3956 ** [sqlite3_prepare16_v2()].
3957 **
3958 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3959 ** [sqlite3_bind_parameter_count()], and
3960 ** [sqlite3_bind_parameter_index()].
3961 */
3962 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
3963
3964 /*
3965 ** CAPI3REF: Index Of A Parameter With A Given Name
3966 **
3967 ** ^Return the index of an SQL parameter given its name.  ^The
3968 ** index value returned is suitable for use as the second
3969 ** parameter to [sqlite3_bind_blob|sqlite3_bind()].  ^A zero
3970 ** is returned if no matching parameter is found.  ^The parameter
3971 ** name must be given in UTF-8 even if the original statement
3972 ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
3973 **
3974 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3975 ** [sqlite3_bind_parameter_count()], and
3976 ** [sqlite3_bind_parameter_index()].
3977 */
3978 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
3979
3980 /*
3981 ** CAPI3REF: Reset All Bindings On A Prepared Statement
3982 **
3983 ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
3984 ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
3985 ** ^Use this routine to reset all host parameters to NULL.
3986 */
3987 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
3988
3989 /*
3990 ** CAPI3REF: Number Of Columns In A Result Set
3991 **
3992 ** ^Return the number of columns in the result set returned by the
3993 ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
3994 ** statement that does not return data (for example an [UPDATE]).
3995 **
3996 ** See also: [sqlite3_data_count()]
3997 */
3998 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
3999
4000 /*
4001 ** CAPI3REF: Column Names In A Result Set
4002 **
4003 ** ^These routines return the name assigned to a particular column
4004 ** in the result set of a [SELECT] statement.  ^The sqlite3_column_name()
4005 ** interface returns a pointer to a zero-terminated UTF-8 string
4006 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
4007 ** UTF-16 string.  ^The first parameter is the [prepared statement]
4008 ** that implements the [SELECT] statement. ^The second parameter is the
4009 ** column number.  ^The leftmost column is number 0.
4010 **
4011 ** ^The returned string pointer is valid until either the [prepared statement]
4012 ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
4013 ** reprepared by the first call to [sqlite3_step()] for a particular run
4014 ** or until the next call to
4015 ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
4016 **
4017 ** ^If sqlite3_malloc() fails during the processing of either routine
4018 ** (for example during a conversion from UTF-8 to UTF-16) then a
4019 ** NULL pointer is returned.
4020 **
4021 ** ^The name of a result column is the value of the "AS" clause for
4022 ** that column, if there is an AS clause.  If there is no AS clause
4023 ** then the name of the column is unspecified and may change from
4024 ** one release of SQLite to the next.
4025 */
4026 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
4027 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
4028
4029 /*
4030 ** CAPI3REF: Source Of Data In A Query Result
4031 **
4032 ** ^These routines provide a means to determine the database, table, and
4033 ** table column that is the origin of a particular result column in
4034 ** [SELECT] statement.
4035 ** ^The name of the database or table or column can be returned as
4036 ** either a UTF-8 or UTF-16 string.  ^The _database_ routines return
4037 ** the database name, the _table_ routines return the table name, and
4038 ** the origin_ routines return the column name.
4039 ** ^The returned string is valid until the [prepared statement] is destroyed
4040 ** using [sqlite3_finalize()] or until the statement is automatically
4041 ** reprepared by the first call to [sqlite3_step()] for a particular run
4042 ** or until the same information is requested
4043 ** again in a different encoding.
4044 **
4045 ** ^The names returned are the original un-aliased names of the
4046 ** database, table, and column.
4047 **
4048 ** ^The first argument to these interfaces is a [prepared statement].
4049 ** ^These functions return information about the Nth result column returned by
4050 ** the statement, where N is the second function argument.
4051 ** ^The left-most column is column 0 for these routines.
4052 **
4053 ** ^If the Nth column returned by the statement is an expression or
4054 ** subquery and is not a column value, then all of these functions return
4055 ** NULL.  ^These routine might also return NULL if a memory allocation error
4056 ** occurs.  ^Otherwise, they return the name of the attached database, table,
4057 ** or column that query result column was extracted from.
4058 **
4059 ** ^As with all other SQLite APIs, those whose names end with "16" return
4060 ** UTF-16 encoded strings and the other functions return UTF-8.
4061 **
4062 ** ^These APIs are only available if the library was compiled with the
4063 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
4064 **
4065 ** If two or more threads call one or more of these routines against the same
4066 ** prepared statement and column at the same time then the results are
4067 ** undefined.
4068 **
4069 ** If two or more threads call one or more
4070 ** [sqlite3_column_database_name | column metadata interfaces]
4071 ** for the same [prepared statement] and result column
4072 ** at the same time then the results are undefined.
4073 */
4074 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
4075 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
4076 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
4077 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
4078 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
4079 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
4080
4081 /*
4082 ** CAPI3REF: Declared Datatype Of A Query Result
4083 **
4084 ** ^(The first parameter is a [prepared statement].
4085 ** If this statement is a [SELECT] statement and the Nth column of the
4086 ** returned result set of that [SELECT] is a table column (not an
4087 ** expression or subquery) then the declared type of the table
4088 ** column is returned.)^  ^If the Nth column of the result set is an
4089 ** expression or subquery, then a NULL pointer is returned.
4090 ** ^The returned string is always UTF-8 encoded.
4091 **
4092 ** ^(For example, given the database schema:
4093 **
4094 ** CREATE TABLE t1(c1 VARIANT);
4095 **
4096 ** and the following statement to be compiled:
4097 **
4098 ** SELECT c1 + 1, c1 FROM t1;
4099 **
4100 ** this routine would return the string "VARIANT" for the second result
4101 ** column (i==1), and a NULL pointer for the first result column (i==0).)^
4102 **
4103 ** ^SQLite uses dynamic run-time typing.  ^So just because a column
4104 ** is declared to contain a particular type does not mean that the
4105 ** data stored in that column is of the declared type.  SQLite is
4106 ** strongly typed, but the typing is dynamic not static.  ^Type
4107 ** is associated with individual values, not with the containers
4108 ** used to hold those values.
4109 */
4110 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
4111 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
4112
4113 /*
4114 ** CAPI3REF: Evaluate An SQL Statement
4115 **
4116 ** After a [prepared statement] has been prepared using either
4117 ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
4118 ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
4119 ** must be called one or more times to evaluate the statement.
4120 **
4121 ** The details of the behavior of the sqlite3_step() interface depend
4122 ** on whether the statement was prepared using the newer "v2" interface
4123 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
4124 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
4125 ** new "v2" interface is recommended for new applications but the legacy
4126 ** interface will continue to be supported.
4127 **
4128 ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
4129 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
4130 ** ^With the "v2" interface, any of the other [result codes] or
4131 ** [extended result codes] might be returned as well.
4132 **
4133 ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
4134 ** database locks it needs to do its job.  ^If the statement is a [COMMIT]
4135 ** or occurs outside of an explicit transaction, then you can retry the
4136 ** statement.  If the statement is not a [COMMIT] and occurs within an
4137 ** explicit transaction then you should rollback the transaction before
4138 ** continuing.
4139 **
4140 ** ^[SQLITE_DONE] means that the statement has finished executing
4141 ** successfully.  sqlite3_step() should not be called again on this virtual
4142 ** machine without first calling [sqlite3_reset()] to reset the virtual
4143 ** machine back to its initial state.
4144 **
4145 ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
4146 ** is returned each time a new row of data is ready for processing by the
4147 ** caller. The values may be accessed using the [column access functions].
4148 ** sqlite3_step() is called again to retrieve the next row of data.
4149 **
4150 ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
4151 ** violation) has occurred.  sqlite3_step() should not be called again on
4152 ** the VM. More information may be found by calling [sqlite3_errmsg()].
4153 ** ^With the legacy interface, a more specific error code (for example,
4154 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
4155 ** can be obtained by calling [sqlite3_reset()] on the
4156 ** [prepared statement].  ^In the "v2" interface,
4157 ** the more specific error code is returned directly by sqlite3_step().
4158 **
4159 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
4160 ** Perhaps it was called on a [prepared statement] that has
4161 ** already been [sqlite3_finalize | finalized] or on one that had
4162 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
4163 ** be the case that the same database connection is being used by two or
4164 ** more threads at the same moment in time.
4165 **
4166 ** For all versions of SQLite up to and including 3.6.23.1, a call to
4167 ** [sqlite3_reset()] was required after sqlite3_step() returned anything
4168 ** other than [SQLITE_ROW] before any subsequent invocation of
4169 ** sqlite3_step().  Failure to reset the prepared statement using 
4170 ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
4171 ** sqlite3_step().  But after version 3.6.23.1, sqlite3_step() began
4172 ** calling [sqlite3_reset()] automatically in this circumstance rather
4173 ** than returning [SQLITE_MISUSE].  This is not considered a compatibility
4174 ** break because any application that ever receives an SQLITE_MISUSE error
4175 ** is broken by definition.  The [SQLITE_OMIT_AUTORESET] compile-time option
4176 ** can be used to restore the legacy behavior.
4177 **
4178 ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
4179 ** API always returns a generic error code, [SQLITE_ERROR], following any
4180 ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
4181 ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
4182 ** specific [error codes] that better describes the error.
4183 ** We admit that this is a goofy design.  The problem has been fixed
4184 ** with the "v2" interface.  If you prepare all of your SQL statements
4185 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
4186 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
4187 ** then the more specific [error codes] are returned directly
4188 ** by sqlite3_step().  The use of the "v2" interface is recommended.
4189 */
4190 SQLITE_API int sqlite3_step(sqlite3_stmt*);
4191
4192 /*
4193 ** CAPI3REF: Number of columns in a result set
4194 **
4195 ** ^The sqlite3_data_count(P) interface returns the number of columns in the
4196 ** current row of the result set of [prepared statement] P.
4197 ** ^If prepared statement P does not have results ready to return
4198 ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
4199 ** interfaces) then sqlite3_data_count(P) returns 0.
4200 ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
4201 ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
4202 ** [sqlite3_step](P) returned [SQLITE_DONE].  ^The sqlite3_data_count(P)
4203 ** will return non-zero if previous call to [sqlite3_step](P) returned
4204 ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
4205 ** where it always returns zero since each step of that multi-step
4206 ** pragma returns 0 columns of data.
4207 **
4208 ** See also: [sqlite3_column_count()]
4209 */
4210 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
4211
4212 /*
4213 ** CAPI3REF: Fundamental Datatypes
4214 ** KEYWORDS: SQLITE_TEXT
4215 **
4216 ** ^(Every value in SQLite has one of five fundamental datatypes:
4217 **
4218 ** <ul>
4219 ** <li> 64-bit signed integer
4220 ** <li> 64-bit IEEE floating point number
4221 ** <li> string
4222 ** <li> BLOB
4223 ** <li> NULL
4224 ** </ul>)^
4225 **
4226 ** These constants are codes for each of those types.
4227 **
4228 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
4229 ** for a completely different meaning.  Software that links against both
4230 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
4231 ** SQLITE_TEXT.
4232 */
4233 #define SQLITE_INTEGER  1
4234 #define SQLITE_FLOAT    2
4235 #define SQLITE_BLOB     4
4236 #define SQLITE_NULL     5
4237 #ifdef SQLITE_TEXT
4238 # undef SQLITE_TEXT
4239 #else
4240 # define SQLITE_TEXT     3
4241 #endif
4242 #define SQLITE3_TEXT     3
4243
4244 /*
4245 ** CAPI3REF: Result Values From A Query
4246 ** KEYWORDS: {column access functions}
4247 **
4248 ** These routines form the "result set" interface.
4249 **
4250 ** ^These routines return information about a single column of the current
4251 ** result row of a query.  ^In every case the first argument is a pointer
4252 ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
4253 ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
4254 ** and the second argument is the index of the column for which information
4255 ** should be returned. ^The leftmost column of the result set has the index 0.
4256 ** ^The number of columns in the result can be determined using
4257 ** [sqlite3_column_count()].
4258 **
4259 ** If the SQL statement does not currently point to a valid row, or if the
4260 ** column index is out of range, the result is undefined.
4261 ** These routines may only be called when the most recent call to
4262 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
4263 ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
4264 ** If any of these routines are called after [sqlite3_reset()] or
4265 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
4266 ** something other than [SQLITE_ROW], the results are undefined.
4267 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
4268 ** are called from a different thread while any of these routines
4269 ** are pending, then the results are undefined.
4270 **
4271 ** ^The sqlite3_column_type() routine returns the
4272 ** [SQLITE_INTEGER | datatype code] for the initial data type
4273 ** of the result column.  ^The returned value is one of [SQLITE_INTEGER],
4274 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
4275 ** returned by sqlite3_column_type() is only meaningful if no type
4276 ** conversions have occurred as described below.  After a type conversion,
4277 ** the value returned by sqlite3_column_type() is undefined.  Future
4278 ** versions of SQLite may change the behavior of sqlite3_column_type()
4279 ** following a type conversion.
4280 **
4281 ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
4282 ** routine returns the number of bytes in that BLOB or string.
4283 ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
4284 ** the string to UTF-8 and then returns the number of bytes.
4285 ** ^If the result is a numeric value then sqlite3_column_bytes() uses
4286 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
4287 ** the number of bytes in that string.
4288 ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
4289 **
4290 ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
4291 ** routine returns the number of bytes in that BLOB or string.
4292 ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
4293 ** the string to UTF-16 and then returns the number of bytes.
4294 ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
4295 ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
4296 ** the number of bytes in that string.
4297 ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
4298 **
4299 ** ^The values returned by [sqlite3_column_bytes()] and 
4300 ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
4301 ** of the string.  ^For clarity: the values returned by
4302 ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
4303 ** bytes in the string, not the number of characters.
4304 **
4305 ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
4306 ** even empty strings, are always zero-terminated.  ^The return
4307 ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
4308 **
4309 ** ^The object returned by [sqlite3_column_value()] is an
4310 ** [unprotected sqlite3_value] object.  An unprotected sqlite3_value object
4311 ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
4312 ** If the [unprotected sqlite3_value] object returned by
4313 ** [sqlite3_column_value()] is used in any other way, including calls
4314 ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
4315 ** or [sqlite3_value_bytes()], then the behavior is undefined.
4316 **
4317 ** These routines attempt to convert the value where appropriate.  ^For
4318 ** example, if the internal representation is FLOAT and a text result
4319 ** is requested, [sqlite3_snprintf()] is used internally to perform the
4320 ** conversion automatically.  ^(The following table details the conversions
4321 ** that are applied:
4322 **
4323 ** <blockquote>
4324 ** <table border="1">
4325 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
4326 **
4327 ** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
4328 ** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
4329 ** <tr><td>  NULL    <td>   TEXT    <td> Result is NULL pointer
4330 ** <tr><td>  NULL    <td>   BLOB    <td> Result is NULL pointer
4331 ** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
4332 ** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
4333 ** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
4334 ** <tr><td>  FLOAT   <td> INTEGER   <td> Convert from float to integer
4335 ** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
4336 ** <tr><td>  FLOAT   <td>   BLOB    <td> Same as FLOAT->TEXT
4337 ** <tr><td>  TEXT    <td> INTEGER   <td> Use atoi()
4338 ** <tr><td>  TEXT    <td>  FLOAT    <td> Use atof()
4339 ** <tr><td>  TEXT    <td>   BLOB    <td> No change
4340 ** <tr><td>  BLOB    <td> INTEGER   <td> Convert to TEXT then use atoi()
4341 ** <tr><td>  BLOB    <td>  FLOAT    <td> Convert to TEXT then use atof()
4342 ** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
4343 ** </table>
4344 ** </blockquote>)^
4345 **
4346 ** The table above makes reference to standard C library functions atoi()
4347 ** and atof().  SQLite does not really use these functions.  It has its
4348 ** own equivalent internal routines.  The atoi() and atof() names are
4349 ** used in the table for brevity and because they are familiar to most
4350 ** C programmers.
4351 **
4352 ** Note that when type conversions occur, pointers returned by prior
4353 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
4354 ** sqlite3_column_text16() may be invalidated.
4355 ** Type conversions and pointer invalidations might occur
4356 ** in the following cases:
4357 **
4358 ** <ul>
4359 ** <li> The initial content is a BLOB and sqlite3_column_text() or
4360 **      sqlite3_column_text16() is called.  A zero-terminator might
4361 **      need to be added to the string.</li>
4362 ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
4363 **      sqlite3_column_text16() is called.  The content must be converted
4364 **      to UTF-16.</li>
4365 ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
4366 **      sqlite3_column_text() is called.  The content must be converted
4367 **      to UTF-8.</li>
4368 ** </ul>
4369 **
4370 ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
4371 ** not invalidate a prior pointer, though of course the content of the buffer
4372 ** that the prior pointer references will have been modified.  Other kinds
4373 ** of conversion are done in place when it is possible, but sometimes they
4374 ** are not possible and in those cases prior pointers are invalidated.
4375 **
4376 ** The safest and easiest to remember policy is to invoke these routines
4377 ** in one of the following ways:
4378 **
4379 ** <ul>
4380 **  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
4381 **  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
4382 **  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
4383 ** </ul>
4384 **
4385 ** In other words, you should call sqlite3_column_text(),
4386 ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
4387 ** into the desired format, then invoke sqlite3_column_bytes() or
4388 ** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
4389 ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
4390 ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
4391 ** with calls to sqlite3_column_bytes().
4392 **
4393 ** ^The pointers returned are valid until a type conversion occurs as
4394 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
4395 ** [sqlite3_finalize()] is called.  ^The memory space used to hold strings
4396 ** and BLOBs is freed automatically.  Do <b>not</b> pass the pointers returned
4397 ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
4398 ** [sqlite3_free()].
4399 **
4400 ** ^(If a memory allocation error occurs during the evaluation of any
4401 ** of these routines, a default value is returned.  The default value
4402 ** is either the integer 0, the floating point number 0.0, or a NULL
4403 ** pointer.  Subsequent calls to [sqlite3_errcode()] will return
4404 ** [SQLITE_NOMEM].)^
4405 */
4406 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
4407 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
4408 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
4409 SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
4410 SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
4411 SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
4412 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
4413 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
4414 SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
4415 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
4416
4417 /*
4418 ** CAPI3REF: Destroy A Prepared Statement Object
4419 **
4420 ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
4421 ** ^If the most recent evaluation of the statement encountered no errors
4422 ** or if the statement is never been evaluated, then sqlite3_finalize() returns
4423 ** SQLITE_OK.  ^If the most recent evaluation of statement S failed, then
4424 ** sqlite3_finalize(S) returns the appropriate [error code] or
4425 ** [extended error code].
4426 **
4427 ** ^The sqlite3_finalize(S) routine can be called at any point during
4428 ** the life cycle of [prepared statement] S:
4429 ** before statement S is ever evaluated, after
4430 ** one or more calls to [sqlite3_reset()], or after any call
4431 ** to [sqlite3_step()] regardless of whether or not the statement has
4432 ** completed execution.
4433 **
4434 ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
4435 **
4436 ** The application must finalize every [prepared statement] in order to avoid
4437 ** resource leaks.  It is a grievous error for the application to try to use
4438 ** a prepared statement after it has been finalized.  Any use of a prepared
4439 ** statement after it has been finalized can result in undefined and
4440 ** undesirable behavior such as segfaults and heap corruption.
4441 */
4442 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
4443
4444 /*
4445 ** CAPI3REF: Reset A Prepared Statement Object
4446 **
4447 ** The sqlite3_reset() function is called to reset a [prepared statement]
4448 ** object back to its initial state, ready to be re-executed.
4449 ** ^Any SQL statement variables that had values bound to them using
4450 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
4451 ** Use [sqlite3_clear_bindings()] to reset the bindings.
4452 **
4453 ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
4454 ** back to the beginning of its program.
4455 **
4456 ** ^If the most recent call to [sqlite3_step(S)] for the
4457 ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
4458 ** or if [sqlite3_step(S)] has never before been called on S,
4459 ** then [sqlite3_reset(S)] returns [SQLITE_OK].
4460 **
4461 ** ^If the most recent call to [sqlite3_step(S)] for the
4462 ** [prepared statement] S indicated an error, then
4463 ** [sqlite3_reset(S)] returns an appropriate [error code].
4464 **
4465 ** ^The [sqlite3_reset(S)] interface does not change the values
4466 ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
4467 */
4468 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
4469
4470 /*
4471 ** CAPI3REF: Create Or Redefine SQL Functions
4472 ** KEYWORDS: {function creation routines}
4473 ** KEYWORDS: {application-defined SQL function}
4474 ** KEYWORDS: {application-defined SQL functions}
4475 **
4476 ** ^These functions (collectively known as "function creation routines")
4477 ** are used to add SQL functions or aggregates or to redefine the behavior
4478 ** of existing SQL functions or aggregates.  The only differences between
4479 ** these routines are the text encoding expected for
4480 ** the second parameter (the name of the function being created)
4481 ** and the presence or absence of a destructor callback for
4482 ** the application data pointer.
4483 **
4484 ** ^The first parameter is the [database connection] to which the SQL
4485 ** function is to be added.  ^If an application uses more than one database
4486 ** connection then application-defined SQL functions must be added
4487 ** to each database connection separately.
4488 **
4489 ** ^The second parameter is the name of the SQL function to be created or
4490 ** redefined.  ^The length of the name is limited to 255 bytes in a UTF-8
4491 ** representation, exclusive of the zero-terminator.  ^Note that the name
4492 ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.  
4493 ** ^Any attempt to create a function with a longer name
4494 ** will result in [SQLITE_MISUSE] being returned.
4495 **
4496 ** ^The third parameter (nArg)
4497 ** is the number of arguments that the SQL function or
4498 ** aggregate takes. ^If this parameter is -1, then the SQL function or
4499 ** aggregate may take any number of arguments between 0 and the limit
4500 ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third
4501 ** parameter is less than -1 or greater than 127 then the behavior is
4502 ** undefined.
4503 **
4504 ** ^The fourth parameter, eTextRep, specifies what
4505 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
4506 ** its parameters.  Every SQL function implementation must be able to work
4507 ** with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be
4508 ** more efficient with one encoding than another.  ^An application may
4509 ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
4510 ** times with the same function but with different values of eTextRep.
4511 ** ^When multiple implementations of the same function are available, SQLite
4512 ** will pick the one that involves the least amount of data conversion.
4513 ** If there is only a single implementation which does not care what text
4514 ** encoding is used, then the fourth argument should be [SQLITE_ANY].
4515 **
4516 ** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
4517 ** function can gain access to this pointer using [sqlite3_user_data()].)^
4518 **
4519 ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
4520 ** pointers to C-language functions that implement the SQL function or
4521 ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
4522 ** callback only; NULL pointers must be passed as the xStep and xFinal
4523 ** parameters. ^An aggregate SQL function requires an implementation of xStep
4524 ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
4525 ** SQL function or aggregate, pass NULL pointers for all three function
4526 ** callbacks.
4527 **
4528 ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
4529 ** then it is destructor for the application data pointer. 
4530 ** The destructor is invoked when the function is deleted, either by being
4531 ** overloaded or when the database connection closes.)^
4532 ** ^The destructor is also invoked if the call to
4533 ** sqlite3_create_function_v2() fails.
4534 ** ^When the destructor callback of the tenth parameter is invoked, it
4535 ** is passed a single argument which is a copy of the application data 
4536 ** pointer which was the fifth parameter to sqlite3_create_function_v2().
4537 **
4538 ** ^It is permitted to register multiple implementations of the same
4539 ** functions with the same name but with either differing numbers of
4540 ** arguments or differing preferred text encodings.  ^SQLite will use
4541 ** the implementation that most closely matches the way in which the
4542 ** SQL function is used.  ^A function implementation with a non-negative
4543 ** nArg parameter is a better match than a function implementation with
4544 ** a negative nArg.  ^A function where the preferred text encoding
4545 ** matches the database encoding is a better
4546 ** match than a function where the encoding is different.  
4547 ** ^A function where the encoding difference is between UTF16le and UTF16be
4548 ** is a closer match than a function where the encoding difference is
4549 ** between UTF8 and UTF16.
4550 **
4551 ** ^Built-in functions may be overloaded by new application-defined functions.
4552 **
4553 ** ^An application-defined function is permitted to call other
4554 ** SQLite interfaces.  However, such calls must not
4555 ** close the database connection nor finalize or reset the prepared
4556 ** statement in which the function is running.
4557 */
4558 SQLITE_API int sqlite3_create_function(
4559   sqlite3 *db,
4560   const char *zFunctionName,
4561   int nArg,
4562   int eTextRep,
4563   void *pApp,
4564   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4565   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4566   void (*xFinal)(sqlite3_context*)
4567 );
4568 SQLITE_API int sqlite3_create_function16(
4569   sqlite3 *db,
4570   const void *zFunctionName,
4571   int nArg,
4572   int eTextRep,
4573   void *pApp,
4574   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4575   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4576   void (*xFinal)(sqlite3_context*)
4577 );
4578 SQLITE_API int sqlite3_create_function_v2(
4579   sqlite3 *db,
4580   const char *zFunctionName,
4581   int nArg,
4582   int eTextRep,
4583   void *pApp,
4584   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4585   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4586   void (*xFinal)(sqlite3_context*),
4587   void(*xDestroy)(void*)
4588 );
4589
4590 /*
4591 ** CAPI3REF: Text Encodings
4592 **
4593 ** These constant define integer codes that represent the various
4594 ** text encodings supported by SQLite.
4595 */
4596 #define SQLITE_UTF8           1
4597 #define SQLITE_UTF16LE        2
4598 #define SQLITE_UTF16BE        3
4599 #define SQLITE_UTF16          4    /* Use native byte order */
4600 #define SQLITE_ANY            5    /* sqlite3_create_function only */
4601 #define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
4602
4603 /*
4604 ** CAPI3REF: Deprecated Functions
4605 ** DEPRECATED
4606 **
4607 ** These functions are [deprecated].  In order to maintain
4608 ** backwards compatibility with older code, these functions continue 
4609 ** to be supported.  However, new applications should avoid
4610 ** the use of these functions.  To help encourage people to avoid
4611 ** using these functions, we are not going to tell you what they do.
4612 */
4613 #ifndef SQLITE_OMIT_DEPRECATED
4614 SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
4615 SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
4616 SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
4617 SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
4618 SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
4619 SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
4620                       void*,sqlite3_int64);
4621 #endif
4622
4623 /*
4624 ** CAPI3REF: Obtaining SQL Function Parameter Values
4625 **
4626 ** The C-language implementation of SQL functions and aggregates uses
4627 ** this set of interface routines to access the parameter values on
4628 ** the function or aggregate.
4629 **
4630 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
4631 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
4632 ** define callbacks that implement the SQL functions and aggregates.
4633 ** The 3rd parameter to these callbacks is an array of pointers to
4634 ** [protected sqlite3_value] objects.  There is one [sqlite3_value] object for
4635 ** each parameter to the SQL function.  These routines are used to
4636 ** extract values from the [sqlite3_value] objects.
4637 **
4638 ** These routines work only with [protected sqlite3_value] objects.
4639 ** Any attempt to use these routines on an [unprotected sqlite3_value]
4640 ** object results in undefined behavior.
4641 **
4642 ** ^These routines work just like the corresponding [column access functions]
4643 ** except that  these routines take a single [protected sqlite3_value] object
4644 ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
4645 **
4646 ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
4647 ** in the native byte-order of the host machine.  ^The
4648 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
4649 ** extract UTF-16 strings as big-endian and little-endian respectively.
4650 **
4651 ** ^(The sqlite3_value_numeric_type() interface attempts to apply
4652 ** numeric affinity to the value.  This means that an attempt is
4653 ** made to convert the value to an integer or floating point.  If
4654 ** such a conversion is possible without loss of information (in other
4655 ** words, if the value is a string that looks like a number)
4656 ** then the conversion is performed.  Otherwise no conversion occurs.
4657 ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
4658 **
4659 ** Please pay particular attention to the fact that the pointer returned
4660 ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
4661 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
4662 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
4663 ** or [sqlite3_value_text16()].
4664 **
4665 ** These routines must be called from the same thread as
4666 ** the SQL function that supplied the [sqlite3_value*] parameters.
4667 */
4668 SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
4669 SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
4670 SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
4671 SQLITE_API double sqlite3_value_double(sqlite3_value*);
4672 SQLITE_API int sqlite3_value_int(sqlite3_value*);
4673 SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
4674 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
4675 SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
4676 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
4677 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
4678 SQLITE_API int sqlite3_value_type(sqlite3_value*);
4679 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
4680
4681 /*
4682 ** CAPI3REF: Obtain Aggregate Function Context
4683 **
4684 ** Implementations of aggregate SQL functions use this
4685 ** routine to allocate memory for storing their state.
4686 **
4687 ** ^The first time the sqlite3_aggregate_context(C,N) routine is called 
4688 ** for a particular aggregate function, SQLite
4689 ** allocates N of memory, zeroes out that memory, and returns a pointer
4690 ** to the new memory. ^On second and subsequent calls to
4691 ** sqlite3_aggregate_context() for the same aggregate function instance,
4692 ** the same buffer is returned.  Sqlite3_aggregate_context() is normally
4693 ** called once for each invocation of the xStep callback and then one
4694 ** last time when the xFinal callback is invoked.  ^(When no rows match
4695 ** an aggregate query, the xStep() callback of the aggregate function
4696 ** implementation is never called and xFinal() is called exactly once.
4697 ** In those cases, sqlite3_aggregate_context() might be called for the
4698 ** first time from within xFinal().)^
4699 **
4700 ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer 
4701 ** when first called if N is less than or equal to zero or if a memory
4702 ** allocate error occurs.
4703 **
4704 ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
4705 ** determined by the N parameter on first successful call.  Changing the
4706 ** value of N in subsequent call to sqlite3_aggregate_context() within
4707 ** the same aggregate function instance will not resize the memory
4708 ** allocation.)^  Within the xFinal callback, it is customary to set
4709 ** N=0 in calls to sqlite3_aggregate_context(C,N) so that no 
4710 ** pointless memory allocations occur.
4711 **
4712 ** ^SQLite automatically frees the memory allocated by 
4713 ** sqlite3_aggregate_context() when the aggregate query concludes.
4714 **
4715 ** The first parameter must be a copy of the
4716 ** [sqlite3_context | SQL function context] that is the first parameter
4717 ** to the xStep or xFinal callback routine that implements the aggregate
4718 ** function.
4719 **
4720 ** This routine must be called from the same thread in which
4721 ** the aggregate SQL function is running.
4722 */
4723 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
4724
4725 /*
4726 ** CAPI3REF: User Data For Functions
4727 **
4728 ** ^The sqlite3_user_data() interface returns a copy of
4729 ** the pointer that was the pUserData parameter (the 5th parameter)
4730 ** of the [sqlite3_create_function()]
4731 ** and [sqlite3_create_function16()] routines that originally
4732 ** registered the application defined function.
4733 **
4734 ** This routine must be called from the same thread in which
4735 ** the application-defined function is running.
4736 */
4737 SQLITE_API void *sqlite3_user_data(sqlite3_context*);
4738
4739 /*
4740 ** CAPI3REF: Database Connection For Functions
4741 **
4742 ** ^The sqlite3_context_db_handle() interface returns a copy of
4743 ** the pointer to the [database connection] (the 1st parameter)
4744 ** of the [sqlite3_create_function()]
4745 ** and [sqlite3_create_function16()] routines that originally
4746 ** registered the application defined function.
4747 */
4748 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
4749
4750 /*
4751 ** CAPI3REF: Function Auxiliary Data
4752 **
4753 ** The following two functions may be used by scalar SQL functions to
4754 ** associate metadata with argument values. If the same value is passed to
4755 ** multiple invocations of the same SQL function during query execution, under
4756 ** some circumstances the associated metadata may be preserved. This may
4757 ** be used, for example, to add a regular-expression matching scalar
4758 ** function. The compiled version of the regular expression is stored as
4759 ** metadata associated with the SQL value passed as the regular expression
4760 ** pattern.  The compiled regular expression can be reused on multiple
4761 ** invocations of the same function so that the original pattern string
4762 ** does not need to be recompiled on each invocation.
4763 **
4764 ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
4765 ** associated by the sqlite3_set_auxdata() function with the Nth argument
4766 ** value to the application-defined function. ^If no metadata has been ever
4767 ** been set for the Nth argument of the function, or if the corresponding
4768 ** function parameter has changed since the meta-data was set,
4769 ** then sqlite3_get_auxdata() returns a NULL pointer.
4770 **
4771 ** ^The sqlite3_set_auxdata() interface saves the metadata
4772 ** pointed to by its 3rd parameter as the metadata for the N-th
4773 ** argument of the application-defined function.  Subsequent
4774 ** calls to sqlite3_get_auxdata() might return this data, if it has
4775 ** not been destroyed.
4776 ** ^If it is not NULL, SQLite will invoke the destructor
4777 ** function given by the 4th parameter to sqlite3_set_auxdata() on
4778 ** the metadata when the corresponding function parameter changes
4779 ** or when the SQL statement completes, whichever comes first.
4780 **
4781 ** SQLite is free to call the destructor and drop metadata on any
4782 ** parameter of any function at any time.  ^The only guarantee is that
4783 ** the destructor will be called before the metadata is dropped.
4784 **
4785 ** ^(In practice, metadata is preserved between function calls for
4786 ** expressions that are constant at compile time. This includes literal
4787 ** values and [parameters].)^
4788 **
4789 ** These routines must be called from the same thread in which
4790 ** the SQL function is running.
4791 */
4792 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
4793 SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
4794
4795
4796 /*
4797 ** CAPI3REF: Constants Defining Special Destructor Behavior
4798 **
4799 ** These are special values for the destructor that is passed in as the
4800 ** final argument to routines like [sqlite3_result_blob()].  ^If the destructor
4801 ** argument is SQLITE_STATIC, it means that the content pointer is constant
4802 ** and will never change.  It does not need to be destroyed.  ^The
4803 ** SQLITE_TRANSIENT value means that the content will likely change in
4804 ** the near future and that SQLite should make its own private copy of
4805 ** the content before returning.
4806 **
4807 ** The typedef is necessary to work around problems in certain
4808 ** C++ compilers.
4809 */
4810 typedef void (*sqlite3_destructor_type)(void*);
4811 #define SQLITE_STATIC      ((sqlite3_destructor_type)0)
4812 #define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
4813
4814 /*
4815 ** CAPI3REF: Setting The Result Of An SQL Function
4816 **
4817 ** These routines are used by the xFunc or xFinal callbacks that
4818 ** implement SQL functions and aggregates.  See
4819 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
4820 ** for additional information.
4821 **
4822 ** These functions work very much like the [parameter binding] family of
4823 ** functions used to bind values to host parameters in prepared statements.
4824 ** Refer to the [SQL parameter] documentation for additional information.
4825 **
4826 ** ^The sqlite3_result_blob() interface sets the result from
4827 ** an application-defined function to be the BLOB whose content is pointed
4828 ** to by the second parameter and which is N bytes long where N is the
4829 ** third parameter.
4830 **
4831 ** ^The sqlite3_result_zeroblob() interfaces set the result of
4832 ** the application-defined function to be a BLOB containing all zero
4833 ** bytes and N bytes in size, where N is the value of the 2nd parameter.
4834 **
4835 ** ^The sqlite3_result_double() interface sets the result from
4836 ** an application-defined function to be a floating point value specified
4837 ** by its 2nd argument.
4838 **
4839 ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
4840 ** cause the implemented SQL function to throw an exception.
4841 ** ^SQLite uses the string pointed to by the
4842 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
4843 ** as the text of an error message.  ^SQLite interprets the error
4844 ** message string from sqlite3_result_error() as UTF-8. ^SQLite
4845 ** interprets the string from sqlite3_result_error16() as UTF-16 in native
4846 ** byte order.  ^If the third parameter to sqlite3_result_error()
4847 ** or sqlite3_result_error16() is negative then SQLite takes as the error
4848 ** message all text up through the first zero character.
4849 ** ^If the third parameter to sqlite3_result_error() or
4850 ** sqlite3_result_error16() is non-negative then SQLite takes that many
4851 ** bytes (not characters) from the 2nd parameter as the error message.
4852 ** ^The sqlite3_result_error() and sqlite3_result_error16()
4853 ** routines make a private copy of the error message text before
4854 ** they return.  Hence, the calling function can deallocate or
4855 ** modify the text after they return without harm.
4856 ** ^The sqlite3_result_error_code() function changes the error code
4857 ** returned by SQLite as a result of an error in a function.  ^By default,
4858 ** the error code is SQLITE_ERROR.  ^A subsequent call to sqlite3_result_error()
4859 ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
4860 **
4861 ** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
4862 ** error indicating that a string or BLOB is too long to represent.
4863 **
4864 ** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
4865 ** error indicating that a memory allocation failed.
4866 **
4867 ** ^The sqlite3_result_int() interface sets the return value
4868 ** of the application-defined function to be the 32-bit signed integer
4869 ** value given in the 2nd argument.
4870 ** ^The sqlite3_result_int64() interface sets the return value
4871 ** of the application-defined function to be the 64-bit signed integer
4872 ** value given in the 2nd argument.
4873 **
4874 ** ^The sqlite3_result_null() interface sets the return value
4875 ** of the application-defined function to be NULL.
4876 **
4877 ** ^The sqlite3_result_text(), sqlite3_result_text16(),
4878 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
4879 ** set the return value of the application-defined function to be
4880 ** a text string which is represented as UTF-8, UTF-16 native byte order,
4881 ** UTF-16 little endian, or UTF-16 big endian, respectively.
4882 ** ^SQLite takes the text result from the application from
4883 ** the 2nd parameter of the sqlite3_result_text* interfaces.
4884 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4885 ** is negative, then SQLite takes result text from the 2nd parameter
4886 ** through the first zero character.
4887 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4888 ** is non-negative, then as many bytes (not characters) of the text
4889 ** pointed to by the 2nd parameter are taken as the application-defined
4890 ** function result.  If the 3rd parameter is non-negative, then it
4891 ** must be the byte offset into the string where the NUL terminator would
4892 ** appear if the string where NUL terminated.  If any NUL characters occur
4893 ** in the string at a byte offset that is less than the value of the 3rd
4894 ** parameter, then the resulting string will contain embedded NULs and the
4895 ** result of expressions operating on strings with embedded NULs is undefined.
4896 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4897 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
4898 ** function as the destructor on the text or BLOB result when it has
4899 ** finished using that result.
4900 ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
4901 ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
4902 ** assumes that the text or BLOB result is in constant space and does not
4903 ** copy the content of the parameter nor call a destructor on the content
4904 ** when it has finished using that result.
4905 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4906 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
4907 ** then SQLite makes a copy of the result into space obtained from
4908 ** from [sqlite3_malloc()] before it returns.
4909 **
4910 ** ^The sqlite3_result_value() interface sets the result of
4911 ** the application-defined function to be a copy the
4912 ** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The
4913 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
4914 ** so that the [sqlite3_value] specified in the parameter may change or
4915 ** be deallocated after sqlite3_result_value() returns without harm.
4916 ** ^A [protected sqlite3_value] object may always be used where an
4917 ** [unprotected sqlite3_value] object is required, so either
4918 ** kind of [sqlite3_value] object can be used with this interface.
4919 **
4920 ** If these routines are called from within the different thread
4921 ** than the one containing the application-defined function that received
4922 ** the [sqlite3_context] pointer, the results are undefined.
4923 */
4924 SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
4925 SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
4926 SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
4927 SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
4928 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
4929 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
4930 SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
4931 SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
4932 SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
4933 SQLITE_API void sqlite3_result_null(sqlite3_context*);
4934 SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
4935 SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
4936 SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
4937 SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
4938 SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
4939 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
4940
4941 /*
4942 ** CAPI3REF: Define New Collating Sequences
4943 **
4944 ** ^These functions add, remove, or modify a [collation] associated
4945 ** with the [database connection] specified as the first argument.
4946 **
4947 ** ^The name of the collation is a UTF-8 string
4948 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
4949 ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
4950 ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
4951 ** considered to be the same name.
4952 **
4953 ** ^(The third argument (eTextRep) must be one of the constants:
4954 ** <ul>
4955 ** <li> [SQLITE_UTF8],
4956 ** <li> [SQLITE_UTF16LE],
4957 ** <li> [SQLITE_UTF16BE],
4958 ** <li> [SQLITE_UTF16], or
4959 ** <li> [SQLITE_UTF16_ALIGNED].
4960 ** </ul>)^
4961 ** ^The eTextRep argument determines the encoding of strings passed
4962 ** to the collating function callback, xCallback.
4963 ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
4964 ** force strings to be UTF16 with native byte order.
4965 ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
4966 ** on an even byte address.
4967 **
4968 ** ^The fourth argument, pArg, is an application data pointer that is passed
4969 ** through as the first argument to the collating function callback.
4970 **
4971 ** ^The fifth argument, xCallback, is a pointer to the collating function.
4972 ** ^Multiple collating functions can be registered using the same name but
4973 ** with different eTextRep parameters and SQLite will use whichever
4974 ** function requires the least amount of data transformation.
4975 ** ^If the xCallback argument is NULL then the collating function is
4976 ** deleted.  ^When all collating functions having the same name are deleted,
4977 ** that collation is no longer usable.
4978 **
4979 ** ^The collating function callback is invoked with a copy of the pArg 
4980 ** application data pointer and with two strings in the encoding specified
4981 ** by the eTextRep argument.  The collating function must return an
4982 ** integer that is negative, zero, or positive
4983 ** if the first string is less than, equal to, or greater than the second,
4984 ** respectively.  A collating function must always return the same answer
4985 ** given the same inputs.  If two or more collating functions are registered
4986 ** to the same collation name (using different eTextRep values) then all
4987 ** must give an equivalent answer when invoked with equivalent strings.
4988 ** The collating function must obey the following properties for all
4989 ** strings A, B, and C:
4990 **
4991 ** <ol>
4992 ** <li> If A==B then B==A.
4993 ** <li> If A==B and B==C then A==C.
4994 ** <li> If A&lt;B THEN B&gt;A.
4995 ** <li> If A&lt;B and B&lt;C then A&lt;C.
4996 ** </ol>
4997 **
4998 ** If a collating function fails any of the above constraints and that
4999 ** collating function is  registered and used, then the behavior of SQLite
5000 ** is undefined.
5001 **
5002 ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
5003 ** with the addition that the xDestroy callback is invoked on pArg when
5004 ** the collating function is deleted.
5005 ** ^Collating functions are deleted when they are overridden by later
5006 ** calls to the collation creation functions or when the
5007 ** [database connection] is closed using [sqlite3_close()].
5008 **
5009 ** ^The xDestroy callback is <u>not</u> called if the 
5010 ** sqlite3_create_collation_v2() function fails.  Applications that invoke
5011 ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should 
5012 ** check the return code and dispose of the application data pointer
5013 ** themselves rather than expecting SQLite to deal with it for them.
5014 ** This is different from every other SQLite interface.  The inconsistency 
5015 ** is unfortunate but cannot be changed without breaking backwards 
5016 ** compatibility.
5017 **
5018 ** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
5019 */
5020 SQLITE_API int sqlite3_create_collation(
5021   sqlite3*, 
5022   const char *zName, 
5023   int eTextRep, 
5024   void *pArg,
5025   int(*xCompare)(void*,int,const void*,int,const void*)
5026 );
5027 SQLITE_API int sqlite3_create_collation_v2(
5028   sqlite3*, 
5029   const char *zName, 
5030   int eTextRep, 
5031   void *pArg,
5032   int(*xCompare)(void*,int,const void*,int,const void*),
5033   void(*xDestroy)(void*)
5034 );
5035 SQLITE_API int sqlite3_create_collation16(
5036   sqlite3*, 
5037   const void *zName,
5038   int eTextRep, 
5039   void *pArg,
5040   int(*xCompare)(void*,int,const void*,int,const void*)
5041 );
5042
5043 /*
5044 ** CAPI3REF: Collation Needed Callbacks
5045 **
5046 ** ^To avoid having to register all collation sequences before a database
5047 ** can be used, a single callback function may be registered with the
5048 ** [database connection] to be invoked whenever an undefined collation
5049 ** sequence is required.
5050 **
5051 ** ^If the function is registered using the sqlite3_collation_needed() API,
5052 ** then it is passed the names of undefined collation sequences as strings
5053 ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
5054 ** the names are passed as UTF-16 in machine native byte order.
5055 ** ^A call to either function replaces the existing collation-needed callback.
5056 **
5057 ** ^(When the callback is invoked, the first argument passed is a copy
5058 ** of the second argument to sqlite3_collation_needed() or
5059 ** sqlite3_collation_needed16().  The second argument is the database
5060 ** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
5061 ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
5062 ** sequence function required.  The fourth parameter is the name of the
5063 ** required collation sequence.)^
5064 **
5065 ** The callback function should register the desired collation using
5066 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
5067 ** [sqlite3_create_collation_v2()].
5068 */
5069 SQLITE_API int sqlite3_collation_needed(
5070   sqlite3*, 
5071   void*, 
5072   void(*)(void*,sqlite3*,int eTextRep,const char*)
5073 );
5074 SQLITE_API int sqlite3_collation_needed16(
5075   sqlite3*, 
5076   void*,
5077   void(*)(void*,sqlite3*,int eTextRep,const void*)
5078 );
5079
5080 #ifdef SQLITE_HAS_CODEC
5081 /*
5082 ** Specify the key for an encrypted database.  This routine should be
5083 ** called right after sqlite3_open().
5084 **
5085 ** The code to implement this API is not available in the public release
5086 ** of SQLite.
5087 */
5088 SQLITE_API int sqlite3_key(
5089   sqlite3 *db,                   /* Database to be rekeyed */
5090   const void *pKey, int nKey     /* The key */
5091 );
5092
5093 /*
5094 ** Change the key on an open database.  If the current database is not
5095 ** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
5096 ** database is decrypted.
5097 **
5098 ** The code to implement this API is not available in the public release
5099 ** of SQLite.
5100 */
5101 SQLITE_API int sqlite3_rekey(
5102   sqlite3 *db,                   /* Database to be rekeyed */
5103   const void *pKey, int nKey     /* The new key */
5104 );
5105
5106 /*
5107 ** Specify the activation key for a SEE database.  Unless 
5108 ** activated, none of the SEE routines will work.
5109 */
5110 SQLITE_API void sqlite3_activate_see(
5111   const char *zPassPhrase        /* Activation phrase */
5112 );
5113 #endif
5114
5115 #ifdef SQLITE_ENABLE_CEROD
5116 /*
5117 ** Specify the activation key for a CEROD database.  Unless 
5118 ** activated, none of the CEROD routines will work.
5119 */
5120 SQLITE_API void sqlite3_activate_cerod(
5121   const char *zPassPhrase        /* Activation phrase */
5122 );
5123 #endif
5124
5125 /*
5126 ** CAPI3REF: Suspend Execution For A Short Time
5127 **
5128 ** The sqlite3_sleep() function causes the current thread to suspend execution
5129 ** for at least a number of milliseconds specified in its parameter.
5130 **
5131 ** If the operating system does not support sleep requests with
5132 ** millisecond time resolution, then the time will be rounded up to
5133 ** the nearest second. The number of milliseconds of sleep actually
5134 ** requested from the operating system is returned.
5135 **
5136 ** ^SQLite implements this interface by calling the xSleep()
5137 ** method of the default [sqlite3_vfs] object.  If the xSleep() method
5138 ** of the default VFS is not implemented correctly, or not implemented at
5139 ** all, then the behavior of sqlite3_sleep() may deviate from the description
5140 ** in the previous paragraphs.
5141 */
5142 SQLITE_API int sqlite3_sleep(int);
5143
5144 /*
5145 ** CAPI3REF: Name Of The Folder Holding Temporary Files
5146 **
5147 ** ^(If this global variable is made to point to a string which is
5148 ** the name of a folder (a.k.a. directory), then all temporary files
5149 ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
5150 ** will be placed in that directory.)^  ^If this variable
5151 ** is a NULL pointer, then SQLite performs a search for an appropriate
5152 ** temporary file directory.
5153 **
5154 ** It is not safe to read or modify this variable in more than one
5155 ** thread at a time.  It is not safe to read or modify this variable
5156 ** if a [database connection] is being used at the same time in a separate
5157 ** thread.
5158 ** It is intended that this variable be set once
5159 ** as part of process initialization and before any SQLite interface
5160 ** routines have been called and that this variable remain unchanged
5161 ** thereafter.
5162 **
5163 ** ^The [temp_store_directory pragma] may modify this variable and cause
5164 ** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
5165 ** the [temp_store_directory pragma] always assumes that any string
5166 ** that this variable points to is held in memory obtained from 
5167 ** [sqlite3_malloc] and the pragma may attempt to free that memory
5168 ** using [sqlite3_free].
5169 ** Hence, if this variable is modified directly, either it should be
5170 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
5171 ** or else the use of the [temp_store_directory pragma] should be avoided.
5172 **
5173 ** <b>Note to Windows Runtime users:</b>  The temporary directory must be set
5174 ** prior to calling [sqlite3_open] or [sqlite3_open_v2].  Otherwise, various
5175 ** features that require the use of temporary files may fail.  Here is an
5176 ** example of how to do this using C++ with the Windows Runtime:
5177 **
5178 ** <blockquote><pre>
5179 ** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
5180 ** &nbsp;     TemporaryFolder->Path->Data();
5181 ** char zPathBuf&#91;MAX_PATH + 1&#93;;
5182 ** memset(zPathBuf, 0, sizeof(zPathBuf));
5183 ** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
5184 ** &nbsp;     NULL, NULL);
5185 ** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
5186 ** </pre></blockquote>
5187 */
5188 SQLITE_API char *sqlite3_temp_directory;
5189
5190 /*
5191 ** CAPI3REF: Name Of The Folder Holding Database Files
5192 **
5193 ** ^(If this global variable is made to point to a string which is
5194 ** the name of a folder (a.k.a. directory), then all database files
5195 ** specified with a relative pathname and created or accessed by
5196 ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
5197 ** to be relative to that directory.)^ ^If this variable is a NULL
5198 ** pointer, then SQLite assumes that all database files specified
5199 ** with a relative pathname are relative to the current directory
5200 ** for the process.  Only the windows VFS makes use of this global
5201 ** variable; it is ignored by the unix VFS.
5202 **
5203 ** Changing the value of this variable while a database connection is
5204 ** open can result in a corrupt database.
5205 **
5206 ** It is not safe to read or modify this variable in more than one
5207 ** thread at a time.  It is not safe to read or modify this variable
5208 ** if a [database connection] is being used at the same time in a separate
5209 ** thread.
5210 ** It is intended that this variable be set once
5211 ** as part of process initialization and before any SQLite interface
5212 ** routines have been called and that this variable remain unchanged
5213 ** thereafter.
5214 **
5215 ** ^The [data_store_directory pragma] may modify this variable and cause
5216 ** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
5217 ** the [data_store_directory pragma] always assumes that any string
5218 ** that this variable points to is held in memory obtained from 
5219 ** [sqlite3_malloc] and the pragma may attempt to free that memory
5220 ** using [sqlite3_free].
5221 ** Hence, if this variable is modified directly, either it should be
5222 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
5223 ** or else the use of the [data_store_directory pragma] should be avoided.
5224 */
5225 SQLITE_API char *sqlite3_data_directory;
5226
5227 /*
5228 ** CAPI3REF: Test For Auto-Commit Mode
5229 ** KEYWORDS: {autocommit mode}
5230 **
5231 ** ^The sqlite3_get_autocommit() interface returns non-zero or
5232 ** zero if the given database connection is or is not in autocommit mode,
5233 ** respectively.  ^Autocommit mode is on by default.
5234 ** ^Autocommit mode is disabled by a [BEGIN] statement.
5235 ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
5236 **
5237 ** If certain kinds of errors occur on a statement within a multi-statement
5238 ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
5239 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
5240 ** transaction might be rolled back automatically.  The only way to
5241 ** find out whether SQLite automatically rolled back the transaction after
5242 ** an error is to use this function.
5243 **
5244 ** If another thread changes the autocommit status of the database
5245 ** connection while this routine is running, then the return value
5246 ** is undefined.
5247 */
5248 SQLITE_API int sqlite3_get_autocommit(sqlite3*);
5249
5250 /*
5251 ** CAPI3REF: Find The Database Handle Of A Prepared Statement
5252 **
5253 ** ^The sqlite3_db_handle interface returns the [database connection] handle
5254 ** to which a [prepared statement] belongs.  ^The [database connection]
5255 ** returned by sqlite3_db_handle is the same [database connection]
5256 ** that was the first argument
5257 ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
5258 ** create the statement in the first place.
5259 */
5260 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
5261
5262 /*
5263 ** CAPI3REF: Return The Filename For A Database Connection
5264 **
5265 ** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
5266 ** associated with database N of connection D.  ^The main database file
5267 ** has the name "main".  If there is no attached database N on the database
5268 ** connection D, or if database N is a temporary or in-memory database, then
5269 ** a NULL pointer is returned.
5270 **
5271 ** ^The filename returned by this function is the output of the
5272 ** xFullPathname method of the [VFS].  ^In other words, the filename
5273 ** will be an absolute pathname, even if the filename used
5274 ** to open the database originally was a URI or relative pathname.
5275 */
5276 SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
5277
5278 /*
5279 ** CAPI3REF: Determine if a database is read-only
5280 **
5281 ** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
5282 ** of connection D is read-only, 0 if it is read/write, or -1 if N is not
5283 ** the name of a database on connection D.
5284 */
5285 SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
5286
5287 /*
5288 ** CAPI3REF: Find the next prepared statement
5289 **
5290 ** ^This interface returns a pointer to the next [prepared statement] after
5291 ** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL
5292 ** then this interface returns a pointer to the first prepared statement
5293 ** associated with the database connection pDb.  ^If no prepared statement
5294 ** satisfies the conditions of this routine, it returns NULL.
5295 **
5296 ** The [database connection] pointer D in a call to
5297 ** [sqlite3_next_stmt(D,S)] must refer to an open database
5298 ** connection and in particular must not be a NULL pointer.
5299 */
5300 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
5301
5302 /*
5303 ** CAPI3REF: Commit And Rollback Notification Callbacks
5304 **
5305 ** ^The sqlite3_commit_hook() interface registers a callback
5306 ** function to be invoked whenever a transaction is [COMMIT | committed].
5307 ** ^Any callback set by a previous call to sqlite3_commit_hook()
5308 ** for the same database connection is overridden.
5309 ** ^The sqlite3_rollback_hook() interface registers a callback
5310 ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
5311 ** ^Any callback set by a previous call to sqlite3_rollback_hook()
5312 ** for the same database connection is overridden.
5313 ** ^The pArg argument is passed through to the callback.
5314 ** ^If the callback on a commit hook function returns non-zero,
5315 ** then the commit is converted into a rollback.
5316 **
5317 ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
5318 ** return the P argument from the previous call of the same function
5319 ** on the same [database connection] D, or NULL for
5320 ** the first call for each function on D.
5321 **
5322 ** The commit and rollback hook callbacks are not reentrant.
5323 ** The callback implementation must not do anything that will modify
5324 ** the database connection that invoked the callback.  Any actions
5325 ** to modify the database connection must be deferred until after the
5326 ** completion of the [sqlite3_step()] call that triggered the commit
5327 ** or rollback hook in the first place.
5328 ** Note that running any other SQL statements, including SELECT statements,
5329 ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
5330 ** the database connections for the meaning of "modify" in this paragraph.
5331 **
5332 ** ^Registering a NULL function disables the callback.
5333 **
5334 ** ^When the commit hook callback routine returns zero, the [COMMIT]
5335 ** operation is allowed to continue normally.  ^If the commit hook
5336 ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
5337 ** ^The rollback hook is invoked on a rollback that results from a commit
5338 ** hook returning non-zero, just as it would be with any other rollback.
5339 **
5340 ** ^For the purposes of this API, a transaction is said to have been
5341 ** rolled back if an explicit "ROLLBACK" statement is executed, or
5342 ** an error or constraint causes an implicit rollback to occur.
5343 ** ^The rollback callback is not invoked if a transaction is
5344 ** automatically rolled back because the database connection is closed.
5345 **
5346 ** See also the [sqlite3_update_hook()] interface.
5347 */
5348 SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
5349 SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
5350
5351 /*
5352 ** CAPI3REF: Data Change Notification Callbacks
5353 **
5354 ** ^The sqlite3_update_hook() interface registers a callback function
5355 ** with the [database connection] identified by the first argument
5356 ** to be invoked whenever a row is updated, inserted or deleted.
5357 ** ^Any callback set by a previous call to this function
5358 ** for the same database connection is overridden.
5359 **
5360 ** ^The second argument is a pointer to the function to invoke when a
5361 ** row is updated, inserted or deleted.
5362 ** ^The first argument to the callback is a copy of the third argument
5363 ** to sqlite3_update_hook().
5364 ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
5365 ** or [SQLITE_UPDATE], depending on the operation that caused the callback
5366 ** to be invoked.
5367 ** ^The third and fourth arguments to the callback contain pointers to the
5368 ** database and table name containing the affected row.
5369 ** ^The final callback parameter is the [rowid] of the row.
5370 ** ^In the case of an update, this is the [rowid] after the update takes place.
5371 **
5372 ** ^(The update hook is not invoked when internal system tables are
5373 ** modified (i.e. sqlite_master and sqlite_sequence).)^
5374 **
5375 ** ^In the current implementation, the update hook
5376 ** is not invoked when duplication rows are deleted because of an
5377 ** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook
5378 ** invoked when rows are deleted using the [truncate optimization].
5379 ** The exceptions defined in this paragraph might change in a future
5380 ** release of SQLite.
5381 **
5382 ** The update hook implementation must not do anything that will modify
5383 ** the database connection that invoked the update hook.  Any actions
5384 ** to modify the database connection must be deferred until after the
5385 ** completion of the [sqlite3_step()] call that triggered the update hook.
5386 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
5387 ** database connections for the meaning of "modify" in this paragraph.
5388 **
5389 ** ^The sqlite3_update_hook(D,C,P) function
5390 ** returns the P argument from the previous call
5391 ** on the same [database connection] D, or NULL for
5392 ** the first call on D.
5393 **
5394 ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
5395 ** interfaces.
5396 */
5397 SQLITE_API void *sqlite3_update_hook(
5398   sqlite3*, 
5399   void(*)(void *,int ,char const *,char const *,sqlite3_int64),
5400   void*
5401 );
5402
5403 /*
5404 ** CAPI3REF: Enable Or Disable Shared Pager Cache
5405 **
5406 ** ^(This routine enables or disables the sharing of the database cache
5407 ** and schema data structures between [database connection | connections]
5408 ** to the same database. Sharing is enabled if the argument is true
5409 ** and disabled if the argument is false.)^
5410 **
5411 ** ^Cache sharing is enabled and disabled for an entire process.
5412 ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
5413 ** sharing was enabled or disabled for each thread separately.
5414 **
5415 ** ^(The cache sharing mode set by this interface effects all subsequent
5416 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
5417 ** Existing database connections continue use the sharing mode
5418 ** that was in effect at the time they were opened.)^
5419 **
5420 ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
5421 ** successfully.  An [error code] is returned otherwise.)^
5422 **
5423 ** ^Shared cache is disabled by default. But this might change in
5424 ** future releases of SQLite.  Applications that care about shared
5425 ** cache setting should set it explicitly.
5426 **
5427 ** This interface is threadsafe on processors where writing a
5428 ** 32-bit integer is atomic.
5429 **
5430 ** See Also:  [SQLite Shared-Cache Mode]
5431 */
5432 SQLITE_API int sqlite3_enable_shared_cache(int);
5433
5434 /*
5435 ** CAPI3REF: Attempt To Free Heap Memory
5436 **
5437 ** ^The sqlite3_release_memory() interface attempts to free N bytes
5438 ** of heap memory by deallocating non-essential memory allocations
5439 ** held by the database library.   Memory used to cache database
5440 ** pages to improve performance is an example of non-essential memory.
5441 ** ^sqlite3_release_memory() returns the number of bytes actually freed,
5442 ** which might be more or less than the amount requested.
5443 ** ^The sqlite3_release_memory() routine is a no-op returning zero
5444 ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5445 **
5446 ** See also: [sqlite3_db_release_memory()]
5447 */
5448 SQLITE_API int sqlite3_release_memory(int);
5449
5450 /*
5451 ** CAPI3REF: Free Memory Used By A Database Connection
5452 **
5453 ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
5454 ** memory as possible from database connection D. Unlike the
5455 ** [sqlite3_release_memory()] interface, this interface is effect even
5456 ** when then [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
5457 ** omitted.
5458 **
5459 ** See also: [sqlite3_release_memory()]
5460 */
5461 SQLITE_API int sqlite3_db_release_memory(sqlite3*);
5462
5463 /*
5464 ** CAPI3REF: Impose A Limit On Heap Size
5465 **
5466 ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
5467 ** soft limit on the amount of heap memory that may be allocated by SQLite.
5468 ** ^SQLite strives to keep heap memory utilization below the soft heap
5469 ** limit by reducing the number of pages held in the page cache
5470 ** as heap memory usages approaches the limit.
5471 ** ^The soft heap limit is "soft" because even though SQLite strives to stay
5472 ** below the limit, it will exceed the limit rather than generate
5473 ** an [SQLITE_NOMEM] error.  In other words, the soft heap limit 
5474 ** is advisory only.
5475 **
5476 ** ^The return value from sqlite3_soft_heap_limit64() is the size of
5477 ** the soft heap limit prior to the call, or negative in the case of an
5478 ** error.  ^If the argument N is negative
5479 ** then no change is made to the soft heap limit.  Hence, the current
5480 ** size of the soft heap limit can be determined by invoking
5481 ** sqlite3_soft_heap_limit64() with a negative argument.
5482 **
5483 ** ^If the argument N is zero then the soft heap limit is disabled.
5484 **
5485 ** ^(The soft heap limit is not enforced in the current implementation
5486 ** if one or more of following conditions are true:
5487 **
5488 ** <ul>
5489 ** <li> The soft heap limit is set to zero.
5490 ** <li> Memory accounting is disabled using a combination of the
5491 **      [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
5492 **      the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
5493 ** <li> An alternative page cache implementation is specified using
5494 **      [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
5495 ** <li> The page cache allocates from its own memory pool supplied
5496 **      by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
5497 **      from the heap.
5498 ** </ul>)^
5499 **
5500 ** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
5501 ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
5502 ** compile-time option is invoked.  With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
5503 ** the soft heap limit is enforced on every memory allocation.  Without
5504 ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
5505 ** when memory is allocated by the page cache.  Testing suggests that because
5506 ** the page cache is the predominate memory user in SQLite, most
5507 ** applications will achieve adequate soft heap limit enforcement without
5508 ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5509 **
5510 ** The circumstances under which SQLite will enforce the soft heap limit may
5511 ** changes in future releases of SQLite.
5512 */
5513 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
5514
5515 /*
5516 ** CAPI3REF: Deprecated Soft Heap Limit Interface
5517 ** DEPRECATED
5518 **
5519 ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
5520 ** interface.  This routine is provided for historical compatibility
5521 ** only.  All new applications should use the
5522 ** [sqlite3_soft_heap_limit64()] interface rather than this one.
5523 */
5524 SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
5525
5526
5527 /*
5528 ** CAPI3REF: Extract Metadata About A Column Of A Table
5529 **
5530 ** ^This routine returns metadata about a specific column of a specific
5531 ** database table accessible using the [database connection] handle
5532 ** passed as the first function argument.
5533 **
5534 ** ^The column is identified by the second, third and fourth parameters to
5535 ** this function. ^The second parameter is either the name of the database
5536 ** (i.e. "main", "temp", or an attached database) containing the specified
5537 ** table or NULL. ^If it is NULL, then all attached databases are searched
5538 ** for the table using the same algorithm used by the database engine to
5539 ** resolve unqualified table references.
5540 **
5541 ** ^The third and fourth parameters to this function are the table and column
5542 ** name of the desired column, respectively. Neither of these parameters
5543 ** may be NULL.
5544 **
5545 ** ^Metadata is returned by writing to the memory locations passed as the 5th
5546 ** and subsequent parameters to this function. ^Any of these arguments may be
5547 ** NULL, in which case the corresponding element of metadata is omitted.
5548 **
5549 ** ^(<blockquote>
5550 ** <table border="1">
5551 ** <tr><th> Parameter <th> Output<br>Type <th>  Description
5552 **
5553 ** <tr><td> 5th <td> const char* <td> Data type
5554 ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
5555 ** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
5556 ** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
5557 ** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]
5558 ** </table>
5559 ** </blockquote>)^
5560 **
5561 ** ^The memory pointed to by the character pointers returned for the
5562 ** declaration type and collation sequence is valid only until the next
5563 ** call to any SQLite API function.
5564 **
5565 ** ^If the specified table is actually a view, an [error code] is returned.
5566 **
5567 ** ^If the specified column is "rowid", "oid" or "_rowid_" and an
5568 ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
5569 ** parameters are set for the explicitly declared column. ^(If there is no
5570 ** explicitly declared [INTEGER PRIMARY KEY] column, then the output
5571 ** parameters are set as follows:
5572 **
5573 ** <pre>
5574 **     data type: "INTEGER"
5575 **     collation sequence: "BINARY"
5576 **     not null: 0
5577 **     primary key: 1
5578 **     auto increment: 0
5579 ** </pre>)^
5580 **
5581 ** ^(This function may load one or more schemas from database files. If an
5582 ** error occurs during this process, or if the requested table or column
5583 ** cannot be found, an [error code] is returned and an error message left
5584 ** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^
5585 **
5586 ** ^This API is only available if the library was compiled with the
5587 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
5588 */
5589 SQLITE_API int sqlite3_table_column_metadata(
5590   sqlite3 *db,                /* Connection handle */
5591   const char *zDbName,        /* Database name or NULL */
5592   const char *zTableName,     /* Table name */
5593   const char *zColumnName,    /* Column name */
5594   char const **pzDataType,    /* OUTPUT: Declared data type */
5595   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
5596   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
5597   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
5598   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
5599 );
5600
5601 /*
5602 ** CAPI3REF: Load An Extension
5603 **
5604 ** ^This interface loads an SQLite extension library from the named file.
5605 **
5606 ** ^The sqlite3_load_extension() interface attempts to load an
5607 ** [SQLite extension] library contained in the file zFile.  If
5608 ** the file cannot be loaded directly, attempts are made to load
5609 ** with various operating-system specific extensions added.
5610 ** So for example, if "samplelib" cannot be loaded, then names like
5611 ** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
5612 ** be tried also.
5613 **
5614 ** ^The entry point is zProc.
5615 ** ^(zProc may be 0, in which case SQLite will try to come up with an
5616 ** entry point name on its own.  It first tries "sqlite3_extension_init".
5617 ** If that does not work, it constructs a name "sqlite3_X_init" where the
5618 ** X is consists of the lower-case equivalent of all ASCII alphabetic
5619 ** characters in the filename from the last "/" to the first following
5620 ** "." and omitting any initial "lib".)^
5621 ** ^The sqlite3_load_extension() interface returns
5622 ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
5623 ** ^If an error occurs and pzErrMsg is not 0, then the
5624 ** [sqlite3_load_extension()] interface shall attempt to
5625 ** fill *pzErrMsg with error message text stored in memory
5626 ** obtained from [sqlite3_malloc()]. The calling function
5627 ** should free this memory by calling [sqlite3_free()].
5628 **
5629 ** ^Extension loading must be enabled using
5630 ** [sqlite3_enable_load_extension()] prior to calling this API,
5631 ** otherwise an error will be returned.
5632 **
5633 ** See also the [load_extension() SQL function].
5634 */
5635 SQLITE_API int sqlite3_load_extension(
5636   sqlite3 *db,          /* Load the extension into this database connection */
5637   const char *zFile,    /* Name of the shared library containing extension */
5638   const char *zProc,    /* Entry point.  Derived from zFile if 0 */
5639   char **pzErrMsg       /* Put error message here if not 0 */
5640 );
5641
5642 /*
5643 ** CAPI3REF: Enable Or Disable Extension Loading
5644 **
5645 ** ^So as not to open security holes in older applications that are
5646 ** unprepared to deal with [extension loading], and as a means of disabling
5647 ** [extension loading] while evaluating user-entered SQL, the following API
5648 ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
5649 **
5650 ** ^Extension loading is off by default.
5651 ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
5652 ** to turn extension loading on and call it with onoff==0 to turn
5653 ** it back off again.
5654 */
5655 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
5656
5657 /*
5658 ** CAPI3REF: Automatically Load Statically Linked Extensions
5659 **
5660 ** ^This interface causes the xEntryPoint() function to be invoked for
5661 ** each new [database connection] that is created.  The idea here is that
5662 ** xEntryPoint() is the entry point for a statically linked [SQLite extension]
5663 ** that is to be automatically loaded into all new database connections.
5664 **
5665 ** ^(Even though the function prototype shows that xEntryPoint() takes
5666 ** no arguments and returns void, SQLite invokes xEntryPoint() with three
5667 ** arguments and expects and integer result as if the signature of the
5668 ** entry point where as follows:
5669 **
5670 ** <blockquote><pre>
5671 ** &nbsp;  int xEntryPoint(
5672 ** &nbsp;    sqlite3 *db,
5673 ** &nbsp;    const char **pzErrMsg,
5674 ** &nbsp;    const struct sqlite3_api_routines *pThunk
5675 ** &nbsp;  );
5676 ** </pre></blockquote>)^
5677 **
5678 ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
5679 ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
5680 ** and return an appropriate [error code].  ^SQLite ensures that *pzErrMsg
5681 ** is NULL before calling the xEntryPoint().  ^SQLite will invoke
5682 ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns.  ^If any
5683 ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
5684 ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
5685 **
5686 ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
5687 ** on the list of automatic extensions is a harmless no-op. ^No entry point
5688 ** will be called more than once for each database connection that is opened.
5689 **
5690 ** See also: [sqlite3_reset_auto_extension()].
5691 */
5692 SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
5693
5694 /*
5695 ** CAPI3REF: Reset Automatic Extension Loading
5696 **
5697 ** ^This interface disables all automatic extensions previously
5698 ** registered using [sqlite3_auto_extension()].
5699 */
5700 SQLITE_API void sqlite3_reset_auto_extension(void);
5701
5702 /*
5703 ** The interface to the virtual-table mechanism is currently considered
5704 ** to be experimental.  The interface might change in incompatible ways.
5705 ** If this is a problem for you, do not use the interface at this time.
5706 **
5707 ** When the virtual-table mechanism stabilizes, we will declare the
5708 ** interface fixed, support it indefinitely, and remove this comment.
5709 */
5710
5711 /*
5712 ** Structures used by the virtual table interface
5713 */
5714 typedef struct sqlite3_vtab sqlite3_vtab;
5715 typedef struct sqlite3_index_info sqlite3_index_info;
5716 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
5717 typedef struct sqlite3_module sqlite3_module;
5718
5719 /*
5720 ** CAPI3REF: Virtual Table Object
5721 ** KEYWORDS: sqlite3_module {virtual table module}
5722 **
5723 ** This structure, sometimes called a "virtual table module", 
5724 ** defines the implementation of a [virtual tables].  
5725 ** This structure consists mostly of methods for the module.
5726 **
5727 ** ^A virtual table module is created by filling in a persistent
5728 ** instance of this structure and passing a pointer to that instance
5729 ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
5730 ** ^The registration remains valid until it is replaced by a different
5731 ** module or until the [database connection] closes.  The content
5732 ** of this structure must not change while it is registered with
5733 ** any database connection.
5734 */
5735 struct sqlite3_module {
5736   int iVersion;
5737   int (*xCreate)(sqlite3*, void *pAux,
5738                int argc, const char *const*argv,
5739                sqlite3_vtab **ppVTab, char**);
5740   int (*xConnect)(sqlite3*, void *pAux,
5741                int argc, const char *const*argv,
5742                sqlite3_vtab **ppVTab, char**);
5743   int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
5744   int (*xDisconnect)(sqlite3_vtab *pVTab);
5745   int (*xDestroy)(sqlite3_vtab *pVTab);
5746   int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
5747   int (*xClose)(sqlite3_vtab_cursor*);
5748   int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
5749                 int argc, sqlite3_value **argv);
5750   int (*xNext)(sqlite3_vtab_cursor*);
5751   int (*xEof)(sqlite3_vtab_cursor*);
5752   int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
5753   int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
5754   int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
5755   int (*xBegin)(sqlite3_vtab *pVTab);
5756   int (*xSync)(sqlite3_vtab *pVTab);
5757   int (*xCommit)(sqlite3_vtab *pVTab);
5758   int (*xRollback)(sqlite3_vtab *pVTab);
5759   int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
5760                        void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
5761                        void **ppArg);
5762   int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
5763   /* The methods above are in version 1 of the sqlite_module object. Those 
5764   ** below are for version 2 and greater. */
5765   int (*xSavepoint)(sqlite3_vtab *pVTab, int);
5766   int (*xRelease)(sqlite3_vtab *pVTab, int);
5767   int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
5768 };
5769
5770 /*
5771 ** CAPI3REF: Virtual Table Indexing Information
5772 ** KEYWORDS: sqlite3_index_info
5773 **
5774 ** The sqlite3_index_info structure and its substructures is used as part
5775 ** of the [virtual table] interface to
5776 ** pass information into and receive the reply from the [xBestIndex]
5777 ** method of a [virtual table module].  The fields under **Inputs** are the
5778 ** inputs to xBestIndex and are read-only.  xBestIndex inserts its
5779 ** results into the **Outputs** fields.
5780 **
5781 ** ^(The aConstraint[] array records WHERE clause constraints of the form:
5782 **
5783 ** <blockquote>column OP expr</blockquote>
5784 **
5785 ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is
5786 ** stored in aConstraint[].op using one of the
5787 ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
5788 ** ^(The index of the column is stored in
5789 ** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the
5790 ** expr on the right-hand side can be evaluated (and thus the constraint
5791 ** is usable) and false if it cannot.)^
5792 **
5793 ** ^The optimizer automatically inverts terms of the form "expr OP column"
5794 ** and makes other simplifications to the WHERE clause in an attempt to
5795 ** get as many WHERE clause terms into the form shown above as possible.
5796 ** ^The aConstraint[] array only reports WHERE clause terms that are
5797 ** relevant to the particular virtual table being queried.
5798 **
5799 ** ^Information about the ORDER BY clause is stored in aOrderBy[].
5800 ** ^Each term of aOrderBy records a column of the ORDER BY clause.
5801 **
5802 ** The [xBestIndex] method must fill aConstraintUsage[] with information
5803 ** about what parameters to pass to xFilter.  ^If argvIndex>0 then
5804 ** the right-hand side of the corresponding aConstraint[] is evaluated
5805 ** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit
5806 ** is true, then the constraint is assumed to be fully handled by the
5807 ** virtual table and is not checked again by SQLite.)^
5808 **
5809 ** ^The idxNum and idxPtr values are recorded and passed into the
5810 ** [xFilter] method.
5811 ** ^[sqlite3_free()] is used to free idxPtr if and only if
5812 ** needToFreeIdxPtr is true.
5813 **
5814 ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
5815 ** the correct order to satisfy the ORDER BY clause so that no separate
5816 ** sorting step is required.
5817 **
5818 ** ^The estimatedCost value is an estimate of the cost of doing the
5819 ** particular lookup.  A full scan of a table with N entries should have
5820 ** a cost of N.  A binary search of a table of N entries should have a
5821 ** cost of approximately log(N).
5822 */
5823 struct sqlite3_index_info {
5824   /* Inputs */
5825   int nConstraint;           /* Number of entries in aConstraint */
5826   struct sqlite3_index_constraint {
5827      int iColumn;              /* Column on left-hand side of constraint */
5828      unsigned char op;         /* Constraint operator */
5829      unsigned char usable;     /* True if this constraint is usable */
5830      int iTermOffset;          /* Used internally - xBestIndex should ignore */
5831   } *aConstraint;            /* Table of WHERE clause constraints */
5832   int nOrderBy;              /* Number of terms in the ORDER BY clause */
5833   struct sqlite3_index_orderby {
5834      int iColumn;              /* Column number */
5835      unsigned char desc;       /* True for DESC.  False for ASC. */
5836   } *aOrderBy;               /* The ORDER BY clause */
5837   /* Outputs */
5838   struct sqlite3_index_constraint_usage {
5839     int argvIndex;           /* if >0, constraint is part of argv to xFilter */
5840     unsigned char omit;      /* Do not code a test for this constraint */
5841   } *aConstraintUsage;
5842   int idxNum;                /* Number used to identify the index */
5843   char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
5844   int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
5845   int orderByConsumed;       /* True if output is already ordered */
5846   double estimatedCost;      /* Estimated cost of using this index */
5847 };
5848
5849 /*
5850 ** CAPI3REF: Virtual Table Constraint Operator Codes
5851 **
5852 ** These macros defined the allowed values for the
5853 ** [sqlite3_index_info].aConstraint[].op field.  Each value represents
5854 ** an operator that is part of a constraint term in the wHERE clause of
5855 ** a query that uses a [virtual table].
5856 */
5857 #define SQLITE_INDEX_CONSTRAINT_EQ    2
5858 #define SQLITE_INDEX_CONSTRAINT_GT    4
5859 #define SQLITE_INDEX_CONSTRAINT_LE    8
5860 #define SQLITE_INDEX_CONSTRAINT_LT    16
5861 #define SQLITE_INDEX_CONSTRAINT_GE    32
5862 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
5863
5864 /*
5865 ** CAPI3REF: Register A Virtual Table Implementation
5866 **
5867 ** ^These routines are used to register a new [virtual table module] name.
5868 ** ^Module names must be registered before
5869 ** creating a new [virtual table] using the module and before using a
5870 ** preexisting [virtual table] for the module.
5871 **
5872 ** ^The module name is registered on the [database connection] specified
5873 ** by the first parameter.  ^The name of the module is given by the 
5874 ** second parameter.  ^The third parameter is a pointer to
5875 ** the implementation of the [virtual table module].   ^The fourth
5876 ** parameter is an arbitrary client data pointer that is passed through
5877 ** into the [xCreate] and [xConnect] methods of the virtual table module
5878 ** when a new virtual table is be being created or reinitialized.
5879 **
5880 ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
5881 ** is a pointer to a destructor for the pClientData.  ^SQLite will
5882 ** invoke the destructor function (if it is not NULL) when SQLite
5883 ** no longer needs the pClientData pointer.  ^The destructor will also
5884 ** be invoked if the call to sqlite3_create_module_v2() fails.
5885 ** ^The sqlite3_create_module()
5886 ** interface is equivalent to sqlite3_create_module_v2() with a NULL
5887 ** destructor.
5888 */
5889 SQLITE_API int sqlite3_create_module(
5890   sqlite3 *db,               /* SQLite connection to register module with */
5891   const char *zName,         /* Name of the module */
5892   const sqlite3_module *p,   /* Methods for the module */
5893   void *pClientData          /* Client data for xCreate/xConnect */
5894 );
5895 SQLITE_API int sqlite3_create_module_v2(
5896   sqlite3 *db,               /* SQLite connection to register module with */
5897   const char *zName,         /* Name of the module */
5898   const sqlite3_module *p,   /* Methods for the module */
5899   void *pClientData,         /* Client data for xCreate/xConnect */
5900   void(*xDestroy)(void*)     /* Module destructor function */
5901 );
5902
5903 /*
5904 ** CAPI3REF: Virtual Table Instance Object
5905 ** KEYWORDS: sqlite3_vtab
5906 **
5907 ** Every [virtual table module] implementation uses a subclass
5908 ** of this object to describe a particular instance
5909 ** of the [virtual table].  Each subclass will
5910 ** be tailored to the specific needs of the module implementation.
5911 ** The purpose of this superclass is to define certain fields that are
5912 ** common to all module implementations.
5913 **
5914 ** ^Virtual tables methods can set an error message by assigning a
5915 ** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should
5916 ** take care that any prior string is freed by a call to [sqlite3_free()]
5917 ** prior to assigning a new string to zErrMsg.  ^After the error message
5918 ** is delivered up to the client application, the string will be automatically
5919 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
5920 */
5921 struct sqlite3_vtab {
5922   const sqlite3_module *pModule;  /* The module for this virtual table */
5923   int nRef;                       /* NO LONGER USED */
5924   char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
5925   /* Virtual table implementations will typically add additional fields */
5926 };
5927
5928 /*
5929 ** CAPI3REF: Virtual Table Cursor Object
5930 ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
5931 **
5932 ** Every [virtual table module] implementation uses a subclass of the
5933 ** following structure to describe cursors that point into the
5934 ** [virtual table] and are used
5935 ** to loop through the virtual table.  Cursors are created using the
5936 ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
5937 ** by the [sqlite3_module.xClose | xClose] method.  Cursors are used
5938 ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
5939 ** of the module.  Each module implementation will define
5940 ** the content of a cursor structure to suit its own needs.
5941 **
5942 ** This superclass exists in order to define fields of the cursor that
5943 ** are common to all implementations.
5944 */
5945 struct sqlite3_vtab_cursor {
5946   sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
5947   /* Virtual table implementations will typically add additional fields */
5948 };
5949
5950 /*
5951 ** CAPI3REF: Declare The Schema Of A Virtual Table
5952 **
5953 ** ^The [xCreate] and [xConnect] methods of a
5954 ** [virtual table module] call this interface
5955 ** to declare the format (the names and datatypes of the columns) of
5956 ** the virtual tables they implement.
5957 */
5958 SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
5959
5960 /*
5961 ** CAPI3REF: Overload A Function For A Virtual Table
5962 **
5963 ** ^(Virtual tables can provide alternative implementations of functions
5964 ** using the [xFindFunction] method of the [virtual table module].  
5965 ** But global versions of those functions
5966 ** must exist in order to be overloaded.)^
5967 **
5968 ** ^(This API makes sure a global version of a function with a particular
5969 ** name and number of parameters exists.  If no such function exists
5970 ** before this API is called, a new function is created.)^  ^The implementation
5971 ** of the new function always causes an exception to be thrown.  So
5972 ** the new function is not good for anything by itself.  Its only
5973 ** purpose is to be a placeholder function that can be overloaded
5974 ** by a [virtual table].
5975 */
5976 SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
5977
5978 /*
5979 ** The interface to the virtual-table mechanism defined above (back up
5980 ** to a comment remarkably similar to this one) is currently considered
5981 ** to be experimental.  The interface might change in incompatible ways.
5982 ** If this is a problem for you, do not use the interface at this time.
5983 **
5984 ** When the virtual-table mechanism stabilizes, we will declare the
5985 ** interface fixed, support it indefinitely, and remove this comment.
5986 */
5987
5988 /*
5989 ** CAPI3REF: A Handle To An Open BLOB
5990 ** KEYWORDS: {BLOB handle} {BLOB handles}
5991 **
5992 ** An instance of this object represents an open BLOB on which
5993 ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
5994 ** ^Objects of this type are created by [sqlite3_blob_open()]
5995 ** and destroyed by [sqlite3_blob_close()].
5996 ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
5997 ** can be used to read or write small subsections of the BLOB.
5998 ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
5999 */
6000 typedef struct sqlite3_blob sqlite3_blob;
6001
6002 /*
6003 ** CAPI3REF: Open A BLOB For Incremental I/O
6004 **
6005 ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
6006 ** in row iRow, column zColumn, table zTable in database zDb;
6007 ** in other words, the same BLOB that would be selected by:
6008 **
6009 ** <pre>
6010 **     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
6011 ** </pre>)^
6012 **
6013 ** ^If the flags parameter is non-zero, then the BLOB is opened for read
6014 ** and write access. ^If it is zero, the BLOB is opened for read access.
6015 ** ^It is not possible to open a column that is part of an index or primary 
6016 ** key for writing. ^If [foreign key constraints] are enabled, it is 
6017 ** not possible to open a column that is part of a [child key] for writing.
6018 **
6019 ** ^Note that the database name is not the filename that contains
6020 ** the database but rather the symbolic name of the database that
6021 ** appears after the AS keyword when the database is connected using [ATTACH].
6022 ** ^For the main database file, the database name is "main".
6023 ** ^For TEMP tables, the database name is "temp".
6024 **
6025 ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
6026 ** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
6027 ** to be a null pointer.)^
6028 ** ^This function sets the [database connection] error code and message
6029 ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related
6030 ** functions. ^Note that the *ppBlob variable is always initialized in a
6031 ** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob
6032 ** regardless of the success or failure of this routine.
6033 **
6034 ** ^(If the row that a BLOB handle points to is modified by an
6035 ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
6036 ** then the BLOB handle is marked as "expired".
6037 ** This is true if any column of the row is changed, even a column
6038 ** other than the one the BLOB handle is open on.)^
6039 ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
6040 ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
6041 ** ^(Changes written into a BLOB prior to the BLOB expiring are not
6042 ** rolled back by the expiration of the BLOB.  Such changes will eventually
6043 ** commit if the transaction continues to completion.)^
6044 **
6045 ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
6046 ** the opened blob.  ^The size of a blob may not be changed by this
6047 ** interface.  Use the [UPDATE] SQL command to change the size of a
6048 ** blob.
6049 **
6050 ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
6051 ** and the built-in [zeroblob] SQL function can be used, if desired,
6052 ** to create an empty, zero-filled blob in which to read or write using
6053 ** this interface.
6054 **
6055 ** To avoid a resource leak, every open [BLOB handle] should eventually
6056 ** be released by a call to [sqlite3_blob_close()].
6057 */
6058 SQLITE_API int sqlite3_blob_open(
6059   sqlite3*,
6060   const char *zDb,
6061   const char *zTable,
6062   const char *zColumn,
6063   sqlite3_int64 iRow,
6064   int flags,
6065   sqlite3_blob **ppBlob
6066 );
6067
6068 /*
6069 ** CAPI3REF: Move a BLOB Handle to a New Row
6070 **
6071 ** ^This function is used to move an existing blob handle so that it points
6072 ** to a different row of the same database table. ^The new row is identified
6073 ** by the rowid value passed as the second argument. Only the row can be
6074 ** changed. ^The database, table and column on which the blob handle is open
6075 ** remain the same. Moving an existing blob handle to a new row can be
6076 ** faster than closing the existing handle and opening a new one.
6077 **
6078 ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
6079 ** it must exist and there must be either a blob or text value stored in
6080 ** the nominated column.)^ ^If the new row is not present in the table, or if
6081 ** it does not contain a blob or text value, or if another error occurs, an
6082 ** SQLite error code is returned and the blob handle is considered aborted.
6083 ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
6084 ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
6085 ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
6086 ** always returns zero.
6087 **
6088 ** ^This function sets the database handle error code and message.
6089 */
6090 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
6091
6092 /*
6093 ** CAPI3REF: Close A BLOB Handle
6094 **
6095 ** ^Closes an open [BLOB handle].
6096 **
6097 ** ^Closing a BLOB shall cause the current transaction to commit
6098 ** if there are no other BLOBs, no pending prepared statements, and the
6099 ** database connection is in [autocommit mode].
6100 ** ^If any writes were made to the BLOB, they might be held in cache
6101 ** until the close operation if they will fit.
6102 **
6103 ** ^(Closing the BLOB often forces the changes
6104 ** out to disk and so if any I/O errors occur, they will likely occur
6105 ** at the time when the BLOB is closed.  Any errors that occur during
6106 ** closing are reported as a non-zero return value.)^
6107 **
6108 ** ^(The BLOB is closed unconditionally.  Even if this routine returns
6109 ** an error code, the BLOB is still closed.)^
6110 **
6111 ** ^Calling this routine with a null pointer (such as would be returned
6112 ** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.
6113 */
6114 SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
6115
6116 /*
6117 ** CAPI3REF: Return The Size Of An Open BLOB
6118 **
6119 ** ^Returns the size in bytes of the BLOB accessible via the 
6120 ** successfully opened [BLOB handle] in its only argument.  ^The
6121 ** incremental blob I/O routines can only read or overwriting existing
6122 ** blob content; they cannot change the size of a blob.
6123 **
6124 ** This routine only works on a [BLOB handle] which has been created
6125 ** by a prior successful call to [sqlite3_blob_open()] and which has not
6126 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
6127 ** to this routine results in undefined and probably undesirable behavior.
6128 */
6129 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
6130
6131 /*
6132 ** CAPI3REF: Read Data From A BLOB Incrementally
6133 **
6134 ** ^(This function is used to read data from an open [BLOB handle] into a
6135 ** caller-supplied buffer. N bytes of data are copied into buffer Z
6136 ** from the open BLOB, starting at offset iOffset.)^
6137 **
6138 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
6139 ** [SQLITE_ERROR] is returned and no data is read.  ^If N or iOffset is
6140 ** less than zero, [SQLITE_ERROR] is returned and no data is read.
6141 ** ^The size of the blob (and hence the maximum value of N+iOffset)
6142 ** can be determined using the [sqlite3_blob_bytes()] interface.
6143 **
6144 ** ^An attempt to read from an expired [BLOB handle] fails with an
6145 ** error code of [SQLITE_ABORT].
6146 **
6147 ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
6148 ** Otherwise, an [error code] or an [extended error code] is returned.)^
6149 **
6150 ** This routine only works on a [BLOB handle] which has been created
6151 ** by a prior successful call to [sqlite3_blob_open()] and which has not
6152 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
6153 ** to this routine results in undefined and probably undesirable behavior.
6154 **
6155 ** See also: [sqlite3_blob_write()].
6156 */
6157 SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
6158
6159 /*
6160 ** CAPI3REF: Write Data Into A BLOB Incrementally
6161 **
6162 ** ^This function is used to write data into an open [BLOB handle] from a
6163 ** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
6164 ** into the open BLOB, starting at offset iOffset.
6165 **
6166 ** ^If the [BLOB handle] passed as the first argument was not opened for
6167 ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
6168 ** this function returns [SQLITE_READONLY].
6169 **
6170 ** ^This function may only modify the contents of the BLOB; it is
6171 ** not possible to increase the size of a BLOB using this API.
6172 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
6173 ** [SQLITE_ERROR] is returned and no data is written.  ^If N is
6174 ** less than zero [SQLITE_ERROR] is returned and no data is written.
6175 ** The size of the BLOB (and hence the maximum value of N+iOffset)
6176 ** can be determined using the [sqlite3_blob_bytes()] interface.
6177 **
6178 ** ^An attempt to write to an expired [BLOB handle] fails with an
6179 ** error code of [SQLITE_ABORT].  ^Writes to the BLOB that occurred
6180 ** before the [BLOB handle] expired are not rolled back by the
6181 ** expiration of the handle, though of course those changes might
6182 ** have been overwritten by the statement that expired the BLOB handle
6183 ** or by other independent statements.
6184 **
6185 ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
6186 ** Otherwise, an  [error code] or an [extended error code] is returned.)^
6187 **
6188 ** This routine only works on a [BLOB handle] which has been created
6189 ** by a prior successful call to [sqlite3_blob_open()] and which has not
6190 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
6191 ** to this routine results in undefined and probably undesirable behavior.
6192 **
6193 ** See also: [sqlite3_blob_read()].
6194 */
6195 SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
6196
6197 /*
6198 ** CAPI3REF: Virtual File System Objects
6199 **
6200 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
6201 ** that SQLite uses to interact
6202 ** with the underlying operating system.  Most SQLite builds come with a
6203 ** single default VFS that is appropriate for the host computer.
6204 ** New VFSes can be registered and existing VFSes can be unregistered.
6205 ** The following interfaces are provided.
6206 **
6207 ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
6208 ** ^Names are case sensitive.
6209 ** ^Names are zero-terminated UTF-8 strings.
6210 ** ^If there is no match, a NULL pointer is returned.
6211 ** ^If zVfsName is NULL then the default VFS is returned.
6212 **
6213 ** ^New VFSes are registered with sqlite3_vfs_register().
6214 ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
6215 ** ^The same VFS can be registered multiple times without injury.
6216 ** ^To make an existing VFS into the default VFS, register it again
6217 ** with the makeDflt flag set.  If two different VFSes with the
6218 ** same name are registered, the behavior is undefined.  If a
6219 ** VFS is registered with a name that is NULL or an empty string,
6220 ** then the behavior is undefined.
6221 **
6222 ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
6223 ** ^(If the default VFS is unregistered, another VFS is chosen as
6224 ** the default.  The choice for the new VFS is arbitrary.)^
6225 */
6226 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
6227 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
6228 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
6229
6230 /*
6231 ** CAPI3REF: Mutexes
6232 **
6233 ** The SQLite core uses these routines for thread
6234 ** synchronization. Though they are intended for internal
6235 ** use by SQLite, code that links against SQLite is
6236 ** permitted to use any of these routines.
6237 **
6238 ** The SQLite source code contains multiple implementations
6239 ** of these mutex routines.  An appropriate implementation
6240 ** is selected automatically at compile-time.  ^(The following
6241 ** implementations are available in the SQLite core:
6242 **
6243 ** <ul>
6244 ** <li>   SQLITE_MUTEX_PTHREADS
6245 ** <li>   SQLITE_MUTEX_W32
6246 ** <li>   SQLITE_MUTEX_NOOP
6247 ** </ul>)^
6248 **
6249 ** ^The SQLITE_MUTEX_NOOP implementation is a set of routines
6250 ** that does no real locking and is appropriate for use in
6251 ** a single-threaded application.  ^The SQLITE_MUTEX_PTHREADS and
6252 ** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
6253 ** and Windows.
6254 **
6255 ** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
6256 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
6257 ** implementation is included with the library. In this case the
6258 ** application must supply a custom mutex implementation using the
6259 ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
6260 ** before calling sqlite3_initialize() or any other public sqlite3_
6261 ** function that calls sqlite3_initialize().)^
6262 **
6263 ** ^The sqlite3_mutex_alloc() routine allocates a new
6264 ** mutex and returns a pointer to it. ^If it returns NULL
6265 ** that means that a mutex could not be allocated.  ^SQLite
6266 ** will unwind its stack and return an error.  ^(The argument
6267 ** to sqlite3_mutex_alloc() is one of these integer constants:
6268 **
6269 ** <ul>
6270 ** <li>  SQLITE_MUTEX_FAST
6271 ** <li>  SQLITE_MUTEX_RECURSIVE
6272 ** <li>  SQLITE_MUTEX_STATIC_MASTER
6273 ** <li>  SQLITE_MUTEX_STATIC_MEM
6274 ** <li>  SQLITE_MUTEX_STATIC_MEM2
6275 ** <li>  SQLITE_MUTEX_STATIC_PRNG
6276 ** <li>  SQLITE_MUTEX_STATIC_LRU
6277 ** <li>  SQLITE_MUTEX_STATIC_LRU2
6278 ** </ul>)^
6279 **
6280 ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
6281 ** cause sqlite3_mutex_alloc() to create
6282 ** a new mutex.  ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
6283 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
6284 ** The mutex implementation does not need to make a distinction
6285 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
6286 ** not want to.  ^SQLite will only request a recursive mutex in
6287 ** cases where it really needs one.  ^If a faster non-recursive mutex
6288 ** implementation is available on the host platform, the mutex subsystem
6289 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
6290 **
6291 ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
6292 ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
6293 ** a pointer to a static preexisting mutex.  ^Six static mutexes are
6294 ** used by the current version of SQLite.  Future versions of SQLite
6295 ** may add additional static mutexes.  Static mutexes are for internal
6296 ** use by SQLite only.  Applications that use SQLite mutexes should
6297 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
6298 ** SQLITE_MUTEX_RECURSIVE.
6299 **
6300 ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
6301 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
6302 ** returns a different mutex on every call.  ^But for the static
6303 ** mutex types, the same mutex is returned on every call that has
6304 ** the same type number.
6305 **
6306 ** ^The sqlite3_mutex_free() routine deallocates a previously
6307 ** allocated dynamic mutex.  ^SQLite is careful to deallocate every
6308 ** dynamic mutex that it allocates.  The dynamic mutexes must not be in
6309 ** use when they are deallocated.  Attempting to deallocate a static
6310 ** mutex results in undefined behavior.  ^SQLite never deallocates
6311 ** a static mutex.
6312 **
6313 ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
6314 ** to enter a mutex.  ^If another thread is already within the mutex,
6315 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
6316 ** SQLITE_BUSY.  ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
6317 ** upon successful entry.  ^(Mutexes created using
6318 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
6319 ** In such cases the,
6320 ** mutex must be exited an equal number of times before another thread
6321 ** can enter.)^  ^(If the same thread tries to enter any other
6322 ** kind of mutex more than once, the behavior is undefined.
6323 ** SQLite will never exhibit
6324 ** such behavior in its own use of mutexes.)^
6325 **
6326 ** ^(Some systems (for example, Windows 95) do not support the operation
6327 ** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
6328 ** will always return SQLITE_BUSY.  The SQLite core only ever uses
6329 ** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^
6330 **
6331 ** ^The sqlite3_mutex_leave() routine exits a mutex that was
6332 ** previously entered by the same thread.   ^(The behavior
6333 ** is undefined if the mutex is not currently entered by the
6334 ** calling thread or is not currently allocated.  SQLite will
6335 ** never do either.)^
6336 **
6337 ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
6338 ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
6339 ** behave as no-ops.
6340 **
6341 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
6342 */
6343 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
6344 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
6345 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
6346 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
6347 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
6348
6349 /*
6350 ** CAPI3REF: Mutex Methods Object
6351 **
6352 ** An instance of this structure defines the low-level routines
6353 ** used to allocate and use mutexes.
6354 **
6355 ** Usually, the default mutex implementations provided by SQLite are
6356 ** sufficient, however the user has the option of substituting a custom
6357 ** implementation for specialized deployments or systems for which SQLite
6358 ** does not provide a suitable implementation. In this case, the user
6359 ** creates and populates an instance of this structure to pass
6360 ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
6361 ** Additionally, an instance of this structure can be used as an
6362 ** output variable when querying the system for the current mutex
6363 ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
6364 **
6365 ** ^The xMutexInit method defined by this structure is invoked as
6366 ** part of system initialization by the sqlite3_initialize() function.
6367 ** ^The xMutexInit routine is called by SQLite exactly once for each
6368 ** effective call to [sqlite3_initialize()].
6369 **
6370 ** ^The xMutexEnd method defined by this structure is invoked as
6371 ** part of system shutdown by the sqlite3_shutdown() function. The
6372 ** implementation of this method is expected to release all outstanding
6373 ** resources obtained by the mutex methods implementation, especially
6374 ** those obtained by the xMutexInit method.  ^The xMutexEnd()
6375 ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
6376 **
6377 ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
6378 ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
6379 ** xMutexNotheld) implement the following interfaces (respectively):
6380 **
6381 ** <ul>
6382 **   <li>  [sqlite3_mutex_alloc()] </li>
6383 **   <li>  [sqlite3_mutex_free()] </li>
6384 **   <li>  [sqlite3_mutex_enter()] </li>
6385 **   <li>  [sqlite3_mutex_try()] </li>
6386 **   <li>  [sqlite3_mutex_leave()] </li>
6387 **   <li>  [sqlite3_mutex_held()] </li>
6388 **   <li>  [sqlite3_mutex_notheld()] </li>
6389 ** </ul>)^
6390 **
6391 ** The only difference is that the public sqlite3_XXX functions enumerated
6392 ** above silently ignore any invocations that pass a NULL pointer instead
6393 ** of a valid mutex handle. The implementations of the methods defined
6394 ** by this structure are not required to handle this case, the results
6395 ** of passing a NULL pointer instead of a valid mutex handle are undefined
6396 ** (i.e. it is acceptable to provide an implementation that segfaults if
6397 ** it is passed a NULL pointer).
6398 **
6399 ** The xMutexInit() method must be threadsafe.  ^It must be harmless to
6400 ** invoke xMutexInit() multiple times within the same process and without
6401 ** intervening calls to xMutexEnd().  Second and subsequent calls to
6402 ** xMutexInit() must be no-ops.
6403 **
6404 ** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
6405 ** and its associates).  ^Similarly, xMutexAlloc() must not use SQLite memory
6406 ** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite
6407 ** memory allocation for a fast or recursive mutex.
6408 **
6409 ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
6410 ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
6411 ** If xMutexInit fails in any way, it is expected to clean up after itself
6412 ** prior to returning.
6413 */
6414 typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
6415 struct sqlite3_mutex_methods {
6416   int (*xMutexInit)(void);
6417   int (*xMutexEnd)(void);
6418   sqlite3_mutex *(*xMutexAlloc)(int);
6419   void (*xMutexFree)(sqlite3_mutex *);
6420   void (*xMutexEnter)(sqlite3_mutex *);
6421   int (*xMutexTry)(sqlite3_mutex *);
6422   void (*xMutexLeave)(sqlite3_mutex *);
6423   int (*xMutexHeld)(sqlite3_mutex *);
6424   int (*xMutexNotheld)(sqlite3_mutex *);
6425 };
6426
6427 /*
6428 ** CAPI3REF: Mutex Verification Routines
6429 **
6430 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
6431 ** are intended for use inside assert() statements.  ^The SQLite core
6432 ** never uses these routines except inside an assert() and applications
6433 ** are advised to follow the lead of the core.  ^The SQLite core only
6434 ** provides implementations for these routines when it is compiled
6435 ** with the SQLITE_DEBUG flag.  ^External mutex implementations
6436 ** are only required to provide these routines if SQLITE_DEBUG is
6437 ** defined and if NDEBUG is not defined.
6438 **
6439 ** ^These routines should return true if the mutex in their argument
6440 ** is held or not held, respectively, by the calling thread.
6441 **
6442 ** ^The implementation is not required to provide versions of these
6443 ** routines that actually work. If the implementation does not provide working
6444 ** versions of these routines, it should at least provide stubs that always
6445 ** return true so that one does not get spurious assertion failures.
6446 **
6447 ** ^If the argument to sqlite3_mutex_held() is a NULL pointer then
6448 ** the routine should return 1.   This seems counter-intuitive since
6449 ** clearly the mutex cannot be held if it does not exist.  But
6450 ** the reason the mutex does not exist is because the build is not
6451 ** using mutexes.  And we do not want the assert() containing the
6452 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
6453 ** the appropriate thing to do.  ^The sqlite3_mutex_notheld()
6454 ** interface should also return 1 when given a NULL pointer.
6455 */
6456 #ifndef NDEBUG
6457 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
6458 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
6459 #endif
6460
6461 /*
6462 ** CAPI3REF: Mutex Types
6463 **
6464 ** The [sqlite3_mutex_alloc()] interface takes a single argument
6465 ** which is one of these integer constants.
6466 **
6467 ** The set of static mutexes may change from one SQLite release to the
6468 ** next.  Applications that override the built-in mutex logic must be
6469 ** prepared to accommodate additional static mutexes.
6470 */
6471 #define SQLITE_MUTEX_FAST             0
6472 #define SQLITE_MUTEX_RECURSIVE        1
6473 #define SQLITE_MUTEX_STATIC_MASTER    2
6474 #define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
6475 #define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */
6476 #define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */
6477 #define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
6478 #define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
6479 #define SQLITE_MUTEX_STATIC_LRU2      7  /* NOT USED */
6480 #define SQLITE_MUTEX_STATIC_PMEM      7  /* sqlite3PageMalloc() */
6481
6482 /*
6483 ** CAPI3REF: Retrieve the mutex for a database connection
6484 **
6485 ** ^This interface returns a pointer the [sqlite3_mutex] object that 
6486 ** serializes access to the [database connection] given in the argument
6487 ** when the [threading mode] is Serialized.
6488 ** ^If the [threading mode] is Single-thread or Multi-thread then this
6489 ** routine returns a NULL pointer.
6490 */
6491 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
6492
6493 /*
6494 ** CAPI3REF: Low-Level Control Of Database Files
6495 **
6496 ** ^The [sqlite3_file_control()] interface makes a direct call to the
6497 ** xFileControl method for the [sqlite3_io_methods] object associated
6498 ** with a particular database identified by the second argument. ^The
6499 ** name of the database is "main" for the main database or "temp" for the
6500 ** TEMP database, or the name that appears after the AS keyword for
6501 ** databases that are added using the [ATTACH] SQL command.
6502 ** ^A NULL pointer can be used in place of "main" to refer to the
6503 ** main database file.
6504 ** ^The third and fourth parameters to this routine
6505 ** are passed directly through to the second and third parameters of
6506 ** the xFileControl method.  ^The return value of the xFileControl
6507 ** method becomes the return value of this routine.
6508 **
6509 ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
6510 ** a pointer to the underlying [sqlite3_file] object to be written into
6511 ** the space pointed to by the 4th parameter.  ^The SQLITE_FCNTL_FILE_POINTER
6512 ** case is a short-circuit path which does not actually invoke the
6513 ** underlying sqlite3_io_methods.xFileControl method.
6514 **
6515 ** ^If the second parameter (zDbName) does not match the name of any
6516 ** open database file, then SQLITE_ERROR is returned.  ^This error
6517 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
6518 ** or [sqlite3_errmsg()].  The underlying xFileControl method might
6519 ** also return SQLITE_ERROR.  There is no way to distinguish between
6520 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
6521 ** xFileControl method.
6522 **
6523 ** See also: [SQLITE_FCNTL_LOCKSTATE]
6524 */
6525 SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
6526
6527 /*
6528 ** CAPI3REF: Testing Interface
6529 **
6530 ** ^The sqlite3_test_control() interface is used to read out internal
6531 ** state of SQLite and to inject faults into SQLite for testing
6532 ** purposes.  ^The first parameter is an operation code that determines
6533 ** the number, meaning, and operation of all subsequent parameters.
6534 **
6535 ** This interface is not for use by applications.  It exists solely
6536 ** for verifying the correct operation of the SQLite library.  Depending
6537 ** on how the SQLite library is compiled, this interface might not exist.
6538 **
6539 ** The details of the operation codes, their meanings, the parameters
6540 ** they take, and what they do are all subject to change without notice.
6541 ** Unlike most of the SQLite API, this function is not guaranteed to
6542 ** operate consistently from one release to the next.
6543 */
6544 SQLITE_API int sqlite3_test_control(int op, ...);
6545
6546 /*
6547 ** CAPI3REF: Testing Interface Operation Codes
6548 **
6549 ** These constants are the valid operation code parameters used
6550 ** as the first argument to [sqlite3_test_control()].
6551 **
6552 ** These parameters and their meanings are subject to change
6553 ** without notice.  These values are for testing purposes only.
6554 ** Applications should not use any of these parameters or the
6555 ** [sqlite3_test_control()] interface.
6556 */
6557 #define SQLITE_TESTCTRL_FIRST                    5
6558 #define SQLITE_TESTCTRL_PRNG_SAVE                5
6559 #define SQLITE_TESTCTRL_PRNG_RESTORE             6
6560 #define SQLITE_TESTCTRL_PRNG_RESET               7
6561 #define SQLITE_TESTCTRL_BITVEC_TEST              8
6562 #define SQLITE_TESTCTRL_FAULT_INSTALL            9
6563 #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
6564 #define SQLITE_TESTCTRL_PENDING_BYTE            11
6565 #define SQLITE_TESTCTRL_ASSERT                  12
6566 #define SQLITE_TESTCTRL_ALWAYS                  13
6567 #define SQLITE_TESTCTRL_RESERVE                 14
6568 #define SQLITE_TESTCTRL_OPTIMIZATIONS           15
6569 #define SQLITE_TESTCTRL_ISKEYWORD               16
6570 #define SQLITE_TESTCTRL_SCRATCHMALLOC           17
6571 #define SQLITE_TESTCTRL_LOCALTIME_FAULT         18
6572 #define SQLITE_TESTCTRL_EXPLAIN_STMT            19
6573 #define SQLITE_TESTCTRL_LAST                    19
6574
6575 /*
6576 ** CAPI3REF: SQLite Runtime Status
6577 **
6578 ** ^This interface is used to retrieve runtime status information
6579 ** about the performance of SQLite, and optionally to reset various
6580 ** highwater marks.  ^The first argument is an integer code for
6581 ** the specific parameter to measure.  ^(Recognized integer codes
6582 ** are of the form [status parameters | SQLITE_STATUS_...].)^
6583 ** ^The current value of the parameter is returned into *pCurrent.
6584 ** ^The highest recorded value is returned in *pHighwater.  ^If the
6585 ** resetFlag is true, then the highest record value is reset after
6586 ** *pHighwater is written.  ^(Some parameters do not record the highest
6587 ** value.  For those parameters
6588 ** nothing is written into *pHighwater and the resetFlag is ignored.)^
6589 ** ^(Other parameters record only the highwater mark and not the current
6590 ** value.  For these latter parameters nothing is written into *pCurrent.)^
6591 **
6592 ** ^The sqlite3_status() routine returns SQLITE_OK on success and a
6593 ** non-zero [error code] on failure.
6594 **
6595 ** This routine is threadsafe but is not atomic.  This routine can be
6596 ** called while other threads are running the same or different SQLite
6597 ** interfaces.  However the values returned in *pCurrent and
6598 ** *pHighwater reflect the status of SQLite at different points in time
6599 ** and it is possible that another thread might change the parameter
6600 ** in between the times when *pCurrent and *pHighwater are written.
6601 **
6602 ** See also: [sqlite3_db_status()]
6603 */
6604 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
6605
6606
6607 /*
6608 ** CAPI3REF: Status Parameters
6609 ** KEYWORDS: {status parameters}
6610 **
6611 ** These integer constants designate various run-time status parameters
6612 ** that can be returned by [sqlite3_status()].
6613 **
6614 ** <dl>
6615 ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
6616 ** <dd>This parameter is the current amount of memory checked out
6617 ** using [sqlite3_malloc()], either directly or indirectly.  The
6618 ** figure includes calls made to [sqlite3_malloc()] by the application
6619 ** and internal memory usage by the SQLite library.  Scratch memory
6620 ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
6621 ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
6622 ** this parameter.  The amount returned is the sum of the allocation
6623 ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
6624 **
6625 ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
6626 ** <dd>This parameter records the largest memory allocation request
6627 ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
6628 ** internal equivalents).  Only the value returned in the
6629 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
6630 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6631 **
6632 ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
6633 ** <dd>This parameter records the number of separate memory allocations
6634 ** currently checked out.</dd>)^
6635 **
6636 ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
6637 ** <dd>This parameter returns the number of pages used out of the
6638 ** [pagecache memory allocator] that was configured using 
6639 ** [SQLITE_CONFIG_PAGECACHE].  The
6640 ** value returned is in pages, not in bytes.</dd>)^
6641 **
6642 ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]] 
6643 ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
6644 ** <dd>This parameter returns the number of bytes of page cache
6645 ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
6646 ** buffer and where forced to overflow to [sqlite3_malloc()].  The
6647 ** returned value includes allocations that overflowed because they
6648 ** where too large (they were larger than the "sz" parameter to
6649 ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
6650 ** no space was left in the page cache.</dd>)^
6651 **
6652 ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
6653 ** <dd>This parameter records the largest memory allocation request
6654 ** handed to [pagecache memory allocator].  Only the value returned in the
6655 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
6656 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6657 **
6658 ** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
6659 ** <dd>This parameter returns the number of allocations used out of the
6660 ** [scratch memory allocator] configured using
6661 ** [SQLITE_CONFIG_SCRATCH].  The value returned is in allocations, not
6662 ** in bytes.  Since a single thread may only have one scratch allocation
6663 ** outstanding at time, this parameter also reports the number of threads
6664 ** using scratch memory at the same time.</dd>)^
6665 **
6666 ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
6667 ** <dd>This parameter returns the number of bytes of scratch memory
6668 ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
6669 ** buffer and where forced to overflow to [sqlite3_malloc()].  The values
6670 ** returned include overflows because the requested allocation was too
6671 ** larger (that is, because the requested allocation was larger than the
6672 ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
6673 ** slots were available.
6674 ** </dd>)^
6675 **
6676 ** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
6677 ** <dd>This parameter records the largest memory allocation request
6678 ** handed to [scratch memory allocator].  Only the value returned in the
6679 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
6680 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6681 **
6682 ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
6683 ** <dd>This parameter records the deepest parser stack.  It is only
6684 ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
6685 ** </dl>
6686 **
6687 ** New status parameters may be added from time to time.
6688 */
6689 #define SQLITE_STATUS_MEMORY_USED          0
6690 #define SQLITE_STATUS_PAGECACHE_USED       1
6691 #define SQLITE_STATUS_PAGECACHE_OVERFLOW   2
6692 #define SQLITE_STATUS_SCRATCH_USED         3
6693 #define SQLITE_STATUS_SCRATCH_OVERFLOW     4
6694 #define SQLITE_STATUS_MALLOC_SIZE          5
6695 #define SQLITE_STATUS_PARSER_STACK         6
6696 #define SQLITE_STATUS_PAGECACHE_SIZE       7
6697 #define SQLITE_STATUS_SCRATCH_SIZE         8
6698 #define SQLITE_STATUS_MALLOC_COUNT         9
6699
6700 /*
6701 ** CAPI3REF: Database Connection Status
6702 **
6703 ** ^This interface is used to retrieve runtime status information 
6704 ** about a single [database connection].  ^The first argument is the
6705 ** database connection object to be interrogated.  ^The second argument
6706 ** is an integer constant, taken from the set of
6707 ** [SQLITE_DBSTATUS options], that
6708 ** determines the parameter to interrogate.  The set of 
6709 ** [SQLITE_DBSTATUS options] is likely
6710 ** to grow in future releases of SQLite.
6711 **
6712 ** ^The current value of the requested parameter is written into *pCur
6713 ** and the highest instantaneous value is written into *pHiwtr.  ^If
6714 ** the resetFlg is true, then the highest instantaneous value is
6715 ** reset back down to the current value.
6716 **
6717 ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
6718 ** non-zero [error code] on failure.
6719 **
6720 ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
6721 */
6722 SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
6723
6724 /*
6725 ** CAPI3REF: Status Parameters for database connections
6726 ** KEYWORDS: {SQLITE_DBSTATUS options}
6727 **
6728 ** These constants are the available integer "verbs" that can be passed as
6729 ** the second argument to the [sqlite3_db_status()] interface.
6730 **
6731 ** New verbs may be added in future releases of SQLite. Existing verbs
6732 ** might be discontinued. Applications should check the return code from
6733 ** [sqlite3_db_status()] to make sure that the call worked.
6734 ** The [sqlite3_db_status()] interface will return a non-zero error code
6735 ** if a discontinued or unsupported verb is invoked.
6736 **
6737 ** <dl>
6738 ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
6739 ** <dd>This parameter returns the number of lookaside memory slots currently
6740 ** checked out.</dd>)^
6741 **
6742 ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
6743 ** <dd>This parameter returns the number malloc attempts that were 
6744 ** satisfied using lookaside memory. Only the high-water value is meaningful;
6745 ** the current value is always zero.)^
6746 **
6747 ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
6748 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
6749 ** <dd>This parameter returns the number malloc attempts that might have
6750 ** been satisfied using lookaside memory but failed due to the amount of
6751 ** memory requested being larger than the lookaside slot size.
6752 ** Only the high-water value is meaningful;
6753 ** the current value is always zero.)^
6754 **
6755 ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
6756 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
6757 ** <dd>This parameter returns the number malloc attempts that might have
6758 ** been satisfied using lookaside memory but failed due to all lookaside
6759 ** memory already being in use.
6760 ** Only the high-water value is meaningful;
6761 ** the current value is always zero.)^
6762 **
6763 ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
6764 ** <dd>This parameter returns the approximate number of of bytes of heap
6765 ** memory used by all pager caches associated with the database connection.)^
6766 ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
6767 **
6768 ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
6769 ** <dd>This parameter returns the approximate number of of bytes of heap
6770 ** memory used to store the schema for all databases associated
6771 ** with the connection - main, temp, and any [ATTACH]-ed databases.)^ 
6772 ** ^The full amount of memory used by the schemas is reported, even if the
6773 ** schema memory is shared with other database connections due to
6774 ** [shared cache mode] being enabled.
6775 ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
6776 **
6777 ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
6778 ** <dd>This parameter returns the approximate number of of bytes of heap
6779 ** and lookaside memory used by all prepared statements associated with
6780 ** the database connection.)^
6781 ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
6782 ** </dd>
6783 **
6784 ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
6785 ** <dd>This parameter returns the number of pager cache hits that have
6786 ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT 
6787 ** is always 0.
6788 ** </dd>
6789 **
6790 ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
6791 ** <dd>This parameter returns the number of pager cache misses that have
6792 ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS 
6793 ** is always 0.
6794 ** </dd>
6795 **
6796 ** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
6797 ** <dd>This parameter returns the number of dirty cache entries that have
6798 ** been written to disk. Specifically, the number of pages written to the
6799 ** wal file in wal mode databases, or the number of pages written to the
6800 ** database file in rollback mode databases. Any pages written as part of
6801 ** transaction rollback or database recovery operations are not included.
6802 ** If an IO or other error occurs while writing a page to disk, the effect
6803 ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
6804 ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
6805 ** </dd>
6806 ** </dl>
6807 */
6808 #define SQLITE_DBSTATUS_LOOKASIDE_USED       0
6809 #define SQLITE_DBSTATUS_CACHE_USED           1
6810 #define SQLITE_DBSTATUS_SCHEMA_USED          2
6811 #define SQLITE_DBSTATUS_STMT_USED            3
6812 #define SQLITE_DBSTATUS_LOOKASIDE_HIT        4
6813 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE  5
6814 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL  6
6815 #define SQLITE_DBSTATUS_CACHE_HIT            7
6816 #define SQLITE_DBSTATUS_CACHE_MISS           8
6817 #define SQLITE_DBSTATUS_CACHE_WRITE          9
6818 #define SQLITE_DBSTATUS_MAX                  9   /* Largest defined DBSTATUS */
6819
6820
6821 /*
6822 ** CAPI3REF: Prepared Statement Status
6823 **
6824 ** ^(Each prepared statement maintains various
6825 ** [SQLITE_STMTSTATUS counters] that measure the number
6826 ** of times it has performed specific operations.)^  These counters can
6827 ** be used to monitor the performance characteristics of the prepared
6828 ** statements.  For example, if the number of table steps greatly exceeds
6829 ** the number of table searches or result rows, that would tend to indicate
6830 ** that the prepared statement is using a full table scan rather than
6831 ** an index.  
6832 **
6833 ** ^(This interface is used to retrieve and reset counter values from
6834 ** a [prepared statement].  The first argument is the prepared statement
6835 ** object to be interrogated.  The second argument
6836 ** is an integer code for a specific [SQLITE_STMTSTATUS counter]
6837 ** to be interrogated.)^
6838 ** ^The current value of the requested counter is returned.
6839 ** ^If the resetFlg is true, then the counter is reset to zero after this
6840 ** interface call returns.
6841 **
6842 ** See also: [sqlite3_status()] and [sqlite3_db_status()].
6843 */
6844 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
6845
6846 /*
6847 ** CAPI3REF: Status Parameters for prepared statements
6848 ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
6849 **
6850 ** These preprocessor macros define integer codes that name counter
6851 ** values associated with the [sqlite3_stmt_status()] interface.
6852 ** The meanings of the various counters are as follows:
6853 **
6854 ** <dl>
6855 ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
6856 ** <dd>^This is the number of times that SQLite has stepped forward in
6857 ** a table as part of a full table scan.  Large numbers for this counter
6858 ** may indicate opportunities for performance improvement through 
6859 ** careful use of indices.</dd>
6860 **
6861 ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
6862 ** <dd>^This is the number of sort operations that have occurred.
6863 ** A non-zero value in this counter may indicate an opportunity to
6864 ** improvement performance through careful use of indices.</dd>
6865 **
6866 ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
6867 ** <dd>^This is the number of rows inserted into transient indices that
6868 ** were created automatically in order to help joins run faster.
6869 ** A non-zero value in this counter may indicate an opportunity to
6870 ** improvement performance by adding permanent indices that do not
6871 ** need to be reinitialized each time the statement is run.</dd>
6872 ** </dl>
6873 */
6874 #define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
6875 #define SQLITE_STMTSTATUS_SORT              2
6876 #define SQLITE_STMTSTATUS_AUTOINDEX         3
6877
6878 /*
6879 ** CAPI3REF: Custom Page Cache Object
6880 **
6881 ** The sqlite3_pcache type is opaque.  It is implemented by
6882 ** the pluggable module.  The SQLite core has no knowledge of
6883 ** its size or internal structure and never deals with the
6884 ** sqlite3_pcache object except by holding and passing pointers
6885 ** to the object.
6886 **
6887 ** See [sqlite3_pcache_methods2] for additional information.
6888 */
6889 typedef struct sqlite3_pcache sqlite3_pcache;
6890
6891 /*
6892 ** CAPI3REF: Custom Page Cache Object
6893 **
6894 ** The sqlite3_pcache_page object represents a single page in the
6895 ** page cache.  The page cache will allocate instances of this
6896 ** object.  Various methods of the page cache use pointers to instances
6897 ** of this object as parameters or as their return value.
6898 **
6899 ** See [sqlite3_pcache_methods2] for additional information.
6900 */
6901 typedef struct sqlite3_pcache_page sqlite3_pcache_page;
6902 struct sqlite3_pcache_page {
6903   void *pBuf;        /* The content of the page */
6904   void *pExtra;      /* Extra information associated with the page */
6905 };
6906
6907 /*
6908 ** CAPI3REF: Application Defined Page Cache.
6909 ** KEYWORDS: {page cache}
6910 **
6911 ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
6912 ** register an alternative page cache implementation by passing in an 
6913 ** instance of the sqlite3_pcache_methods2 structure.)^
6914 ** In many applications, most of the heap memory allocated by 
6915 ** SQLite is used for the page cache.
6916 ** By implementing a 
6917 ** custom page cache using this API, an application can better control
6918 ** the amount of memory consumed by SQLite, the way in which 
6919 ** that memory is allocated and released, and the policies used to 
6920 ** determine exactly which parts of a database file are cached and for 
6921 ** how long.
6922 **
6923 ** The alternative page cache mechanism is an
6924 ** extreme measure that is only needed by the most demanding applications.
6925 ** The built-in page cache is recommended for most uses.
6926 **
6927 ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
6928 ** internal buffer by SQLite within the call to [sqlite3_config].  Hence
6929 ** the application may discard the parameter after the call to
6930 ** [sqlite3_config()] returns.)^
6931 **
6932 ** [[the xInit() page cache method]]
6933 ** ^(The xInit() method is called once for each effective 
6934 ** call to [sqlite3_initialize()])^
6935 ** (usually only once during the lifetime of the process). ^(The xInit()
6936 ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
6937 ** The intent of the xInit() method is to set up global data structures 
6938 ** required by the custom page cache implementation. 
6939 ** ^(If the xInit() method is NULL, then the 
6940 ** built-in default page cache is used instead of the application defined
6941 ** page cache.)^
6942 **
6943 ** [[the xShutdown() page cache method]]
6944 ** ^The xShutdown() method is called by [sqlite3_shutdown()].
6945 ** It can be used to clean up 
6946 ** any outstanding resources before process shutdown, if required.
6947 ** ^The xShutdown() method may be NULL.
6948 **
6949 ** ^SQLite automatically serializes calls to the xInit method,
6950 ** so the xInit method need not be threadsafe.  ^The
6951 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
6952 ** not need to be threadsafe either.  All other methods must be threadsafe
6953 ** in multithreaded applications.
6954 **
6955 ** ^SQLite will never invoke xInit() more than once without an intervening
6956 ** call to xShutdown().
6957 **
6958 ** [[the xCreate() page cache methods]]
6959 ** ^SQLite invokes the xCreate() method to construct a new cache instance.
6960 ** SQLite will typically create one cache instance for each open database file,
6961 ** though this is not guaranteed. ^The
6962 ** first parameter, szPage, is the size in bytes of the pages that must
6963 ** be allocated by the cache.  ^szPage will always a power of two.  ^The
6964 ** second parameter szExtra is a number of bytes of extra storage 
6965 ** associated with each page cache entry.  ^The szExtra parameter will
6966 ** a number less than 250.  SQLite will use the
6967 ** extra szExtra bytes on each page to store metadata about the underlying
6968 ** database page on disk.  The value passed into szExtra depends
6969 ** on the SQLite version, the target platform, and how SQLite was compiled.
6970 ** ^The third argument to xCreate(), bPurgeable, is true if the cache being
6971 ** created will be used to cache database pages of a file stored on disk, or
6972 ** false if it is used for an in-memory database. The cache implementation
6973 ** does not have to do anything special based with the value of bPurgeable;
6974 ** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will
6975 ** never invoke xUnpin() except to deliberately delete a page.
6976 ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
6977 ** false will always have the "discard" flag set to true.  
6978 ** ^Hence, a cache created with bPurgeable false will
6979 ** never contain any unpinned pages.
6980 **
6981 ** [[the xCachesize() page cache method]]
6982 ** ^(The xCachesize() method may be called at any time by SQLite to set the
6983 ** suggested maximum cache-size (number of pages stored by) the cache
6984 ** instance passed as the first argument. This is the value configured using
6985 ** the SQLite "[PRAGMA cache_size]" command.)^  As with the bPurgeable
6986 ** parameter, the implementation is not required to do anything with this
6987 ** value; it is advisory only.
6988 **
6989 ** [[the xPagecount() page cache methods]]
6990 ** The xPagecount() method must return the number of pages currently
6991 ** stored in the cache, both pinned and unpinned.
6992 ** 
6993 ** [[the xFetch() page cache methods]]
6994 ** The xFetch() method locates a page in the cache and returns a pointer to 
6995 ** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
6996 ** The pBuf element of the returned sqlite3_pcache_page object will be a
6997 ** pointer to a buffer of szPage bytes used to store the content of a 
6998 ** single database page.  The pExtra element of sqlite3_pcache_page will be
6999 ** a pointer to the szExtra bytes of extra storage that SQLite has requested
7000 ** for each entry in the page cache.
7001 **
7002 ** The page to be fetched is determined by the key. ^The minimum key value
7003 ** is 1.  After it has been retrieved using xFetch, the page is considered
7004 ** to be "pinned".
7005 **
7006 ** If the requested page is already in the page cache, then the page cache
7007 ** implementation must return a pointer to the page buffer with its content
7008 ** intact.  If the requested page is not already in the cache, then the
7009 ** cache implementation should use the value of the createFlag
7010 ** parameter to help it determined what action to take:
7011 **
7012 ** <table border=1 width=85% align=center>
7013 ** <tr><th> createFlag <th> Behavior when page is not already in cache
7014 ** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.
7015 ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
7016 **                 Otherwise return NULL.
7017 ** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return
7018 **                 NULL if allocating a new page is effectively impossible.
7019 ** </table>
7020 **
7021 ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  SQLite
7022 ** will only use a createFlag of 2 after a prior call with a createFlag of 1
7023 ** failed.)^  In between the to xFetch() calls, SQLite may
7024 ** attempt to unpin one or more cache pages by spilling the content of
7025 ** pinned pages to disk and synching the operating system disk cache.
7026 **
7027 ** [[the xUnpin() page cache method]]
7028 ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
7029 ** as its second argument.  If the third parameter, discard, is non-zero,
7030 ** then the page must be evicted from the cache.
7031 ** ^If the discard parameter is
7032 ** zero, then the page may be discarded or retained at the discretion of
7033 ** page cache implementation. ^The page cache implementation
7034 ** may choose to evict unpinned pages at any time.
7035 **
7036 ** The cache must not perform any reference counting. A single 
7037 ** call to xUnpin() unpins the page regardless of the number of prior calls 
7038 ** to xFetch().
7039 **
7040 ** [[the xRekey() page cache methods]]
7041 ** The xRekey() method is used to change the key value associated with the
7042 ** page passed as the second argument. If the cache
7043 ** previously contains an entry associated with newKey, it must be
7044 ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
7045 ** to be pinned.
7046 **
7047 ** When SQLite calls the xTruncate() method, the cache must discard all
7048 ** existing cache entries with page numbers (keys) greater than or equal
7049 ** to the value of the iLimit parameter passed to xTruncate(). If any
7050 ** of these pages are pinned, they are implicitly unpinned, meaning that
7051 ** they can be safely discarded.
7052 **
7053 ** [[the xDestroy() page cache method]]
7054 ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
7055 ** All resources associated with the specified cache should be freed. ^After
7056 ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
7057 ** handle invalid, and will not use it with any other sqlite3_pcache_methods2
7058 ** functions.
7059 **
7060 ** [[the xShrink() page cache method]]
7061 ** ^SQLite invokes the xShrink() method when it wants the page cache to
7062 ** free up as much of heap memory as possible.  The page cache implementation
7063 ** is not obligated to free any memory, but well-behaved implementations should
7064 ** do their best.
7065 */
7066 typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
7067 struct sqlite3_pcache_methods2 {
7068   int iVersion;
7069   void *pArg;
7070   int (*xInit)(void*);
7071   void (*xShutdown)(void*);
7072   sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
7073   void (*xCachesize)(sqlite3_pcache*, int nCachesize);
7074   int (*xPagecount)(sqlite3_pcache*);
7075   sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
7076   void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
7077   void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*, 
7078       unsigned oldKey, unsigned newKey);
7079   void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
7080   void (*xDestroy)(sqlite3_pcache*);
7081   void (*xShrink)(sqlite3_pcache*);
7082 };
7083
7084 /*
7085 ** This is the obsolete pcache_methods object that has now been replaced
7086 ** by sqlite3_pcache_methods2.  This object is not used by SQLite.  It is
7087 ** retained in the header file for backwards compatibility only.
7088 */
7089 typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
7090 struct sqlite3_pcache_methods {
7091   void *pArg;
7092   int (*xInit)(void*);
7093   void (*xShutdown)(void*);
7094   sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
7095   void (*xCachesize)(sqlite3_pcache*, int nCachesize);
7096   int (*xPagecount)(sqlite3_pcache*);
7097   void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
7098   void (*xUnpin)(sqlite3_pcache*, void*, int discard);
7099   void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
7100   void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
7101   void (*xDestroy)(sqlite3_pcache*);
7102 };
7103
7104
7105 /*
7106 ** CAPI3REF: Online Backup Object
7107 **
7108 ** The sqlite3_backup object records state information about an ongoing
7109 ** online backup operation.  ^The sqlite3_backup object is created by
7110 ** a call to [sqlite3_backup_init()] and is destroyed by a call to
7111 ** [sqlite3_backup_finish()].
7112 **
7113 ** See Also: [Using the SQLite Online Backup API]
7114 */
7115 typedef struct sqlite3_backup sqlite3_backup;
7116
7117 /*
7118 ** CAPI3REF: Online Backup API.
7119 **
7120 ** The backup API copies the content of one database into another.
7121 ** It is useful either for creating backups of databases or
7122 ** for copying in-memory databases to or from persistent files. 
7123 **
7124 ** See Also: [Using the SQLite Online Backup API]
7125 **
7126 ** ^SQLite holds a write transaction open on the destination database file
7127 ** for the duration of the backup operation.
7128 ** ^The source database is read-locked only while it is being read;
7129 ** it is not locked continuously for the entire backup operation.
7130 ** ^Thus, the backup may be performed on a live source database without
7131 ** preventing other database connections from
7132 ** reading or writing to the source database while the backup is underway.
7133 ** 
7134 ** ^(To perform a backup operation: 
7135 **   <ol>
7136 **     <li><b>sqlite3_backup_init()</b> is called once to initialize the
7137 **         backup, 
7138 **     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer 
7139 **         the data between the two databases, and finally
7140 **     <li><b>sqlite3_backup_finish()</b> is called to release all resources 
7141 **         associated with the backup operation. 
7142 **   </ol>)^
7143 ** There should be exactly one call to sqlite3_backup_finish() for each
7144 ** successful call to sqlite3_backup_init().
7145 **
7146 ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
7147 **
7148 ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the 
7149 ** [database connection] associated with the destination database 
7150 ** and the database name, respectively.
7151 ** ^The database name is "main" for the main database, "temp" for the
7152 ** temporary database, or the name specified after the AS keyword in
7153 ** an [ATTACH] statement for an attached database.
7154 ** ^The S and M arguments passed to 
7155 ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
7156 ** and database name of the source database, respectively.
7157 ** ^The source and destination [database connections] (parameters S and D)
7158 ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
7159 ** an error.
7160 **
7161 ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
7162 ** returned and an error code and error message are stored in the
7163 ** destination [database connection] D.
7164 ** ^The error code and message for the failed call to sqlite3_backup_init()
7165 ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
7166 ** [sqlite3_errmsg16()] functions.
7167 ** ^A successful call to sqlite3_backup_init() returns a pointer to an
7168 ** [sqlite3_backup] object.
7169 ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
7170 ** sqlite3_backup_finish() functions to perform the specified backup 
7171 ** operation.
7172 **
7173 ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
7174 **
7175 ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between 
7176 ** the source and destination databases specified by [sqlite3_backup] object B.
7177 ** ^If N is negative, all remaining source pages are copied. 
7178 ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
7179 ** are still more pages to be copied, then the function returns [SQLITE_OK].
7180 ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
7181 ** from source to destination, then it returns [SQLITE_DONE].
7182 ** ^If an error occurs while running sqlite3_backup_step(B,N),
7183 ** then an [error code] is returned. ^As well as [SQLITE_OK] and
7184 ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
7185 ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
7186 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
7187 **
7188 ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
7189 ** <ol>
7190 ** <li> the destination database was opened read-only, or
7191 ** <li> the destination database is using write-ahead-log journaling
7192 ** and the destination and source page sizes differ, or
7193 ** <li> the destination database is an in-memory database and the
7194 ** destination and source page sizes differ.
7195 ** </ol>)^
7196 **
7197 ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
7198 ** the [sqlite3_busy_handler | busy-handler function]
7199 ** is invoked (if one is specified). ^If the 
7200 ** busy-handler returns non-zero before the lock is available, then 
7201 ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
7202 ** sqlite3_backup_step() can be retried later. ^If the source
7203 ** [database connection]
7204 ** is being used to write to the source database when sqlite3_backup_step()
7205 ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
7206 ** case the call to sqlite3_backup_step() can be retried later on. ^(If
7207 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
7208 ** [SQLITE_READONLY] is returned, then 
7209 ** there is no point in retrying the call to sqlite3_backup_step(). These 
7210 ** errors are considered fatal.)^  The application must accept 
7211 ** that the backup operation has failed and pass the backup operation handle 
7212 ** to the sqlite3_backup_finish() to release associated resources.
7213 **
7214 ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
7215 ** on the destination file. ^The exclusive lock is not released until either 
7216 ** sqlite3_backup_finish() is called or the backup operation is complete 
7217 ** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to
7218 ** sqlite3_backup_step() obtains a [shared lock] on the source database that
7219 ** lasts for the duration of the sqlite3_backup_step() call.
7220 ** ^Because the source database is not locked between calls to
7221 ** sqlite3_backup_step(), the source database may be modified mid-way
7222 ** through the backup process.  ^If the source database is modified by an
7223 ** external process or via a database connection other than the one being
7224 ** used by the backup operation, then the backup will be automatically
7225 ** restarted by the next call to sqlite3_backup_step(). ^If the source 
7226 ** database is modified by the using the same database connection as is used
7227 ** by the backup operation, then the backup database is automatically
7228 ** updated at the same time.
7229 **
7230 ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
7231 **
7232 ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the 
7233 ** application wishes to abandon the backup operation, the application
7234 ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
7235 ** ^The sqlite3_backup_finish() interfaces releases all
7236 ** resources associated with the [sqlite3_backup] object. 
7237 ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
7238 ** active write-transaction on the destination database is rolled back.
7239 ** The [sqlite3_backup] object is invalid
7240 ** and may not be used following a call to sqlite3_backup_finish().
7241 **
7242 ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
7243 ** sqlite3_backup_step() errors occurred, regardless or whether or not
7244 ** sqlite3_backup_step() completed.
7245 ** ^If an out-of-memory condition or IO error occurred during any prior
7246 ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
7247 ** sqlite3_backup_finish() returns the corresponding [error code].
7248 **
7249 ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
7250 ** is not a permanent error and does not affect the return value of
7251 ** sqlite3_backup_finish().
7252 **
7253 ** [[sqlite3_backup__remaining()]] [[sqlite3_backup_pagecount()]]
7254 ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
7255 **
7256 ** ^Each call to sqlite3_backup_step() sets two values inside
7257 ** the [sqlite3_backup] object: the number of pages still to be backed
7258 ** up and the total number of pages in the source database file.
7259 ** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
7260 ** retrieve these two values, respectively.
7261 **
7262 ** ^The values returned by these functions are only updated by
7263 ** sqlite3_backup_step(). ^If the source database is modified during a backup
7264 ** operation, then the values are not updated to account for any extra
7265 ** pages that need to be updated or the size of the source database file
7266 ** changing.
7267 **
7268 ** <b>Concurrent Usage of Database Handles</b>
7269 **
7270 ** ^The source [database connection] may be used by the application for other
7271 ** purposes while a backup operation is underway or being initialized.
7272 ** ^If SQLite is compiled and configured to support threadsafe database
7273 ** connections, then the source database connection may be used concurrently
7274 ** from within other threads.
7275 **
7276 ** However, the application must guarantee that the destination 
7277 ** [database connection] is not passed to any other API (by any thread) after 
7278 ** sqlite3_backup_init() is called and before the corresponding call to
7279 ** sqlite3_backup_finish().  SQLite does not currently check to see
7280 ** if the application incorrectly accesses the destination [database connection]
7281 ** and so no error code is reported, but the operations may malfunction
7282 ** nevertheless.  Use of the destination database connection while a
7283 ** backup is in progress might also also cause a mutex deadlock.
7284 **
7285 ** If running in [shared cache mode], the application must
7286 ** guarantee that the shared cache used by the destination database
7287 ** is not accessed while the backup is running. In practice this means
7288 ** that the application must guarantee that the disk file being 
7289 ** backed up to is not accessed by any connection within the process,
7290 ** not just the specific connection that was passed to sqlite3_backup_init().
7291 **
7292 ** The [sqlite3_backup] object itself is partially threadsafe. Multiple 
7293 ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
7294 ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
7295 ** APIs are not strictly speaking threadsafe. If they are invoked at the
7296 ** same time as another thread is invoking sqlite3_backup_step() it is
7297 ** possible that they return invalid values.
7298 */
7299 SQLITE_API sqlite3_backup *sqlite3_backup_init(
7300   sqlite3 *pDest,                        /* Destination database handle */
7301   const char *zDestName,                 /* Destination database name */
7302   sqlite3 *pSource,                      /* Source database handle */
7303   const char *zSourceName                /* Source database name */
7304 );
7305 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
7306 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
7307 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
7308 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
7309
7310 /*
7311 ** CAPI3REF: Unlock Notification
7312 **
7313 ** ^When running in shared-cache mode, a database operation may fail with
7314 ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
7315 ** individual tables within the shared-cache cannot be obtained. See
7316 ** [SQLite Shared-Cache Mode] for a description of shared-cache locking. 
7317 ** ^This API may be used to register a callback that SQLite will invoke 
7318 ** when the connection currently holding the required lock relinquishes it.
7319 ** ^This API is only available if the library was compiled with the
7320 ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
7321 **
7322 ** See Also: [Using the SQLite Unlock Notification Feature].
7323 **
7324 ** ^Shared-cache locks are released when a database connection concludes
7325 ** its current transaction, either by committing it or rolling it back. 
7326 **
7327 ** ^When a connection (known as the blocked connection) fails to obtain a
7328 ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
7329 ** identity of the database connection (the blocking connection) that
7330 ** has locked the required resource is stored internally. ^After an 
7331 ** application receives an SQLITE_LOCKED error, it may call the
7332 ** sqlite3_unlock_notify() method with the blocked connection handle as 
7333 ** the first argument to register for a callback that will be invoked
7334 ** when the blocking connections current transaction is concluded. ^The
7335 ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
7336 ** call that concludes the blocking connections transaction.
7337 **
7338 ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
7339 ** there is a chance that the blocking connection will have already
7340 ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
7341 ** If this happens, then the specified callback is invoked immediately,
7342 ** from within the call to sqlite3_unlock_notify().)^
7343 **
7344 ** ^If the blocked connection is attempting to obtain a write-lock on a
7345 ** shared-cache table, and more than one other connection currently holds
7346 ** a read-lock on the same table, then SQLite arbitrarily selects one of 
7347 ** the other connections to use as the blocking connection.
7348 **
7349 ** ^(There may be at most one unlock-notify callback registered by a 
7350 ** blocked connection. If sqlite3_unlock_notify() is called when the
7351 ** blocked connection already has a registered unlock-notify callback,
7352 ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
7353 ** called with a NULL pointer as its second argument, then any existing
7354 ** unlock-notify callback is canceled. ^The blocked connections 
7355 ** unlock-notify callback may also be canceled by closing the blocked
7356 ** connection using [sqlite3_close()].
7357 **
7358 ** The unlock-notify callback is not reentrant. If an application invokes
7359 ** any sqlite3_xxx API functions from within an unlock-notify callback, a
7360 ** crash or deadlock may be the result.
7361 **
7362 ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
7363 ** returns SQLITE_OK.
7364 **
7365 ** <b>Callback Invocation Details</b>
7366 **
7367 ** When an unlock-notify callback is registered, the application provides a 
7368 ** single void* pointer that is passed to the callback when it is invoked.
7369 ** However, the signature of the callback function allows SQLite to pass
7370 ** it an array of void* context pointers. The first argument passed to
7371 ** an unlock-notify callback is a pointer to an array of void* pointers,
7372 ** and the second is the number of entries in the array.
7373 **
7374 ** When a blocking connections transaction is concluded, there may be
7375 ** more than one blocked connection that has registered for an unlock-notify
7376 ** callback. ^If two or more such blocked connections have specified the
7377 ** same callback function, then instead of invoking the callback function
7378 ** multiple times, it is invoked once with the set of void* context pointers
7379 ** specified by the blocked connections bundled together into an array.
7380 ** This gives the application an opportunity to prioritize any actions 
7381 ** related to the set of unblocked database connections.
7382 **
7383 ** <b>Deadlock Detection</b>
7384 **
7385 ** Assuming that after registering for an unlock-notify callback a 
7386 ** database waits for the callback to be issued before taking any further
7387 ** action (a reasonable assumption), then using this API may cause the
7388 ** application to deadlock. For example, if connection X is waiting for
7389 ** connection Y's transaction to be concluded, and similarly connection
7390 ** Y is waiting on connection X's transaction, then neither connection
7391 ** will proceed and the system may remain deadlocked indefinitely.
7392 **
7393 ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
7394 ** detection. ^If a given call to sqlite3_unlock_notify() would put the
7395 ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
7396 ** unlock-notify callback is registered. The system is said to be in
7397 ** a deadlocked state if connection A has registered for an unlock-notify
7398 ** callback on the conclusion of connection B's transaction, and connection
7399 ** B has itself registered for an unlock-notify callback when connection
7400 ** A's transaction is concluded. ^Indirect deadlock is also detected, so
7401 ** the system is also considered to be deadlocked if connection B has
7402 ** registered for an unlock-notify callback on the conclusion of connection
7403 ** C's transaction, where connection C is waiting on connection A. ^Any
7404 ** number of levels of indirection are allowed.
7405 **
7406 ** <b>The "DROP TABLE" Exception</b>
7407 **
7408 ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost 
7409 ** always appropriate to call sqlite3_unlock_notify(). There is however,
7410 ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
7411 ** SQLite checks if there are any currently executing SELECT statements
7412 ** that belong to the same connection. If there are, SQLITE_LOCKED is
7413 ** returned. In this case there is no "blocking connection", so invoking
7414 ** sqlite3_unlock_notify() results in the unlock-notify callback being
7415 ** invoked immediately. If the application then re-attempts the "DROP TABLE"
7416 ** or "DROP INDEX" query, an infinite loop might be the result.
7417 **
7418 ** One way around this problem is to check the extended error code returned
7419 ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
7420 ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
7421 ** the special "DROP TABLE/INDEX" case, the extended error code is just 
7422 ** SQLITE_LOCKED.)^
7423 */
7424 SQLITE_API int sqlite3_unlock_notify(
7425   sqlite3 *pBlocked,                          /* Waiting connection */
7426   void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */
7427   void *pNotifyArg                            /* Argument to pass to xNotify */
7428 );
7429
7430
7431 /*
7432 ** CAPI3REF: String Comparison
7433 **
7434 ** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
7435 ** and extensions to compare the contents of two buffers containing UTF-8
7436 ** strings in a case-independent fashion, using the same definition of "case
7437 ** independence" that SQLite uses internally when comparing identifiers.
7438 */
7439 SQLITE_API int sqlite3_stricmp(const char *, const char *);
7440 SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
7441
7442 /*
7443 ** CAPI3REF: String Globbing
7444 *
7445 ** ^The [sqlite3_strglob(P,X)] interface returns zero if string X matches
7446 ** the glob pattern P, and it returns non-zero if string X does not match
7447 ** the glob pattern P.  ^The definition of glob pattern matching used in
7448 ** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
7449 ** SQL dialect used by SQLite.  ^The sqlite3_strglob(P,X) function is case
7450 ** sensitive.
7451 **
7452 ** Note that this routine returns zero on a match and non-zero if the strings
7453 ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
7454 */
7455 SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr);
7456
7457 /*
7458 ** CAPI3REF: Error Logging Interface
7459 **
7460 ** ^The [sqlite3_log()] interface writes a message into the [error log]
7461 ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
7462 ** ^If logging is enabled, the zFormat string and subsequent arguments are
7463 ** used with [sqlite3_snprintf()] to generate the final output string.
7464 **
7465 ** The sqlite3_log() interface is intended for use by extensions such as
7466 ** virtual tables, collating functions, and SQL functions.  While there is
7467 ** nothing to prevent an application from calling sqlite3_log(), doing so
7468 ** is considered bad form.
7469 **
7470 ** The zFormat string must not be NULL.
7471 **
7472 ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
7473 ** will not use dynamically allocated memory.  The log message is stored in
7474 ** a fixed-length buffer on the stack.  If the log message is longer than
7475 ** a few hundred characters, it will be truncated to the length of the
7476 ** buffer.
7477 */
7478 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
7479
7480 /*
7481 ** CAPI3REF: Write-Ahead Log Commit Hook
7482 **
7483 ** ^The [sqlite3_wal_hook()] function is used to register a callback that
7484 ** will be invoked each time a database connection commits data to a
7485 ** [write-ahead log] (i.e. whenever a transaction is committed in
7486 ** [journal_mode | journal_mode=WAL mode]). 
7487 **
7488 ** ^The callback is invoked by SQLite after the commit has taken place and 
7489 ** the associated write-lock on the database released, so the implementation 
7490 ** may read, write or [checkpoint] the database as required.
7491 **
7492 ** ^The first parameter passed to the callback function when it is invoked
7493 ** is a copy of the third parameter passed to sqlite3_wal_hook() when
7494 ** registering the callback. ^The second is a copy of the database handle.
7495 ** ^The third parameter is the name of the database that was written to -
7496 ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
7497 ** is the number of pages currently in the write-ahead log file,
7498 ** including those that were just committed.
7499 **
7500 ** The callback function should normally return [SQLITE_OK].  ^If an error
7501 ** code is returned, that error will propagate back up through the
7502 ** SQLite code base to cause the statement that provoked the callback
7503 ** to report an error, though the commit will have still occurred. If the
7504 ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
7505 ** that does not correspond to any valid SQLite error code, the results
7506 ** are undefined.
7507 **
7508 ** A single database handle may have at most a single write-ahead log callback 
7509 ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
7510 ** previously registered write-ahead log callback. ^Note that the
7511 ** [sqlite3_wal_autocheckpoint()] interface and the
7512 ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
7513 ** those overwrite any prior [sqlite3_wal_hook()] settings.
7514 */
7515 SQLITE_API void *sqlite3_wal_hook(
7516   sqlite3*, 
7517   int(*)(void *,sqlite3*,const char*,int),
7518   void*
7519 );
7520
7521 /*
7522 ** CAPI3REF: Configure an auto-checkpoint
7523 **
7524 ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
7525 ** [sqlite3_wal_hook()] that causes any database on [database connection] D
7526 ** to automatically [checkpoint]
7527 ** after committing a transaction if there are N or
7528 ** more frames in the [write-ahead log] file.  ^Passing zero or 
7529 ** a negative value as the nFrame parameter disables automatic
7530 ** checkpoints entirely.
7531 **
7532 ** ^The callback registered by this function replaces any existing callback
7533 ** registered using [sqlite3_wal_hook()].  ^Likewise, registering a callback
7534 ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
7535 ** configured by this function.
7536 **
7537 ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
7538 ** from SQL.
7539 **
7540 ** ^Every new [database connection] defaults to having the auto-checkpoint
7541 ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
7542 ** pages.  The use of this interface
7543 ** is only necessary if the default setting is found to be suboptimal
7544 ** for a particular application.
7545 */
7546 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
7547
7548 /*
7549 ** CAPI3REF: Checkpoint a database
7550 **
7551 ** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X
7552 ** on [database connection] D to be [checkpointed].  ^If X is NULL or an
7553 ** empty string, then a checkpoint is run on all databases of
7554 ** connection D.  ^If the database connection D is not in
7555 ** [WAL | write-ahead log mode] then this interface is a harmless no-op.
7556 **
7557 ** ^The [wal_checkpoint pragma] can be used to invoke this interface
7558 ** from SQL.  ^The [sqlite3_wal_autocheckpoint()] interface and the
7559 ** [wal_autocheckpoint pragma] can be used to cause this interface to be
7560 ** run whenever the WAL reaches a certain size threshold.
7561 **
7562 ** See also: [sqlite3_wal_checkpoint_v2()]
7563 */
7564 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
7565
7566 /*
7567 ** CAPI3REF: Checkpoint a database
7568 **
7569 ** Run a checkpoint operation on WAL database zDb attached to database 
7570 ** handle db. The specific operation is determined by the value of the 
7571 ** eMode parameter:
7572 **
7573 ** <dl>
7574 ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
7575 **   Checkpoint as many frames as possible without waiting for any database 
7576 **   readers or writers to finish. Sync the db file if all frames in the log
7577 **   are checkpointed. This mode is the same as calling 
7578 **   sqlite3_wal_checkpoint(). The busy-handler callback is never invoked.
7579 **
7580 ** <dt>SQLITE_CHECKPOINT_FULL<dd>
7581 **   This mode blocks (calls the busy-handler callback) until there is no
7582 **   database writer and all readers are reading from the most recent database
7583 **   snapshot. It then checkpoints all frames in the log file and syncs the
7584 **   database file. This call blocks database writers while it is running,
7585 **   but not database readers.
7586 **
7587 ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
7588 **   This mode works the same way as SQLITE_CHECKPOINT_FULL, except after 
7589 **   checkpointing the log file it blocks (calls the busy-handler callback)
7590 **   until all readers are reading from the database file only. This ensures 
7591 **   that the next client to write to the database file restarts the log file 
7592 **   from the beginning. This call blocks database writers while it is running,
7593 **   but not database readers.
7594 ** </dl>
7595 **
7596 ** If pnLog is not NULL, then *pnLog is set to the total number of frames in
7597 ** the log file before returning. If pnCkpt is not NULL, then *pnCkpt is set to
7598 ** the total number of checkpointed frames (including any that were already
7599 ** checkpointed when this function is called). *pnLog and *pnCkpt may be
7600 ** populated even if sqlite3_wal_checkpoint_v2() returns other than SQLITE_OK.
7601 ** If no values are available because of an error, they are both set to -1
7602 ** before returning to communicate this to the caller.
7603 **
7604 ** All calls obtain an exclusive "checkpoint" lock on the database file. If
7605 ** any other process is running a checkpoint operation at the same time, the 
7606 ** lock cannot be obtained and SQLITE_BUSY is returned. Even if there is a 
7607 ** busy-handler configured, it will not be invoked in this case.
7608 **
7609 ** The SQLITE_CHECKPOINT_FULL and RESTART modes also obtain the exclusive 
7610 ** "writer" lock on the database file. If the writer lock cannot be obtained
7611 ** immediately, and a busy-handler is configured, it is invoked and the writer
7612 ** lock retried until either the busy-handler returns 0 or the lock is
7613 ** successfully obtained. The busy-handler is also invoked while waiting for
7614 ** database readers as described above. If the busy-handler returns 0 before
7615 ** the writer lock is obtained or while waiting for database readers, the
7616 ** checkpoint operation proceeds from that point in the same way as 
7617 ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible 
7618 ** without blocking any further. SQLITE_BUSY is returned in this case.
7619 **
7620 ** If parameter zDb is NULL or points to a zero length string, then the
7621 ** specified operation is attempted on all WAL databases. In this case the
7622 ** values written to output parameters *pnLog and *pnCkpt are undefined. If 
7623 ** an SQLITE_BUSY error is encountered when processing one or more of the 
7624 ** attached WAL databases, the operation is still attempted on any remaining 
7625 ** attached databases and SQLITE_BUSY is returned to the caller. If any other 
7626 ** error occurs while processing an attached database, processing is abandoned 
7627 ** and the error code returned to the caller immediately. If no error 
7628 ** (SQLITE_BUSY or otherwise) is encountered while processing the attached 
7629 ** databases, SQLITE_OK is returned.
7630 **
7631 ** If database zDb is the name of an attached database that is not in WAL
7632 ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. If
7633 ** zDb is not NULL (or a zero length string) and is not the name of any
7634 ** attached database, SQLITE_ERROR is returned to the caller.
7635 */
7636 SQLITE_API int sqlite3_wal_checkpoint_v2(
7637   sqlite3 *db,                    /* Database handle */
7638   const char *zDb,                /* Name of attached database (or NULL) */
7639   int eMode,                      /* SQLITE_CHECKPOINT_* value */
7640   int *pnLog,                     /* OUT: Size of WAL log in frames */
7641   int *pnCkpt                     /* OUT: Total number of frames checkpointed */
7642 );
7643
7644 /*
7645 ** CAPI3REF: Checkpoint operation parameters
7646 **
7647 ** These constants can be used as the 3rd parameter to
7648 ** [sqlite3_wal_checkpoint_v2()].  See the [sqlite3_wal_checkpoint_v2()]
7649 ** documentation for additional information about the meaning and use of
7650 ** each of these values.
7651 */
7652 #define SQLITE_CHECKPOINT_PASSIVE 0
7653 #define SQLITE_CHECKPOINT_FULL    1
7654 #define SQLITE_CHECKPOINT_RESTART 2
7655
7656 /*
7657 ** CAPI3REF: Virtual Table Interface Configuration
7658 **
7659 ** This function may be called by either the [xConnect] or [xCreate] method
7660 ** of a [virtual table] implementation to configure
7661 ** various facets of the virtual table interface.
7662 **
7663 ** If this interface is invoked outside the context of an xConnect or
7664 ** xCreate virtual table method then the behavior is undefined.
7665 **
7666 ** At present, there is only one option that may be configured using
7667 ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].)  Further options
7668 ** may be added in the future.
7669 */
7670 SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
7671
7672 /*
7673 ** CAPI3REF: Virtual Table Configuration Options
7674 **
7675 ** These macros define the various options to the
7676 ** [sqlite3_vtab_config()] interface that [virtual table] implementations
7677 ** can use to customize and optimize their behavior.
7678 **
7679 ** <dl>
7680 ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
7681 ** <dd>Calls of the form
7682 ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
7683 ** where X is an integer.  If X is zero, then the [virtual table] whose
7684 ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
7685 ** support constraints.  In this configuration (which is the default) if
7686 ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
7687 ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
7688 ** specified as part of the users SQL statement, regardless of the actual
7689 ** ON CONFLICT mode specified.
7690 **
7691 ** If X is non-zero, then the virtual table implementation guarantees
7692 ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
7693 ** any modifications to internal or persistent data structures have been made.
7694 ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite 
7695 ** is able to roll back a statement or database transaction, and abandon
7696 ** or continue processing the current SQL statement as appropriate. 
7697 ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
7698 ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
7699 ** had been ABORT.
7700 **
7701 ** Virtual table implementations that are required to handle OR REPLACE
7702 ** must do so within the [xUpdate] method. If a call to the 
7703 ** [sqlite3_vtab_on_conflict()] function indicates that the current ON 
7704 ** CONFLICT policy is REPLACE, the virtual table implementation should 
7705 ** silently replace the appropriate rows within the xUpdate callback and
7706 ** return SQLITE_OK. Or, if this is not possible, it may return
7707 ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT 
7708 ** constraint handling.
7709 ** </dl>
7710 */
7711 #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
7712
7713 /*
7714 ** CAPI3REF: Determine The Virtual Table Conflict Policy
7715 **
7716 ** This function may only be called from within a call to the [xUpdate] method
7717 ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
7718 ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
7719 ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
7720 ** of the SQL statement that triggered the call to the [xUpdate] method of the
7721 ** [virtual table].
7722 */
7723 SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
7724
7725 /*
7726 ** CAPI3REF: Conflict resolution modes
7727 **
7728 ** These constants are returned by [sqlite3_vtab_on_conflict()] to
7729 ** inform a [virtual table] implementation what the [ON CONFLICT] mode
7730 ** is for the SQL statement being evaluated.
7731 **
7732 ** Note that the [SQLITE_IGNORE] constant is also used as a potential
7733 ** return value from the [sqlite3_set_authorizer()] callback and that
7734 ** [SQLITE_ABORT] is also a [result code].
7735 */
7736 #define SQLITE_ROLLBACK 1
7737 /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
7738 #define SQLITE_FAIL     3
7739 /* #define SQLITE_ABORT 4  // Also an error code */
7740 #define SQLITE_REPLACE  5
7741
7742
7743
7744 /*
7745 ** Undo the hack that converts floating point types to integer for
7746 ** builds on processors without floating point support.
7747 */
7748 #ifdef SQLITE_OMIT_FLOATING_POINT
7749 # undef double
7750 #endif
7751
7752 #if 0
7753 }  /* End of the 'extern "C"' block */
7754 #endif
7755 #endif
7756
7757 /*
7758 ** 2010 August 30
7759 **
7760 ** The author disclaims copyright to this source code.  In place of
7761 ** a legal notice, here is a blessing:
7762 **
7763 **    May you do good and not evil.
7764 **    May you find forgiveness for yourself and forgive others.
7765 **    May you share freely, never taking more than you give.
7766 **
7767 *************************************************************************
7768 */
7769
7770 #ifndef _SQLITE3RTREE_H_
7771 #define _SQLITE3RTREE_H_
7772
7773
7774 #if 0
7775 extern "C" {
7776 #endif
7777
7778 typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
7779
7780 /*
7781 ** Register a geometry callback named zGeom that can be used as part of an
7782 ** R-Tree geometry query as follows:
7783 **
7784 **   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
7785 */
7786 SQLITE_API int sqlite3_rtree_geometry_callback(
7787   sqlite3 *db,
7788   const char *zGeom,
7789 #ifdef SQLITE_RTREE_INT_ONLY
7790   int (*xGeom)(sqlite3_rtree_geometry*, int n, sqlite3_int64 *a, int *pRes),
7791 #else
7792   int (*xGeom)(sqlite3_rtree_geometry*, int n, double *a, int *pRes),
7793 #endif
7794   void *pContext
7795 );
7796
7797
7798 /*
7799 ** A pointer to a structure of the following type is passed as the first
7800 ** argument to callbacks registered using rtree_geometry_callback().
7801 */
7802 struct sqlite3_rtree_geometry {
7803   void *pContext;                 /* Copy of pContext passed to s_r_g_c() */
7804   int nParam;                     /* Size of array aParam[] */
7805   double *aParam;                 /* Parameters passed to SQL geom function */
7806   void *pUser;                    /* Callback implementation user data */
7807   void (*xDelUser)(void *);       /* Called by SQLite to clean up pUser */
7808 };
7809
7810
7811 #if 0
7812 }  /* end of the 'extern "C"' block */
7813 #endif
7814
7815 #endif  /* ifndef _SQLITE3RTREE_H_ */
7816
7817
7818 /************** End of sqlite3.h *********************************************/
7819 /************** Continuing where we left off in sqliteInt.h ******************/
7820 /************** Include hash.h in the middle of sqliteInt.h ******************/
7821 /************** Begin file hash.h ********************************************/
7822 /*
7823 ** 2001 September 22
7824 **
7825 ** The author disclaims copyright to this source code.  In place of
7826 ** a legal notice, here is a blessing:
7827 **
7828 **    May you do good and not evil.
7829 **    May you find forgiveness for yourself and forgive others.
7830 **    May you share freely, never taking more than you give.
7831 **
7832 *************************************************************************
7833 ** This is the header file for the generic hash-table implementation
7834 ** used in SQLite.
7835 */
7836 #ifndef _SQLITE_HASH_H_
7837 #define _SQLITE_HASH_H_
7838
7839 /* Forward declarations of structures. */
7840 typedef struct Hash Hash;
7841 typedef struct HashElem HashElem;
7842
7843 /* A complete hash table is an instance of the following structure.
7844 ** The internals of this structure are intended to be opaque -- client
7845 ** code should not attempt to access or modify the fields of this structure
7846 ** directly.  Change this structure only by using the routines below.
7847 ** However, some of the "procedures" and "functions" for modifying and
7848 ** accessing this structure are really macros, so we can't really make
7849 ** this structure opaque.
7850 **
7851 ** All elements of the hash table are on a single doubly-linked list.
7852 ** Hash.first points to the head of this list.
7853 **
7854 ** There are Hash.htsize buckets.  Each bucket points to a spot in
7855 ** the global doubly-linked list.  The contents of the bucket are the
7856 ** element pointed to plus the next _ht.count-1 elements in the list.
7857 **
7858 ** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
7859 ** by a linear search of the global list.  For small tables, the 
7860 ** Hash.ht table is never allocated because if there are few elements
7861 ** in the table, it is faster to do a linear search than to manage
7862 ** the hash table.
7863 */
7864 struct Hash {
7865   unsigned int htsize;      /* Number of buckets in the hash table */
7866   unsigned int count;       /* Number of entries in this table */
7867   HashElem *first;          /* The first element of the array */
7868   struct _ht {              /* the hash table */
7869     int count;                 /* Number of entries with this hash */
7870     HashElem *chain;           /* Pointer to first entry with this hash */
7871   } *ht;
7872 };
7873
7874 /* Each element in the hash table is an instance of the following 
7875 ** structure.  All elements are stored on a single doubly-linked list.
7876 **
7877 ** Again, this structure is intended to be opaque, but it can't really
7878 ** be opaque because it is used by macros.
7879 */
7880 struct HashElem {
7881   HashElem *next, *prev;       /* Next and previous elements in the table */
7882   void *data;                  /* Data associated with this element */
7883   const char *pKey; int nKey;  /* Key associated with this element */
7884 };
7885
7886 /*
7887 ** Access routines.  To delete, insert a NULL pointer.
7888 */
7889 SQLITE_PRIVATE void sqlite3HashInit(Hash*);
7890 SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
7891 SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);
7892 SQLITE_PRIVATE void sqlite3HashClear(Hash*);
7893
7894 /*
7895 ** Macros for looping over all elements of a hash table.  The idiom is
7896 ** like this:
7897 **
7898 **   Hash h;
7899 **   HashElem *p;
7900 **   ...
7901 **   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
7902 **     SomeStructure *pData = sqliteHashData(p);
7903 **     // do something with pData
7904 **   }
7905 */
7906 #define sqliteHashFirst(H)  ((H)->first)
7907 #define sqliteHashNext(E)   ((E)->next)
7908 #define sqliteHashData(E)   ((E)->data)
7909 /* #define sqliteHashKey(E)    ((E)->pKey) // NOT USED */
7910 /* #define sqliteHashKeysize(E) ((E)->nKey)  // NOT USED */
7911
7912 /*
7913 ** Number of entries in a hash table
7914 */
7915 /* #define sqliteHashCount(H)  ((H)->count) // NOT USED */
7916
7917 #endif /* _SQLITE_HASH_H_ */
7918
7919 /************** End of hash.h ************************************************/
7920 /************** Continuing where we left off in sqliteInt.h ******************/
7921 /************** Include parse.h in the middle of sqliteInt.h *****************/
7922 /************** Begin file parse.h *******************************************/
7923 #define TK_SEMI                            1
7924 #define TK_EXPLAIN                         2
7925 #define TK_QUERY                           3
7926 #define TK_PLAN                            4
7927 #define TK_BEGIN                           5
7928 #define TK_TRANSACTION                     6
7929 #define TK_DEFERRED                        7
7930 #define TK_IMMEDIATE                       8
7931 #define TK_EXCLUSIVE                       9
7932 #define TK_COMMIT                         10
7933 #define TK_END                            11
7934 #define TK_ROLLBACK                       12
7935 #define TK_SAVEPOINT                      13
7936 #define TK_RELEASE                        14
7937 #define TK_TO                             15
7938 #define TK_TABLE                          16
7939 #define TK_CREATE                         17
7940 #define TK_IF                             18
7941 #define TK_NOT                            19
7942 #define TK_EXISTS                         20
7943 #define TK_TEMP                           21
7944 #define TK_LP                             22
7945 #define TK_RP                             23
7946 #define TK_AS                             24
7947 #define TK_COMMA                          25
7948 #define TK_ID                             26
7949 #define TK_INDEXED                        27
7950 #define TK_ABORT                          28
7951 #define TK_ACTION                         29
7952 #define TK_AFTER                          30
7953 #define TK_ANALYZE                        31
7954 #define TK_ASC                            32
7955 #define TK_ATTACH                         33
7956 #define TK_BEFORE                         34
7957 #define TK_BY                             35
7958 #define TK_CASCADE                        36
7959 #define TK_CAST                           37
7960 #define TK_COLUMNKW                       38
7961 #define TK_CONFLICT                       39
7962 #define TK_DATABASE                       40
7963 #define TK_DESC                           41
7964 #define TK_DETACH                         42
7965 #define TK_EACH                           43
7966 #define TK_FAIL                           44
7967 #define TK_FOR                            45
7968 #define TK_IGNORE                         46
7969 #define TK_INITIALLY                      47
7970 #define TK_INSTEAD                        48
7971 #define TK_LIKE_KW                        49
7972 #define TK_MATCH                          50
7973 #define TK_NO                             51
7974 #define TK_KEY                            52
7975 #define TK_OF                             53
7976 #define TK_OFFSET                         54
7977 #define TK_PRAGMA                         55
7978 #define TK_RAISE                          56
7979 #define TK_REPLACE                        57
7980 #define TK_RESTRICT                       58
7981 #define TK_ROW                            59
7982 #define TK_TRIGGER                        60
7983 #define TK_VACUUM                         61
7984 #define TK_VIEW                           62
7985 #define TK_VIRTUAL                        63
7986 #define TK_REINDEX                        64
7987 #define TK_RENAME                         65
7988 #define TK_CTIME_KW                       66
7989 #define TK_ANY                            67
7990 #define TK_OR                             68
7991 #define TK_AND                            69
7992 #define TK_IS                             70
7993 #define TK_BETWEEN                        71
7994 #define TK_IN                             72
7995 #define TK_ISNULL                         73
7996 #define TK_NOTNULL                        74
7997 #define TK_NE                             75
7998 #define TK_EQ                             76
7999 #define TK_GT                             77
8000 #define TK_LE                             78
8001 #define TK_LT                             79
8002 #define TK_GE                             80
8003 #define TK_ESCAPE                         81
8004 #define TK_BITAND                         82
8005 #define TK_BITOR                          83
8006 #define TK_LSHIFT                         84
8007 #define TK_RSHIFT                         85
8008 #define TK_PLUS                           86
8009 #define TK_MINUS                          87
8010 #define TK_STAR                           88
8011 #define TK_SLASH                          89
8012 #define TK_REM                            90
8013 #define TK_CONCAT                         91
8014 #define TK_COLLATE                        92
8015 #define TK_BITNOT                         93
8016 #define TK_STRING                         94
8017 #define TK_JOIN_KW                        95
8018 #define TK_CONSTRAINT                     96
8019 #define TK_DEFAULT                        97
8020 #define TK_NULL                           98
8021 #define TK_PRIMARY                        99
8022 #define TK_UNIQUE                         100
8023 #define TK_CHECK                          101
8024 #define TK_REFERENCES                     102
8025 #define TK_AUTOINCR                       103
8026 #define TK_ON                             104
8027 #define TK_INSERT                         105
8028 #define TK_DELETE                         106
8029 #define TK_UPDATE                         107
8030 #define TK_SET                            108
8031 #define TK_DEFERRABLE                     109
8032 #define TK_FOREIGN                        110
8033 #define TK_DROP                           111
8034 #define TK_UNION                          112
8035 #define TK_ALL                            113
8036 #define TK_EXCEPT                         114
8037 #define TK_INTERSECT                      115
8038 #define TK_SELECT                         116
8039 #define TK_DISTINCT                       117
8040 #define TK_DOT                            118
8041 #define TK_FROM                           119
8042 #define TK_JOIN                           120
8043 #define TK_USING                          121
8044 #define TK_ORDER                          122
8045 #define TK_GROUP                          123
8046 #define TK_HAVING                         124
8047 #define TK_LIMIT                          125
8048 #define TK_WHERE                          126
8049 #define TK_INTO                           127
8050 #define TK_VALUES                         128
8051 #define TK_INTEGER                        129
8052 #define TK_FLOAT                          130
8053 #define TK_BLOB                           131
8054 #define TK_REGISTER                       132
8055 #define TK_VARIABLE                       133
8056 #define TK_CASE                           134
8057 #define TK_WHEN                           135
8058 #define TK_THEN                           136
8059 #define TK_ELSE                           137
8060 #define TK_INDEX                          138
8061 #define TK_ALTER                          139
8062 #define TK_ADD                            140
8063 #define TK_TO_TEXT                        141
8064 #define TK_TO_BLOB                        142
8065 #define TK_TO_NUMERIC                     143
8066 #define TK_TO_INT                         144
8067 #define TK_TO_REAL                        145
8068 #define TK_ISNOT                          146
8069 #define TK_END_OF_FILE                    147
8070 #define TK_ILLEGAL                        148
8071 #define TK_SPACE                          149
8072 #define TK_UNCLOSED_STRING                150
8073 #define TK_FUNCTION                       151
8074 #define TK_COLUMN                         152
8075 #define TK_AGG_FUNCTION                   153
8076 #define TK_AGG_COLUMN                     154
8077 #define TK_CONST_FUNC                     155
8078 #define TK_UMINUS                         156
8079 #define TK_UPLUS                          157
8080
8081 /************** End of parse.h ***********************************************/
8082 /************** Continuing where we left off in sqliteInt.h ******************/
8083 #include <stdio.h>
8084 #include <stdlib.h>
8085 #include <string.h>
8086 #include <assert.h>
8087 #include <stddef.h>
8088
8089 /*
8090 ** If compiling for a processor that lacks floating point support,
8091 ** substitute integer for floating-point
8092 */
8093 #ifdef SQLITE_OMIT_FLOATING_POINT
8094 # define double sqlite_int64
8095 # define float sqlite_int64
8096 # define LONGDOUBLE_TYPE sqlite_int64
8097 # ifndef SQLITE_BIG_DBL
8098 #   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
8099 # endif
8100 # define SQLITE_OMIT_DATETIME_FUNCS 1
8101 # define SQLITE_OMIT_TRACE 1
8102 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
8103 # undef SQLITE_HAVE_ISNAN
8104 #endif
8105 #ifndef SQLITE_BIG_DBL
8106 # define SQLITE_BIG_DBL (1e99)
8107 #endif
8108
8109 /*
8110 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
8111 ** afterward. Having this macro allows us to cause the C compiler 
8112 ** to omit code used by TEMP tables without messy #ifndef statements.
8113 */
8114 #ifdef SQLITE_OMIT_TEMPDB
8115 #define OMIT_TEMPDB 1
8116 #else
8117 #define OMIT_TEMPDB 0
8118 #endif
8119
8120 /*
8121 ** The "file format" number is an integer that is incremented whenever
8122 ** the VDBE-level file format changes.  The following macros define the
8123 ** the default file format for new databases and the maximum file format
8124 ** that the library can read.
8125 */
8126 #define SQLITE_MAX_FILE_FORMAT 4
8127 #ifndef SQLITE_DEFAULT_FILE_FORMAT
8128 # define SQLITE_DEFAULT_FILE_FORMAT 4
8129 #endif
8130
8131 /*
8132 ** Determine whether triggers are recursive by default.  This can be
8133 ** changed at run-time using a pragma.
8134 */
8135 #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
8136 # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
8137 #endif
8138
8139 /*
8140 ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
8141 ** on the command-line
8142 */
8143 #ifndef SQLITE_TEMP_STORE
8144 # define SQLITE_TEMP_STORE 1
8145 # define SQLITE_TEMP_STORE_xc 1  /* Exclude from ctime.c */
8146 #endif
8147
8148 /*
8149 ** GCC does not define the offsetof() macro so we'll have to do it
8150 ** ourselves.
8151 */
8152 #ifndef offsetof
8153 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
8154 #endif
8155
8156 /*
8157 ** Check to see if this machine uses EBCDIC.  (Yes, believe it or
8158 ** not, there are still machines out there that use EBCDIC.)
8159 */
8160 #if 'A' == '\301'
8161 # define SQLITE_EBCDIC 1
8162 #else
8163 # define SQLITE_ASCII 1
8164 #endif
8165
8166 /*
8167 ** Integers of known sizes.  These typedefs might change for architectures
8168 ** where the sizes very.  Preprocessor macros are available so that the
8169 ** types can be conveniently redefined at compile-type.  Like this:
8170 **
8171 **         cc '-DUINTPTR_TYPE=long long int' ...
8172 */
8173 #ifndef UINT32_TYPE
8174 # ifdef HAVE_UINT32_T
8175 #  define UINT32_TYPE uint32_t
8176 # else
8177 #  define UINT32_TYPE unsigned int
8178 # endif
8179 #endif
8180 #ifndef UINT16_TYPE
8181 # ifdef HAVE_UINT16_T
8182 #  define UINT16_TYPE uint16_t
8183 # else
8184 #  define UINT16_TYPE unsigned short int
8185 # endif
8186 #endif
8187 #ifndef INT16_TYPE
8188 # ifdef HAVE_INT16_T
8189 #  define INT16_TYPE int16_t
8190 # else
8191 #  define INT16_TYPE short int
8192 # endif
8193 #endif
8194 #ifndef UINT8_TYPE
8195 # ifdef HAVE_UINT8_T
8196 #  define UINT8_TYPE uint8_t
8197 # else
8198 #  define UINT8_TYPE unsigned char
8199 # endif
8200 #endif
8201 #ifndef INT8_TYPE
8202 # ifdef HAVE_INT8_T
8203 #  define INT8_TYPE int8_t
8204 # else
8205 #  define INT8_TYPE signed char
8206 # endif
8207 #endif
8208 #ifndef LONGDOUBLE_TYPE
8209 # define LONGDOUBLE_TYPE long double
8210 #endif
8211 typedef sqlite_int64 i64;          /* 8-byte signed integer */
8212 typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
8213 typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
8214 typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
8215 typedef INT16_TYPE i16;            /* 2-byte signed integer */
8216 typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
8217 typedef INT8_TYPE i8;              /* 1-byte signed integer */
8218
8219 /*
8220 ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
8221 ** that can be stored in a u32 without loss of data.  The value
8222 ** is 0x00000000ffffffff.  But because of quirks of some compilers, we
8223 ** have to specify the value in the less intuitive manner shown:
8224 */
8225 #define SQLITE_MAX_U32  ((((u64)1)<<32)-1)
8226
8227 /*
8228 ** The datatype used to store estimates of the number of rows in a
8229 ** table or index.  This is an unsigned integer type.  For 99.9% of
8230 ** the world, a 32-bit integer is sufficient.  But a 64-bit integer
8231 ** can be used at compile-time if desired.
8232 */
8233 #ifdef SQLITE_64BIT_STATS
8234  typedef u64 tRowcnt;    /* 64-bit only if requested at compile-time */
8235 #else
8236  typedef u32 tRowcnt;    /* 32-bit is the default */
8237 #endif
8238
8239 /*
8240 ** Macros to determine whether the machine is big or little endian,
8241 ** evaluated at runtime.
8242 */
8243 #ifdef SQLITE_AMALGAMATION
8244 SQLITE_PRIVATE const int sqlite3one = 1;
8245 #else
8246 SQLITE_PRIVATE const int sqlite3one;
8247 #endif
8248 #if defined(i386) || defined(__i386__) || defined(_M_IX86)\
8249                              || defined(__x86_64) || defined(__x86_64__)
8250 # define SQLITE_BIGENDIAN    0
8251 # define SQLITE_LITTLEENDIAN 1
8252 # define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
8253 #else
8254 # define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
8255 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
8256 # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
8257 #endif
8258
8259 /*
8260 ** Constants for the largest and smallest possible 64-bit signed integers.
8261 ** These macros are designed to work correctly on both 32-bit and 64-bit
8262 ** compilers.
8263 */
8264 #define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
8265 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
8266
8267 /* 
8268 ** Round up a number to the next larger multiple of 8.  This is used
8269 ** to force 8-byte alignment on 64-bit architectures.
8270 */
8271 #define ROUND8(x)     (((x)+7)&~7)
8272
8273 /*
8274 ** Round down to the nearest multiple of 8
8275 */
8276 #define ROUNDDOWN8(x) ((x)&~7)
8277
8278 /*
8279 ** Assert that the pointer X is aligned to an 8-byte boundary.  This
8280 ** macro is used only within assert() to verify that the code gets
8281 ** all alignment restrictions correct.
8282 **
8283 ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
8284 ** underlying malloc() implemention might return us 4-byte aligned
8285 ** pointers.  In that case, only verify 4-byte alignment.
8286 */
8287 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
8288 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&3)==0)
8289 #else
8290 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)
8291 #endif
8292
8293 /*
8294 ** Disable MMAP on platforms where it is known to not work
8295 */
8296 #if defined(__OpenBSD__) || defined(__QNXNTO__)
8297 # undef SQLITE_MAX_MMAP_SIZE
8298 # define SQLITE_MAX_MMAP_SIZE 0
8299 #endif
8300
8301 /*
8302 ** Default maximum size of memory used by memory-mapped I/O in the VFS
8303 */
8304 #ifdef __APPLE__
8305 # include <TargetConditionals.h>
8306 # if TARGET_OS_IPHONE
8307 #   undef SQLITE_MAX_MMAP_SIZE
8308 #   define SQLITE_MAX_MMAP_SIZE 0
8309 # endif
8310 #endif
8311 #ifndef SQLITE_MAX_MMAP_SIZE
8312 # if defined(__linux__) \
8313   || defined(_WIN32) \
8314   || (defined(__APPLE__) && defined(__MACH__)) \
8315   || defined(__sun)
8316 #   define SQLITE_MAX_MMAP_SIZE 0x7fff0000  /* 2147418112 */
8317 # else
8318 #   define SQLITE_MAX_MMAP_SIZE 0
8319 # endif
8320 # define SQLITE_MAX_MMAP_SIZE_xc 1 /* exclude from ctime.c */
8321 #endif
8322
8323 /*
8324 ** The default MMAP_SIZE is zero on all platforms.  Or, even if a larger
8325 ** default MMAP_SIZE is specified at compile-time, make sure that it does
8326 ** not exceed the maximum mmap size.
8327 */
8328 #ifndef SQLITE_DEFAULT_MMAP_SIZE
8329 # define SQLITE_DEFAULT_MMAP_SIZE 0
8330 # define SQLITE_DEFAULT_MMAP_SIZE_xc 1  /* Exclude from ctime.c */
8331 #endif
8332 #if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
8333 # undef SQLITE_DEFAULT_MMAP_SIZE
8334 # define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
8335 #endif
8336
8337 /*
8338 ** An instance of the following structure is used to store the busy-handler
8339 ** callback for a given sqlite handle. 
8340 **
8341 ** The sqlite.busyHandler member of the sqlite struct contains the busy
8342 ** callback for the database handle. Each pager opened via the sqlite
8343 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
8344 ** callback is currently invoked only from within pager.c.
8345 */
8346 typedef struct BusyHandler BusyHandler;
8347 struct BusyHandler {
8348   int (*xFunc)(void *,int);  /* The busy callback */
8349   void *pArg;                /* First arg to busy callback */
8350   int nBusy;                 /* Incremented with each busy call */
8351 };
8352
8353 /*
8354 ** Name of the master database table.  The master database table
8355 ** is a special table that holds the names and attributes of all
8356 ** user tables and indices.
8357 */
8358 #define MASTER_NAME       "sqlite_master"
8359 #define TEMP_MASTER_NAME  "sqlite_temp_master"
8360
8361 /*
8362 ** The root-page of the master database table.
8363 */
8364 #define MASTER_ROOT       1
8365
8366 /*
8367 ** The name of the schema table.
8368 */
8369 #define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
8370
8371 /*
8372 ** A convenience macro that returns the number of elements in
8373 ** an array.
8374 */
8375 #define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
8376
8377 /*
8378 ** Determine if the argument is a power of two
8379 */
8380 #define IsPowerOfTwo(X) (((X)&((X)-1))==0)
8381
8382 /*
8383 ** The following value as a destructor means to use sqlite3DbFree().
8384 ** The sqlite3DbFree() routine requires two parameters instead of the 
8385 ** one parameter that destructors normally want.  So we have to introduce 
8386 ** this magic value that the code knows to handle differently.  Any 
8387 ** pointer will work here as long as it is distinct from SQLITE_STATIC
8388 ** and SQLITE_TRANSIENT.
8389 */
8390 #define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3MallocSize)
8391
8392 /*
8393 ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
8394 ** not support Writable Static Data (WSD) such as global and static variables.
8395 ** All variables must either be on the stack or dynamically allocated from
8396 ** the heap.  When WSD is unsupported, the variable declarations scattered
8397 ** throughout the SQLite code must become constants instead.  The SQLITE_WSD
8398 ** macro is used for this purpose.  And instead of referencing the variable
8399 ** directly, we use its constant as a key to lookup the run-time allocated
8400 ** buffer that holds real variable.  The constant is also the initializer
8401 ** for the run-time allocated buffer.
8402 **
8403 ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
8404 ** macros become no-ops and have zero performance impact.
8405 */
8406 #ifdef SQLITE_OMIT_WSD
8407   #define SQLITE_WSD const
8408   #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
8409   #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
8410 SQLITE_API   int sqlite3_wsd_init(int N, int J);
8411 SQLITE_API   void *sqlite3_wsd_find(void *K, int L);
8412 #else
8413   #define SQLITE_WSD 
8414   #define GLOBAL(t,v) v
8415   #define sqlite3GlobalConfig sqlite3Config
8416 #endif
8417
8418 /*
8419 ** The following macros are used to suppress compiler warnings and to
8420 ** make it clear to human readers when a function parameter is deliberately 
8421 ** left unused within the body of a function. This usually happens when
8422 ** a function is called via a function pointer. For example the 
8423 ** implementation of an SQL aggregate step callback may not use the
8424 ** parameter indicating the number of arguments passed to the aggregate,
8425 ** if it knows that this is enforced elsewhere.
8426 **
8427 ** When a function parameter is not used at all within the body of a function,
8428 ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
8429 ** However, these macros may also be used to suppress warnings related to
8430 ** parameters that may or may not be used depending on compilation options.
8431 ** For example those parameters only used in assert() statements. In these
8432 ** cases the parameters are named as per the usual conventions.
8433 */
8434 #define UNUSED_PARAMETER(x) (void)(x)
8435 #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
8436
8437 /*
8438 ** Forward references to structures
8439 */
8440 typedef struct AggInfo AggInfo;
8441 typedef struct AuthContext AuthContext;
8442 typedef struct AutoincInfo AutoincInfo;
8443 typedef struct Bitvec Bitvec;
8444 typedef struct CollSeq CollSeq;
8445 typedef struct Column Column;
8446 typedef struct Db Db;
8447 typedef struct Schema Schema;
8448 typedef struct Expr Expr;
8449 typedef struct ExprList ExprList;
8450 typedef struct ExprSpan ExprSpan;
8451 typedef struct FKey FKey;
8452 typedef struct FuncDestructor FuncDestructor;
8453 typedef struct FuncDef FuncDef;
8454 typedef struct FuncDefHash FuncDefHash;
8455 typedef struct IdList IdList;
8456 typedef struct Index Index;
8457 typedef struct IndexSample IndexSample;
8458 typedef struct KeyClass KeyClass;
8459 typedef struct KeyInfo KeyInfo;
8460 typedef struct Lookaside Lookaside;
8461 typedef struct LookasideSlot LookasideSlot;
8462 typedef struct Module Module;
8463 typedef struct NameContext NameContext;
8464 typedef struct Parse Parse;
8465 typedef struct RowSet RowSet;
8466 typedef struct Savepoint Savepoint;
8467 typedef struct Select Select;
8468 typedef struct SelectDest SelectDest;
8469 typedef struct SrcList SrcList;
8470 typedef struct StrAccum StrAccum;
8471 typedef struct Table Table;
8472 typedef struct TableLock TableLock;
8473 typedef struct Token Token;
8474 typedef struct Trigger Trigger;
8475 typedef struct TriggerPrg TriggerPrg;
8476 typedef struct TriggerStep TriggerStep;
8477 typedef struct UnpackedRecord UnpackedRecord;
8478 typedef struct VTable VTable;
8479 typedef struct VtabCtx VtabCtx;
8480 typedef struct Walker Walker;
8481 typedef struct WherePlan WherePlan;
8482 typedef struct WhereInfo WhereInfo;
8483 typedef struct WhereLevel WhereLevel;
8484
8485 /*
8486 ** Defer sourcing vdbe.h and btree.h until after the "u8" and 
8487 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
8488 ** pointer types (i.e. FuncDef) defined above.
8489 */
8490 /************** Include btree.h in the middle of sqliteInt.h *****************/
8491 /************** Begin file btree.h *******************************************/
8492 /*
8493 ** 2001 September 15
8494 **
8495 ** The author disclaims copyright to this source code.  In place of
8496 ** a legal notice, here is a blessing:
8497 **
8498 **    May you do good and not evil.
8499 **    May you find forgiveness for yourself and forgive others.
8500 **    May you share freely, never taking more than you give.
8501 **
8502 *************************************************************************
8503 ** This header file defines the interface that the sqlite B-Tree file
8504 ** subsystem.  See comments in the source code for a detailed description
8505 ** of what each interface routine does.
8506 */
8507 #ifndef _BTREE_H_
8508 #define _BTREE_H_
8509
8510 /* TODO: This definition is just included so other modules compile. It
8511 ** needs to be revisited.
8512 */
8513 #define SQLITE_N_BTREE_META 10
8514
8515 /*
8516 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
8517 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
8518 */
8519 #ifndef SQLITE_DEFAULT_AUTOVACUUM
8520   #define SQLITE_DEFAULT_AUTOVACUUM 0
8521 #endif
8522
8523 #define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
8524 #define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
8525 #define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
8526
8527 /*
8528 ** Forward declarations of structure
8529 */
8530 typedef struct Btree Btree;
8531 typedef struct BtCursor BtCursor;
8532 typedef struct BtShared BtShared;
8533
8534
8535 SQLITE_PRIVATE int sqlite3BtreeOpen(
8536   sqlite3_vfs *pVfs,       /* VFS to use with this b-tree */
8537   const char *zFilename,   /* Name of database file to open */
8538   sqlite3 *db,             /* Associated database connection */
8539   Btree **ppBtree,         /* Return open Btree* here */
8540   int flags,               /* Flags */
8541   int vfsFlags             /* Flags passed through to VFS open */
8542 );
8543
8544 /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
8545 ** following values.
8546 **
8547 ** NOTE:  These values must match the corresponding PAGER_ values in
8548 ** pager.h.
8549 */
8550 #define BTREE_OMIT_JOURNAL  1  /* Do not create or use a rollback journal */
8551 #define BTREE_MEMORY        2  /* This is an in-memory DB */
8552 #define BTREE_SINGLE        4  /* The file contains at most 1 b-tree */
8553 #define BTREE_UNORDERED     8  /* Use of a hash implementation is OK */
8554
8555 SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
8556 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
8557 SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
8558 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int,int);
8559 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
8560 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
8561 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
8562 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
8563 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
8564 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
8565 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
8566 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG)
8567 SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
8568 #endif
8569 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
8570 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
8571 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
8572 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
8573 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
8574 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
8575 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int);
8576 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
8577 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
8578 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
8579 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
8580 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
8581 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
8582 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
8583 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
8584 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
8585
8586 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
8587 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
8588 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
8589
8590 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
8591
8592 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
8593 ** of the flags shown below.
8594 **
8595 ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
8596 ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
8597 ** is stored in the leaves.  (BTREE_INTKEY is used for SQL tables.)  With
8598 ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
8599 ** anywhere - the key is the content.  (BTREE_BLOBKEY is used for SQL
8600 ** indices.)
8601 */
8602 #define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
8603 #define BTREE_BLOBKEY    2    /* Table has keys only - no data */
8604
8605 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
8606 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
8607 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
8608
8609 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
8610 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
8611
8612 SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
8613
8614 /*
8615 ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
8616 ** should be one of the following values. The integer values are assigned 
8617 ** to constants so that the offset of the corresponding field in an
8618 ** SQLite database header may be found using the following formula:
8619 **
8620 **   offset = 36 + (idx * 4)
8621 **
8622 ** For example, the free-page-count field is located at byte offset 36 of
8623 ** the database file header. The incr-vacuum-flag field is located at
8624 ** byte offset 64 (== 36+4*7).
8625 */
8626 #define BTREE_FREE_PAGE_COUNT     0
8627 #define BTREE_SCHEMA_VERSION      1
8628 #define BTREE_FILE_FORMAT         2
8629 #define BTREE_DEFAULT_CACHE_SIZE  3
8630 #define BTREE_LARGEST_ROOT_PAGE   4
8631 #define BTREE_TEXT_ENCODING       5
8632 #define BTREE_USER_VERSION        6
8633 #define BTREE_INCR_VACUUM         7
8634 #define BTREE_APPLICATION_ID      8
8635
8636 /*
8637 ** Values that may be OR'd together to form the second argument of an
8638 ** sqlite3BtreeCursorHints() call.
8639 */
8640 #define BTREE_BULKLOAD 0x00000001
8641
8642 SQLITE_PRIVATE int sqlite3BtreeCursor(
8643   Btree*,                              /* BTree containing table to open */
8644   int iTable,                          /* Index of root page */
8645   int wrFlag,                          /* 1 for writing.  0 for read-only */
8646   struct KeyInfo*,                     /* First argument to compare function */
8647   BtCursor *pCursor                    /* Space to write cursor structure */
8648 );
8649 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
8650 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
8651
8652 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
8653 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
8654   BtCursor*,
8655   UnpackedRecord *pUnKey,
8656   i64 intKey,
8657   int bias,
8658   int *pRes
8659 );
8660 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
8661 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
8662 SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
8663                                   const void *pData, int nData,
8664                                   int nZero, int bias, int seekResult);
8665 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
8666 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
8667 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
8668 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
8669 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
8670 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
8671 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
8672 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
8673 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
8674 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
8675 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
8676 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64);
8677 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*);
8678
8679 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
8680 SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
8681
8682 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
8683 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
8684 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
8685 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
8686 SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *, unsigned int mask);
8687
8688 #ifndef NDEBUG
8689 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
8690 #endif
8691
8692 #ifndef SQLITE_OMIT_BTREECOUNT
8693 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
8694 #endif
8695
8696 #ifdef SQLITE_TEST
8697 SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
8698 SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
8699 #endif
8700
8701 #ifndef SQLITE_OMIT_WAL
8702 SQLITE_PRIVATE   int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
8703 #endif
8704
8705 /*
8706 ** If we are not using shared cache, then there is no need to
8707 ** use mutexes to access the BtShared structures.  So make the
8708 ** Enter and Leave procedures no-ops.
8709 */
8710 #ifndef SQLITE_OMIT_SHARED_CACHE
8711 SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
8712 SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
8713 #else
8714 # define sqlite3BtreeEnter(X) 
8715 # define sqlite3BtreeEnterAll(X)
8716 #endif
8717
8718 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
8719 SQLITE_PRIVATE   int sqlite3BtreeSharable(Btree*);
8720 SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
8721 SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
8722 SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
8723 SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
8724 #ifndef NDEBUG
8725   /* These routines are used inside assert() statements only. */
8726 SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
8727 SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
8728 SQLITE_PRIVATE   int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
8729 #endif
8730 #else
8731
8732 # define sqlite3BtreeSharable(X) 0
8733 # define sqlite3BtreeLeave(X)
8734 # define sqlite3BtreeEnterCursor(X)
8735 # define sqlite3BtreeLeaveCursor(X)
8736 # define sqlite3BtreeLeaveAll(X)
8737
8738 # define sqlite3BtreeHoldsMutex(X) 1
8739 # define sqlite3BtreeHoldsAllMutexes(X) 1
8740 # define sqlite3SchemaMutexHeld(X,Y,Z) 1
8741 #endif
8742
8743
8744 #endif /* _BTREE_H_ */
8745
8746 /************** End of btree.h ***********************************************/
8747 /************** Continuing where we left off in sqliteInt.h ******************/
8748 /************** Include vdbe.h in the middle of sqliteInt.h ******************/
8749 /************** Begin file vdbe.h ********************************************/
8750 /*
8751 ** 2001 September 15
8752 **
8753 ** The author disclaims copyright to this source code.  In place of
8754 ** a legal notice, here is a blessing:
8755 **
8756 **    May you do good and not evil.
8757 **    May you find forgiveness for yourself and forgive others.
8758 **    May you share freely, never taking more than you give.
8759 **
8760 *************************************************************************
8761 ** Header file for the Virtual DataBase Engine (VDBE)
8762 **
8763 ** This header defines the interface to the virtual database engine
8764 ** or VDBE.  The VDBE implements an abstract machine that runs a
8765 ** simple program to access and modify the underlying database.
8766 */
8767 #ifndef _SQLITE_VDBE_H_
8768 #define _SQLITE_VDBE_H_
8769 /* #include <stdio.h> */
8770
8771 /*
8772 ** A single VDBE is an opaque structure named "Vdbe".  Only routines
8773 ** in the source file sqliteVdbe.c are allowed to see the insides
8774 ** of this structure.
8775 */
8776 typedef struct Vdbe Vdbe;
8777
8778 /*
8779 ** The names of the following types declared in vdbeInt.h are required
8780 ** for the VdbeOp definition.
8781 */
8782 typedef struct VdbeFunc VdbeFunc;
8783 typedef struct Mem Mem;
8784 typedef struct SubProgram SubProgram;
8785
8786 /*
8787 ** A single instruction of the virtual machine has an opcode
8788 ** and as many as three operands.  The instruction is recorded
8789 ** as an instance of the following structure:
8790 */
8791 struct VdbeOp {
8792   u8 opcode;          /* What operation to perform */
8793   signed char p4type; /* One of the P4_xxx constants for p4 */
8794   u8 opflags;         /* Mask of the OPFLG_* flags in opcodes.h */
8795   u8 p5;              /* Fifth parameter is an unsigned character */
8796   int p1;             /* First operand */
8797   int p2;             /* Second parameter (often the jump destination) */
8798   int p3;             /* The third parameter */
8799   union {             /* fourth parameter */
8800     int i;                 /* Integer value if p4type==P4_INT32 */
8801     void *p;               /* Generic pointer */
8802     char *z;               /* Pointer to data for string (char array) types */
8803     i64 *pI64;             /* Used when p4type is P4_INT64 */
8804     double *pReal;         /* Used when p4type is P4_REAL */
8805     FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
8806     VdbeFunc *pVdbeFunc;   /* Used when p4type is P4_VDBEFUNC */
8807     CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
8808     Mem *pMem;             /* Used when p4type is P4_MEM */
8809     VTable *pVtab;         /* Used when p4type is P4_VTAB */
8810     KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
8811     int *ai;               /* Used when p4type is P4_INTARRAY */
8812     SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */
8813     int (*xAdvance)(BtCursor *, int *);
8814   } p4;
8815 #ifdef SQLITE_DEBUG
8816   char *zComment;          /* Comment to improve readability */
8817 #endif
8818 #ifdef VDBE_PROFILE
8819   int cnt;                 /* Number of times this instruction was executed */
8820   u64 cycles;              /* Total time spent executing this instruction */
8821 #endif
8822 };
8823 typedef struct VdbeOp VdbeOp;
8824
8825
8826 /*
8827 ** A sub-routine used to implement a trigger program.
8828 */
8829 struct SubProgram {
8830   VdbeOp *aOp;                  /* Array of opcodes for sub-program */
8831   int nOp;                      /* Elements in aOp[] */
8832   int nMem;                     /* Number of memory cells required */
8833   int nCsr;                     /* Number of cursors required */
8834   int nOnce;                    /* Number of OP_Once instructions */
8835   void *token;                  /* id that may be used to recursive triggers */
8836   SubProgram *pNext;            /* Next sub-program already visited */
8837 };
8838
8839 /*
8840 ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
8841 ** it takes up less space.
8842 */
8843 struct VdbeOpList {
8844   u8 opcode;          /* What operation to perform */
8845   signed char p1;     /* First operand */
8846   signed char p2;     /* Second parameter (often the jump destination) */
8847   signed char p3;     /* Third parameter */
8848 };
8849 typedef struct VdbeOpList VdbeOpList;
8850
8851 /*
8852 ** Allowed values of VdbeOp.p4type
8853 */
8854 #define P4_NOTUSED    0   /* The P4 parameter is not used */
8855 #define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
8856 #define P4_STATIC   (-2)  /* Pointer to a static string */
8857 #define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */
8858 #define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */
8859 #define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */
8860 #define P4_VDBEFUNC (-7)  /* P4 is a pointer to a VdbeFunc structure */
8861 #define P4_MEM      (-8)  /* P4 is a pointer to a Mem*    structure */
8862 #define P4_TRANSIENT  0   /* P4 is a pointer to a transient string */
8863 #define P4_VTAB     (-10) /* P4 is a pointer to an sqlite3_vtab structure */
8864 #define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlite3_mprintf() */
8865 #define P4_REAL     (-12) /* P4 is a 64-bit floating point value */
8866 #define P4_INT64    (-13) /* P4 is a 64-bit signed integer */
8867 #define P4_INT32    (-14) /* P4 is a 32-bit signed integer */
8868 #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
8869 #define P4_SUBPROGRAM  (-18) /* P4 is a pointer to a SubProgram structure */
8870 #define P4_ADVANCE  (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */
8871
8872 /* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
8873 ** is made.  That copy is freed when the Vdbe is finalized.  But if the
8874 ** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used.  It still
8875 ** gets freed when the Vdbe is finalized so it still should be obtained
8876 ** from a single sqliteMalloc().  But no copy is made and the calling
8877 ** function should *not* try to free the KeyInfo.
8878 */
8879 #define P4_KEYINFO_HANDOFF (-16)
8880 #define P4_KEYINFO_STATIC  (-17)
8881
8882 /*
8883 ** The Vdbe.aColName array contains 5n Mem structures, where n is the 
8884 ** number of columns of data returned by the statement.
8885 */
8886 #define COLNAME_NAME     0
8887 #define COLNAME_DECLTYPE 1
8888 #define COLNAME_DATABASE 2
8889 #define COLNAME_TABLE    3
8890 #define COLNAME_COLUMN   4
8891 #ifdef SQLITE_ENABLE_COLUMN_METADATA
8892 # define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
8893 #else
8894 # ifdef SQLITE_OMIT_DECLTYPE
8895 #   define COLNAME_N      1      /* Store only the name */
8896 # else
8897 #   define COLNAME_N      2      /* Store the name and decltype */
8898 # endif
8899 #endif
8900
8901 /*
8902 ** The following macro converts a relative address in the p2 field
8903 ** of a VdbeOp structure into a negative number so that 
8904 ** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
8905 ** the macro again restores the address.
8906 */
8907 #define ADDR(X)  (-1-(X))
8908
8909 /*
8910 ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
8911 ** header file that defines a number for each opcode used by the VDBE.
8912 */
8913 /************** Include opcodes.h in the middle of vdbe.h ********************/
8914 /************** Begin file opcodes.h *****************************************/
8915 /* Automatically generated.  Do not edit */
8916 /* See the mkopcodeh.awk script for details */
8917 #define OP_Goto                                 1
8918 #define OP_Gosub                                2
8919 #define OP_Return                               3
8920 #define OP_Yield                                4
8921 #define OP_HaltIfNull                           5
8922 #define OP_Halt                                 6
8923 #define OP_Integer                              7
8924 #define OP_Int64                                8
8925 #define OP_Real                               130   /* same as TK_FLOAT    */
8926 #define OP_String8                             94   /* same as TK_STRING   */
8927 #define OP_String                               9
8928 #define OP_Null                                10
8929 #define OP_Blob                                11
8930 #define OP_Variable                            12
8931 #define OP_Move                                13
8932 #define OP_Copy                                14
8933 #define OP_SCopy                               15
8934 #define OP_ResultRow                           16
8935 #define OP_Concat                              91   /* same as TK_CONCAT   */
8936 #define OP_Add                                 86   /* same as TK_PLUS     */
8937 #define OP_Subtract                            87   /* same as TK_MINUS    */
8938 #define OP_Multiply                            88   /* same as TK_STAR     */
8939 #define OP_Divide                              89   /* same as TK_SLASH    */
8940 #define OP_Remainder                           90   /* same as TK_REM      */
8941 #define OP_CollSeq                             17
8942 #define OP_Function                            18
8943 #define OP_BitAnd                              82   /* same as TK_BITAND   */
8944 #define OP_BitOr                               83   /* same as TK_BITOR    */
8945 #define OP_ShiftLeft                           84   /* same as TK_LSHIFT   */
8946 #define OP_ShiftRight                          85   /* same as TK_RSHIFT   */
8947 #define OP_AddImm                              20
8948 #define OP_MustBeInt                           21
8949 #define OP_RealAffinity                        22
8950 #define OP_ToText                             141   /* same as TK_TO_TEXT  */
8951 #define OP_ToBlob                             142   /* same as TK_TO_BLOB  */
8952 #define OP_ToNumeric                          143   /* same as TK_TO_NUMERIC*/
8953 #define OP_ToInt                              144   /* same as TK_TO_INT   */
8954 #define OP_ToReal                             145   /* same as TK_TO_REAL  */
8955 #define OP_Eq                                  76   /* same as TK_EQ       */
8956 #define OP_Ne                                  75   /* same as TK_NE       */
8957 #define OP_Lt                                  79   /* same as TK_LT       */
8958 #define OP_Le                                  78   /* same as TK_LE       */
8959 #define OP_Gt                                  77   /* same as TK_GT       */
8960 #define OP_Ge                                  80   /* same as TK_GE       */
8961 #define OP_Permutation                         23
8962 #define OP_Compare                             24
8963 #define OP_Jump                                25
8964 #define OP_And                                 69   /* same as TK_AND      */
8965 #define OP_Or                                  68   /* same as TK_OR       */
8966 #define OP_Not                                 19   /* same as TK_NOT      */
8967 #define OP_BitNot                              93   /* same as TK_BITNOT   */
8968 #define OP_Once                                26
8969 #define OP_If                                  27
8970 #define OP_IfNot                               28
8971 #define OP_IsNull                              73   /* same as TK_ISNULL   */
8972 #define OP_NotNull                             74   /* same as TK_NOTNULL  */
8973 #define OP_Column                              29
8974 #define OP_Affinity                            30
8975 #define OP_MakeRecord                          31
8976 #define OP_Count                               32
8977 #define OP_Savepoint                           33
8978 #define OP_AutoCommit                          34
8979 #define OP_Transaction                         35
8980 #define OP_ReadCookie                          36
8981 #define OP_SetCookie                           37
8982 #define OP_VerifyCookie                        38
8983 #define OP_OpenRead                            39
8984 #define OP_OpenWrite                           40
8985 #define OP_OpenAutoindex                       41
8986 #define OP_OpenEphemeral                       42
8987 #define OP_SorterOpen                          43
8988 #define OP_OpenPseudo                          44
8989 #define OP_Close                               45
8990 #define OP_SeekLt                              46
8991 #define OP_SeekLe                              47
8992 #define OP_SeekGe                              48
8993 #define OP_SeekGt                              49
8994 #define OP_Seek                                50
8995 #define OP_NotFound                            51
8996 #define OP_Found                               52
8997 #define OP_IsUnique                            53
8998 #define OP_NotExists                           54
8999 #define OP_Sequence                            55
9000 #define OP_NewRowid                            56
9001 #define OP_Insert                              57
9002 #define OP_InsertInt                           58
9003 #define OP_Delete                              59
9004 #define OP_ResetCount                          60
9005 #define OP_SorterCompare                       61
9006 #define OP_SorterData                          62
9007 #define OP_RowKey                              63
9008 #define OP_RowData                             64
9009 #define OP_Rowid                               65
9010 #define OP_NullRow                             66
9011 #define OP_Last                                67
9012 #define OP_SorterSort                          70
9013 #define OP_Sort                                71
9014 #define OP_Rewind                              72
9015 #define OP_SorterNext                          81
9016 #define OP_Prev                                92
9017 #define OP_Next                                95
9018 #define OP_SorterInsert                        96
9019 #define OP_IdxInsert                           97
9020 #define OP_IdxDelete                           98
9021 #define OP_IdxRowid                            99
9022 #define OP_IdxLT                              100
9023 #define OP_IdxGE                              101
9024 #define OP_Destroy                            102
9025 #define OP_Clear                              103
9026 #define OP_CreateIndex                        104
9027 #define OP_CreateTable                        105
9028 #define OP_ParseSchema                        106
9029 #define OP_LoadAnalysis                       107
9030 #define OP_DropTable                          108
9031 #define OP_DropIndex                          109
9032 #define OP_DropTrigger                        110
9033 #define OP_IntegrityCk                        111
9034 #define OP_RowSetAdd                          112
9035 #define OP_RowSetRead                         113
9036 #define OP_RowSetTest                         114
9037 #define OP_Program                            115
9038 #define OP_Param                              116
9039 #define OP_FkCounter                          117
9040 #define OP_FkIfZero                           118
9041 #define OP_MemMax                             119
9042 #define OP_IfPos                              120
9043 #define OP_IfNeg                              121
9044 #define OP_IfZero                             122
9045 #define OP_AggStep                            123
9046 #define OP_AggFinal                           124
9047 #define OP_Checkpoint                         125
9048 #define OP_JournalMode                        126
9049 #define OP_Vacuum                             127
9050 #define OP_IncrVacuum                         128
9051 #define OP_Expire                             129
9052 #define OP_TableLock                          131
9053 #define OP_VBegin                             132
9054 #define OP_VCreate                            133
9055 #define OP_VDestroy                           134
9056 #define OP_VOpen                              135
9057 #define OP_VFilter                            136
9058 #define OP_VColumn                            137
9059 #define OP_VNext                              138
9060 #define OP_VRename                            139
9061 #define OP_VUpdate                            140
9062 #define OP_Pagecount                          146
9063 #define OP_MaxPgcnt                           147
9064 #define OP_Trace                              148
9065 #define OP_Noop                               149
9066 #define OP_Explain                            150
9067
9068
9069 /* Properties such as "out2" or "jump" that are specified in
9070 ** comments following the "case" for each opcode in the vdbe.c
9071 ** are encoded into bitvectors as follows:
9072 */
9073 #define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */
9074 #define OPFLG_OUT2_PRERELEASE 0x0002  /* out2-prerelease: */
9075 #define OPFLG_IN1             0x0004  /* in1:   P1 is an input */
9076 #define OPFLG_IN2             0x0008  /* in2:   P2 is an input */
9077 #define OPFLG_IN3             0x0010  /* in3:   P3 is an input */
9078 #define OPFLG_OUT2            0x0020  /* out2:  P2 is an output */
9079 #define OPFLG_OUT3            0x0040  /* out3:  P3 is an output */
9080 #define OPFLG_INITIALIZER {\
9081 /*   0 */ 0x00, 0x01, 0x01, 0x04, 0x04, 0x10, 0x00, 0x02,\
9082 /*   8 */ 0x02, 0x02, 0x02, 0x02, 0x02, 0x00, 0x00, 0x24,\
9083 /*  16 */ 0x00, 0x00, 0x00, 0x24, 0x04, 0x05, 0x04, 0x00,\
9084 /*  24 */ 0x00, 0x01, 0x01, 0x05, 0x05, 0x00, 0x00, 0x00,\
9085 /*  32 */ 0x02, 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00,\
9086 /*  40 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x11,\
9087 /*  48 */ 0x11, 0x11, 0x08, 0x11, 0x11, 0x11, 0x11, 0x02,\
9088 /*  56 */ 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
9089 /*  64 */ 0x00, 0x02, 0x00, 0x01, 0x4c, 0x4c, 0x01, 0x01,\
9090 /*  72 */ 0x01, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
9091 /*  80 */ 0x15, 0x01, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\
9092 /*  88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x01, 0x24, 0x02, 0x01,\
9093 /*  96 */ 0x08, 0x08, 0x00, 0x02, 0x01, 0x01, 0x02, 0x00,\
9094 /* 104 */ 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
9095 /* 112 */ 0x0c, 0x45, 0x15, 0x01, 0x02, 0x00, 0x01, 0x08,\
9096 /* 120 */ 0x05, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02, 0x00,\
9097 /* 128 */ 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,\
9098 /* 136 */ 0x01, 0x00, 0x01, 0x00, 0x00, 0x04, 0x04, 0x04,\
9099 /* 144 */ 0x04, 0x04, 0x02, 0x02, 0x00, 0x00, 0x00,}
9100
9101 /************** End of opcodes.h *********************************************/
9102 /************** Continuing where we left off in vdbe.h ***********************/
9103
9104 /*
9105 ** Prototypes for the VDBE interface.  See comments on the implementation
9106 ** for a description of what each of these routines does.
9107 */
9108 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
9109 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
9110 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
9111 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
9112 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
9113 SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
9114 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
9115 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
9116 SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
9117 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
9118 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
9119 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
9120 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
9121 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
9122 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr);
9123 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
9124 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
9125 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
9126 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
9127 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
9128 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
9129 SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
9130 SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
9131 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
9132 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
9133 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
9134 #ifdef SQLITE_DEBUG
9135 SQLITE_PRIVATE   int sqlite3VdbeAssertMayAbort(Vdbe *, int);
9136 SQLITE_PRIVATE   void sqlite3VdbeTrace(Vdbe*,FILE*);
9137 #endif
9138 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
9139 SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
9140 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
9141 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
9142 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
9143 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
9144 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
9145 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
9146 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
9147 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
9148 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe*, int, u8);
9149 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
9150 #ifndef SQLITE_OMIT_TRACE
9151 SQLITE_PRIVATE   char *sqlite3VdbeExpandSql(Vdbe*, const char*);
9152 #endif
9153
9154 SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
9155 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
9156 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **);
9157
9158 #ifndef SQLITE_OMIT_TRIGGER
9159 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
9160 #endif
9161
9162
9163 #ifndef NDEBUG
9164 SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
9165 # define VdbeComment(X)  sqlite3VdbeComment X
9166 SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
9167 # define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
9168 #else
9169 # define VdbeComment(X)
9170 # define VdbeNoopComment(X)
9171 #endif
9172
9173 #endif
9174
9175 /************** End of vdbe.h ************************************************/
9176 /************** Continuing where we left off in sqliteInt.h ******************/
9177 /************** Include pager.h in the middle of sqliteInt.h *****************/
9178 /************** Begin file pager.h *******************************************/
9179 /*
9180 ** 2001 September 15
9181 **
9182 ** The author disclaims copyright to this source code.  In place of
9183 ** a legal notice, here is a blessing:
9184 **
9185 **    May you do good and not evil.
9186 **    May you find forgiveness for yourself and forgive others.
9187 **    May you share freely, never taking more than you give.
9188 **
9189 *************************************************************************
9190 ** This header file defines the interface that the sqlite page cache
9191 ** subsystem.  The page cache subsystem reads and writes a file a page
9192 ** at a time and provides a journal for rollback.
9193 */
9194
9195 #ifndef _PAGER_H_
9196 #define _PAGER_H_
9197
9198 /*
9199 ** Default maximum size for persistent journal files. A negative 
9200 ** value means no limit. This value may be overridden using the 
9201 ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
9202 */
9203 #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
9204   #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
9205 #endif
9206
9207 /*
9208 ** The type used to represent a page number.  The first page in a file
9209 ** is called page 1.  0 is used to represent "not a page".
9210 */
9211 typedef u32 Pgno;
9212
9213 /*
9214 ** Each open file is managed by a separate instance of the "Pager" structure.
9215 */
9216 typedef struct Pager Pager;
9217
9218 /*
9219 ** Handle type for pages.
9220 */
9221 typedef struct PgHdr DbPage;
9222
9223 /*
9224 ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
9225 ** reserved for working around a windows/posix incompatibility). It is
9226 ** used in the journal to signify that the remainder of the journal file 
9227 ** is devoted to storing a master journal name - there are no more pages to
9228 ** roll back. See comments for function writeMasterJournal() in pager.c 
9229 ** for details.
9230 */
9231 #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
9232
9233 /*
9234 ** Allowed values for the flags parameter to sqlite3PagerOpen().
9235 **
9236 ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
9237 */
9238 #define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
9239 #define PAGER_MEMORY        0x0002    /* In-memory database */
9240
9241 /*
9242 ** Valid values for the second argument to sqlite3PagerLockingMode().
9243 */
9244 #define PAGER_LOCKINGMODE_QUERY      -1
9245 #define PAGER_LOCKINGMODE_NORMAL      0
9246 #define PAGER_LOCKINGMODE_EXCLUSIVE   1
9247
9248 /*
9249 ** Numeric constants that encode the journalmode.  
9250 */
9251 #define PAGER_JOURNALMODE_QUERY     (-1)  /* Query the value of journalmode */
9252 #define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
9253 #define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
9254 #define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
9255 #define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
9256 #define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
9257 #define PAGER_JOURNALMODE_WAL         5   /* Use write-ahead logging */
9258
9259 /*
9260 ** Flags that make up the mask passed to sqlite3PagerAcquire().
9261 */
9262 #define PAGER_ACQUIRE_NOCONTENT     0x01  /* Do not load data from disk */
9263 #define PAGER_ACQUIRE_READONLY      0x02  /* Read-only page is acceptable */
9264
9265 /*
9266 ** The remainder of this file contains the declarations of the functions
9267 ** that make up the Pager sub-system API. See source code comments for 
9268 ** a detailed description of each routine.
9269 */
9270
9271 /* Open and close a Pager connection. */ 
9272 SQLITE_PRIVATE int sqlite3PagerOpen(
9273   sqlite3_vfs*,
9274   Pager **ppPager,
9275   const char*,
9276   int,
9277   int,
9278   int,
9279   void(*)(DbPage*)
9280 );
9281 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
9282 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
9283
9284 /* Functions used to configure a Pager object. */
9285 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
9286 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
9287 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
9288 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
9289 SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
9290 SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
9291 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int,int);
9292 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
9293 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
9294 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
9295 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
9296 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
9297 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
9298
9299 /* Functions used to obtain and release page references. */ 
9300 SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
9301 #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
9302 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
9303 SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
9304 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
9305
9306 /* Operations on page references. */
9307 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
9308 SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
9309 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
9310 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
9311 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *); 
9312 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *); 
9313
9314 /* Functions used to manage pager transactions and savepoints. */
9315 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
9316 SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
9317 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
9318 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
9319 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
9320 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
9321 SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
9322 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
9323 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
9324 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
9325
9326 #ifndef SQLITE_OMIT_WAL
9327 SQLITE_PRIVATE   int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);
9328 SQLITE_PRIVATE   int sqlite3PagerWalSupported(Pager *pPager);
9329 SQLITE_PRIVATE   int sqlite3PagerWalCallback(Pager *pPager);
9330 SQLITE_PRIVATE   int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
9331 SQLITE_PRIVATE   int sqlite3PagerCloseWal(Pager *pPager);
9332 #endif
9333
9334 #ifdef SQLITE_ENABLE_ZIPVFS
9335 SQLITE_PRIVATE   int sqlite3PagerWalFramesize(Pager *pPager);
9336 #endif
9337
9338 /* Functions used to query pager state and configuration. */
9339 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
9340 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
9341 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
9342 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
9343 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
9344 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
9345 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
9346 SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
9347 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
9348 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
9349 SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
9350 SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *);
9351 SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
9352
9353 /* Functions used to truncate the database file. */
9354 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
9355
9356 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
9357 SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
9358 #endif
9359
9360 /* Functions to support testing and debugging. */
9361 #if !defined(NDEBUG) || defined(SQLITE_TEST)
9362 SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
9363 SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
9364 #endif
9365 #ifdef SQLITE_TEST
9366 SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
9367 SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
9368   void disable_simulated_io_errors(void);
9369   void enable_simulated_io_errors(void);
9370 #else
9371 # define disable_simulated_io_errors()
9372 # define enable_simulated_io_errors()
9373 #endif
9374
9375 #endif /* _PAGER_H_ */
9376
9377 /************** End of pager.h ***********************************************/
9378 /************** Continuing where we left off in sqliteInt.h ******************/
9379 /************** Include pcache.h in the middle of sqliteInt.h ****************/
9380 /************** Begin file pcache.h ******************************************/
9381 /*
9382 ** 2008 August 05
9383 **
9384 ** The author disclaims copyright to this source code.  In place of
9385 ** a legal notice, here is a blessing:
9386 **
9387 **    May you do good and not evil.
9388 **    May you find forgiveness for yourself and forgive others.
9389 **    May you share freely, never taking more than you give.
9390 **
9391 *************************************************************************
9392 ** This header file defines the interface that the sqlite page cache
9393 ** subsystem. 
9394 */
9395
9396 #ifndef _PCACHE_H_
9397
9398 typedef struct PgHdr PgHdr;
9399 typedef struct PCache PCache;
9400
9401 /*
9402 ** Every page in the cache is controlled by an instance of the following
9403 ** structure.
9404 */
9405 struct PgHdr {
9406   sqlite3_pcache_page *pPage;    /* Pcache object page handle */
9407   void *pData;                   /* Page data */
9408   void *pExtra;                  /* Extra content */
9409   PgHdr *pDirty;                 /* Transient list of dirty pages */
9410   Pager *pPager;                 /* The pager this page is part of */
9411   Pgno pgno;                     /* Page number for this page */
9412 #ifdef SQLITE_CHECK_PAGES
9413   u32 pageHash;                  /* Hash of page content */
9414 #endif
9415   u16 flags;                     /* PGHDR flags defined below */
9416
9417   /**********************************************************************
9418   ** Elements above are public.  All that follows is private to pcache.c
9419   ** and should not be accessed by other modules.
9420   */
9421   i16 nRef;                      /* Number of users of this page */
9422   PCache *pCache;                /* Cache that owns this page */
9423
9424   PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
9425   PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
9426 };
9427
9428 /* Bit values for PgHdr.flags */
9429 #define PGHDR_DIRTY             0x002  /* Page has changed */
9430 #define PGHDR_NEED_SYNC         0x004  /* Fsync the rollback journal before
9431                                        ** writing this page to the database */
9432 #define PGHDR_NEED_READ         0x008  /* Content is unread */
9433 #define PGHDR_REUSE_UNLIKELY    0x010  /* A hint that reuse is unlikely */
9434 #define PGHDR_DONT_WRITE        0x020  /* Do not write content to disk */
9435
9436 #define PGHDR_MMAP              0x040  /* This is an mmap page object */
9437
9438 /* Initialize and shutdown the page cache subsystem */
9439 SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
9440 SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
9441
9442 /* Page cache buffer management:
9443 ** These routines implement SQLITE_CONFIG_PAGECACHE.
9444 */
9445 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
9446
9447 /* Create a new pager cache.
9448 ** Under memory stress, invoke xStress to try to make pages clean.
9449 ** Only clean and unpinned pages can be reclaimed.
9450 */
9451 SQLITE_PRIVATE void sqlite3PcacheOpen(
9452   int szPage,                    /* Size of every page */
9453   int szExtra,                   /* Extra space associated with each page */
9454   int bPurgeable,                /* True if pages are on backing store */
9455   int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
9456   void *pStress,                 /* Argument to xStress */
9457   PCache *pToInit                /* Preallocated space for the PCache */
9458 );
9459
9460 /* Modify the page-size after the cache has been created. */
9461 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
9462
9463 /* Return the size in bytes of a PCache object.  Used to preallocate
9464 ** storage space.
9465 */
9466 SQLITE_PRIVATE int sqlite3PcacheSize(void);
9467
9468 /* One release per successful fetch.  Page is pinned until released.
9469 ** Reference counted. 
9470 */
9471 SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
9472 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
9473
9474 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
9475 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
9476 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
9477 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
9478
9479 /* Change a page number.  Used by incr-vacuum. */
9480 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
9481
9482 /* Remove all pages with pgno>x.  Reset the cache if x==0 */
9483 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
9484
9485 /* Get a list of all dirty pages in the cache, sorted by page number */
9486 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
9487
9488 /* Reset and close the cache object */
9489 SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
9490
9491 /* Clear flags from pages of the page cache */
9492 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
9493
9494 /* Discard the contents of the cache */
9495 SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
9496
9497 /* Return the total number of outstanding page references */
9498 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
9499
9500 /* Increment the reference count of an existing page */
9501 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
9502
9503 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
9504
9505 /* Return the total number of pages stored in the cache */
9506 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
9507
9508 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
9509 /* Iterate through all dirty pages currently stored in the cache. This
9510 ** interface is only available if SQLITE_CHECK_PAGES is defined when the 
9511 ** library is built.
9512 */
9513 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
9514 #endif
9515
9516 /* Set and get the suggested cache-size for the specified pager-cache.
9517 **
9518 ** If no global maximum is configured, then the system attempts to limit
9519 ** the total number of pages cached by purgeable pager-caches to the sum
9520 ** of the suggested cache-sizes.
9521 */
9522 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
9523 #ifdef SQLITE_TEST
9524 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
9525 #endif
9526
9527 /* Free up as much memory as possible from the page cache */
9528 SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
9529
9530 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
9531 /* Try to return memory used by the pcache module to the main memory heap */
9532 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
9533 #endif
9534
9535 #ifdef SQLITE_TEST
9536 SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
9537 #endif
9538
9539 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
9540
9541 #endif /* _PCACHE_H_ */
9542
9543 /************** End of pcache.h **********************************************/
9544 /************** Continuing where we left off in sqliteInt.h ******************/
9545
9546 /************** Include os.h in the middle of sqliteInt.h ********************/
9547 /************** Begin file os.h **********************************************/
9548 /*
9549 ** 2001 September 16
9550 **
9551 ** The author disclaims copyright to this source code.  In place of
9552 ** a legal notice, here is a blessing:
9553 **
9554 **    May you do good and not evil.
9555 **    May you find forgiveness for yourself and forgive others.
9556 **    May you share freely, never taking more than you give.
9557 **
9558 ******************************************************************************
9559 **
9560 ** This header file (together with is companion C source-code file
9561 ** "os.c") attempt to abstract the underlying operating system so that
9562 ** the SQLite library will work on both POSIX and windows systems.
9563 **
9564 ** This header file is #include-ed by sqliteInt.h and thus ends up
9565 ** being included by every source file.
9566 */
9567 #ifndef _SQLITE_OS_H_
9568 #define _SQLITE_OS_H_
9569
9570 /*
9571 ** Figure out if we are dealing with Unix, Windows, or some other
9572 ** operating system.  After the following block of preprocess macros,
9573 ** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, and SQLITE_OS_OTHER 
9574 ** will defined to either 1 or 0.  One of the four will be 1.  The other 
9575 ** three will be 0.
9576 */
9577 #if defined(SQLITE_OS_OTHER)
9578 # if SQLITE_OS_OTHER==1
9579 #   undef SQLITE_OS_UNIX
9580 #   define SQLITE_OS_UNIX 0
9581 #   undef SQLITE_OS_WIN
9582 #   define SQLITE_OS_WIN 0
9583 # else
9584 #   undef SQLITE_OS_OTHER
9585 # endif
9586 #endif
9587 #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
9588 # define SQLITE_OS_OTHER 0
9589 # ifndef SQLITE_OS_WIN
9590 #   if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
9591 #     define SQLITE_OS_WIN 1
9592 #     define SQLITE_OS_UNIX 0
9593 #   else
9594 #     define SQLITE_OS_WIN 0
9595 #     define SQLITE_OS_UNIX 1
9596 #  endif
9597 # else
9598 #  define SQLITE_OS_UNIX 0
9599 # endif
9600 #else
9601 # ifndef SQLITE_OS_WIN
9602 #  define SQLITE_OS_WIN 0
9603 # endif
9604 #endif
9605
9606 #if SQLITE_OS_WIN
9607 # include <windows.h>
9608 #endif
9609
9610 /*
9611 ** Determine if we are dealing with Windows NT.
9612 **
9613 ** We ought to be able to determine if we are compiling for win98 or winNT
9614 ** using the _WIN32_WINNT macro as follows:
9615 **
9616 ** #if defined(_WIN32_WINNT)
9617 ** # define SQLITE_OS_WINNT 1
9618 ** #else
9619 ** # define SQLITE_OS_WINNT 0
9620 ** #endif
9621 **
9622 ** However, vs2005 does not set _WIN32_WINNT by default, as it ought to,
9623 ** so the above test does not work.  We'll just assume that everything is
9624 ** winNT unless the programmer explicitly says otherwise by setting
9625 ** SQLITE_OS_WINNT to 0.
9626 */
9627 #if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
9628 # define SQLITE_OS_WINNT 1
9629 #endif
9630
9631 /*
9632 ** Determine if we are dealing with WindowsCE - which has a much
9633 ** reduced API.
9634 */
9635 #if defined(_WIN32_WCE)
9636 # define SQLITE_OS_WINCE 1
9637 #else
9638 # define SQLITE_OS_WINCE 0
9639 #endif
9640
9641 /*
9642 ** Determine if we are dealing with WinRT, which provides only a subset of
9643 ** the full Win32 API.
9644 */
9645 #if !defined(SQLITE_OS_WINRT)
9646 # define SQLITE_OS_WINRT 0
9647 #endif
9648
9649 /* If the SET_FULLSYNC macro is not defined above, then make it
9650 ** a no-op
9651 */
9652 #ifndef SET_FULLSYNC
9653 # define SET_FULLSYNC(x,y)
9654 #endif
9655
9656 /*
9657 ** The default size of a disk sector
9658 */
9659 #ifndef SQLITE_DEFAULT_SECTOR_SIZE
9660 # define SQLITE_DEFAULT_SECTOR_SIZE 4096
9661 #endif
9662
9663 /*
9664 ** Temporary files are named starting with this prefix followed by 16 random
9665 ** alphanumeric characters, and no file extension. They are stored in the
9666 ** OS's standard temporary file directory, and are deleted prior to exit.
9667 ** If sqlite is being embedded in another program, you may wish to change the
9668 ** prefix to reflect your program's name, so that if your program exits
9669 ** prematurely, old temporary files can be easily identified. This can be done
9670 ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
9671 **
9672 ** 2006-10-31:  The default prefix used to be "sqlite_".  But then
9673 ** Mcafee started using SQLite in their anti-virus product and it
9674 ** started putting files with the "sqlite" name in the c:/temp folder.
9675 ** This annoyed many windows users.  Those users would then do a 
9676 ** Google search for "sqlite", find the telephone numbers of the
9677 ** developers and call to wake them up at night and complain.
9678 ** For this reason, the default name prefix is changed to be "sqlite" 
9679 ** spelled backwards.  So the temp files are still identified, but
9680 ** anybody smart enough to figure out the code is also likely smart
9681 ** enough to know that calling the developer will not help get rid
9682 ** of the file.
9683 */
9684 #ifndef SQLITE_TEMP_FILE_PREFIX
9685 # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
9686 #endif
9687
9688 /*
9689 ** The following values may be passed as the second argument to
9690 ** sqlite3OsLock(). The various locks exhibit the following semantics:
9691 **
9692 ** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
9693 ** RESERVED:  A single process may hold a RESERVED lock on a file at
9694 **            any time. Other processes may hold and obtain new SHARED locks.
9695 ** PENDING:   A single process may hold a PENDING lock on a file at
9696 **            any one time. Existing SHARED locks may persist, but no new
9697 **            SHARED locks may be obtained by other processes.
9698 ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
9699 **
9700 ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
9701 ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
9702 ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
9703 ** sqlite3OsLock().
9704 */
9705 #define NO_LOCK         0
9706 #define SHARED_LOCK     1
9707 #define RESERVED_LOCK   2
9708 #define PENDING_LOCK    3
9709 #define EXCLUSIVE_LOCK  4
9710
9711 /*
9712 ** File Locking Notes:  (Mostly about windows but also some info for Unix)
9713 **
9714 ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
9715 ** those functions are not available.  So we use only LockFile() and
9716 ** UnlockFile().
9717 **
9718 ** LockFile() prevents not just writing but also reading by other processes.
9719 ** A SHARED_LOCK is obtained by locking a single randomly-chosen 
9720 ** byte out of a specific range of bytes. The lock byte is obtained at 
9721 ** random so two separate readers can probably access the file at the 
9722 ** same time, unless they are unlucky and choose the same lock byte.
9723 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
9724 ** There can only be one writer.  A RESERVED_LOCK is obtained by locking
9725 ** a single byte of the file that is designated as the reserved lock byte.
9726 ** A PENDING_LOCK is obtained by locking a designated byte different from
9727 ** the RESERVED_LOCK byte.
9728 **
9729 ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
9730 ** which means we can use reader/writer locks.  When reader/writer locks
9731 ** are used, the lock is placed on the same range of bytes that is used
9732 ** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
9733 ** will support two or more Win95 readers or two or more WinNT readers.
9734 ** But a single Win95 reader will lock out all WinNT readers and a single
9735 ** WinNT reader will lock out all other Win95 readers.
9736 **
9737 ** The following #defines specify the range of bytes used for locking.
9738 ** SHARED_SIZE is the number of bytes available in the pool from which
9739 ** a random byte is selected for a shared lock.  The pool of bytes for
9740 ** shared locks begins at SHARED_FIRST. 
9741 **
9742 ** The same locking strategy and
9743 ** byte ranges are used for Unix.  This leaves open the possiblity of having
9744 ** clients on win95, winNT, and unix all talking to the same shared file
9745 ** and all locking correctly.  To do so would require that samba (or whatever
9746 ** tool is being used for file sharing) implements locks correctly between
9747 ** windows and unix.  I'm guessing that isn't likely to happen, but by
9748 ** using the same locking range we are at least open to the possibility.
9749 **
9750 ** Locking in windows is manditory.  For this reason, we cannot store
9751 ** actual data in the bytes used for locking.  The pager never allocates
9752 ** the pages involved in locking therefore.  SHARED_SIZE is selected so
9753 ** that all locks will fit on a single page even at the minimum page size.
9754 ** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
9755 ** is set high so that we don't have to allocate an unused page except
9756 ** for very large databases.  But one should test the page skipping logic 
9757 ** by setting PENDING_BYTE low and running the entire regression suite.
9758 **
9759 ** Changing the value of PENDING_BYTE results in a subtly incompatible
9760 ** file format.  Depending on how it is changed, you might not notice
9761 ** the incompatibility right away, even running a full regression test.
9762 ** The default location of PENDING_BYTE is the first byte past the
9763 ** 1GB boundary.
9764 **
9765 */
9766 #ifdef SQLITE_OMIT_WSD
9767 # define PENDING_BYTE     (0x40000000)
9768 #else
9769 # define PENDING_BYTE      sqlite3PendingByte
9770 #endif
9771 #define RESERVED_BYTE     (PENDING_BYTE+1)
9772 #define SHARED_FIRST      (PENDING_BYTE+2)
9773 #define SHARED_SIZE       510
9774
9775 /*
9776 ** Wrapper around OS specific sqlite3_os_init() function.
9777 */
9778 SQLITE_PRIVATE int sqlite3OsInit(void);
9779
9780 /* 
9781 ** Functions for accessing sqlite3_file methods 
9782 */
9783 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
9784 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
9785 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
9786 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
9787 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
9788 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
9789 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
9790 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
9791 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
9792 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
9793 SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
9794 #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
9795 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
9796 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
9797 SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
9798 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
9799 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
9800 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
9801 SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
9802 SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
9803
9804
9805 /* 
9806 ** Functions for accessing sqlite3_vfs methods 
9807 */
9808 SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
9809 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
9810 SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
9811 SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
9812 #ifndef SQLITE_OMIT_LOAD_EXTENSION
9813 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
9814 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
9815 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
9816 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
9817 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
9818 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
9819 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
9820 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
9821
9822 /*
9823 ** Convenience functions for opening and closing files using 
9824 ** sqlite3_malloc() to obtain space for the file-handle structure.
9825 */
9826 SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
9827 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
9828
9829 #endif /* _SQLITE_OS_H_ */
9830
9831 /************** End of os.h **************************************************/
9832 /************** Continuing where we left off in sqliteInt.h ******************/
9833 /************** Include mutex.h in the middle of sqliteInt.h *****************/
9834 /************** Begin file mutex.h *******************************************/
9835 /*
9836 ** 2007 August 28
9837 **
9838 ** The author disclaims copyright to this source code.  In place of
9839 ** a legal notice, here is a blessing:
9840 **
9841 **    May you do good and not evil.
9842 **    May you find forgiveness for yourself and forgive others.
9843 **    May you share freely, never taking more than you give.
9844 **
9845 *************************************************************************
9846 **
9847 ** This file contains the common header for all mutex implementations.
9848 ** The sqliteInt.h header #includes this file so that it is available
9849 ** to all source files.  We break it out in an effort to keep the code
9850 ** better organized.
9851 **
9852 ** NOTE:  source files should *not* #include this header file directly.
9853 ** Source files should #include the sqliteInt.h file and let that file
9854 ** include this one indirectly.
9855 */
9856
9857
9858 /*
9859 ** Figure out what version of the code to use.  The choices are
9860 **
9861 **   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
9862 **                             mutexes implemention cannot be overridden
9863 **                             at start-time.
9864 **
9865 **   SQLITE_MUTEX_NOOP         For single-threaded applications.  No
9866 **                             mutual exclusion is provided.  But this
9867 **                             implementation can be overridden at
9868 **                             start-time.
9869 **
9870 **   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
9871 **
9872 **   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
9873 */
9874 #if !SQLITE_THREADSAFE
9875 # define SQLITE_MUTEX_OMIT
9876 #endif
9877 #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
9878 #  if SQLITE_OS_UNIX
9879 #    define SQLITE_MUTEX_PTHREADS
9880 #  elif SQLITE_OS_WIN
9881 #    define SQLITE_MUTEX_W32
9882 #  else
9883 #    define SQLITE_MUTEX_NOOP
9884 #  endif
9885 #endif
9886
9887 #ifdef SQLITE_MUTEX_OMIT
9888 /*
9889 ** If this is a no-op implementation, implement everything as macros.
9890 */
9891 #define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
9892 #define sqlite3_mutex_free(X)
9893 #define sqlite3_mutex_enter(X)    
9894 #define sqlite3_mutex_try(X)      SQLITE_OK
9895 #define sqlite3_mutex_leave(X)    
9896 #define sqlite3_mutex_held(X)     ((void)(X),1)
9897 #define sqlite3_mutex_notheld(X)  ((void)(X),1)
9898 #define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
9899 #define sqlite3MutexInit()        SQLITE_OK
9900 #define sqlite3MutexEnd()
9901 #define MUTEX_LOGIC(X)
9902 #else
9903 #define MUTEX_LOGIC(X)            X
9904 #endif /* defined(SQLITE_MUTEX_OMIT) */
9905
9906 /************** End of mutex.h ***********************************************/
9907 /************** Continuing where we left off in sqliteInt.h ******************/
9908
9909
9910 /*
9911 ** Each database file to be accessed by the system is an instance
9912 ** of the following structure.  There are normally two of these structures
9913 ** in the sqlite.aDb[] array.  aDb[0] is the main database file and
9914 ** aDb[1] is the database file used to hold temporary tables.  Additional
9915 ** databases may be attached.
9916 */
9917 struct Db {
9918   char *zName;         /* Name of this database */
9919   Btree *pBt;          /* The B*Tree structure for this database file */
9920   u8 inTrans;          /* 0: not writable.  1: Transaction.  2: Checkpoint */
9921   u8 safety_level;     /* How aggressive at syncing data to disk */
9922   Schema *pSchema;     /* Pointer to database schema (possibly shared) */
9923 };
9924
9925 /*
9926 ** An instance of the following structure stores a database schema.
9927 **
9928 ** Most Schema objects are associated with a Btree.  The exception is
9929 ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
9930 ** In shared cache mode, a single Schema object can be shared by multiple
9931 ** Btrees that refer to the same underlying BtShared object.
9932 ** 
9933 ** Schema objects are automatically deallocated when the last Btree that
9934 ** references them is destroyed.   The TEMP Schema is manually freed by
9935 ** sqlite3_close().
9936 *
9937 ** A thread must be holding a mutex on the corresponding Btree in order
9938 ** to access Schema content.  This implies that the thread must also be
9939 ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
9940 ** For a TEMP Schema, only the connection mutex is required.
9941 */
9942 struct Schema {
9943   int schema_cookie;   /* Database schema version number for this file */
9944   int iGeneration;     /* Generation counter.  Incremented with each change */
9945   Hash tblHash;        /* All tables indexed by name */
9946   Hash idxHash;        /* All (named) indices indexed by name */
9947   Hash trigHash;       /* All triggers indexed by name */
9948   Hash fkeyHash;       /* All foreign keys by referenced table name */
9949   Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
9950   u8 file_format;      /* Schema format version for this file */
9951   u8 enc;              /* Text encoding used by this database */
9952   u16 flags;           /* Flags associated with this schema */
9953   int cache_size;      /* Number of pages to use in the cache */
9954 };
9955
9956 /*
9957 ** These macros can be used to test, set, or clear bits in the 
9958 ** Db.pSchema->flags field.
9959 */
9960 #define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->flags&(P))==(P))
9961 #define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->flags&(P))!=0)
9962 #define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->flags|=(P)
9963 #define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->flags&=~(P)
9964
9965 /*
9966 ** Allowed values for the DB.pSchema->flags field.
9967 **
9968 ** The DB_SchemaLoaded flag is set after the database schema has been
9969 ** read into internal hash tables.
9970 **
9971 ** DB_UnresetViews means that one or more views have column names that
9972 ** have been filled out.  If the schema changes, these column names might
9973 ** changes and so the view will need to be reset.
9974 */
9975 #define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
9976 #define DB_UnresetViews    0x0002  /* Some views have defined column names */
9977 #define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
9978
9979 /*
9980 ** The number of different kinds of things that can be limited
9981 ** using the sqlite3_limit() interface.
9982 */
9983 #define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)
9984
9985 /*
9986 ** Lookaside malloc is a set of fixed-size buffers that can be used
9987 ** to satisfy small transient memory allocation requests for objects
9988 ** associated with a particular database connection.  The use of
9989 ** lookaside malloc provides a significant performance enhancement
9990 ** (approx 10%) by avoiding numerous malloc/free requests while parsing
9991 ** SQL statements.
9992 **
9993 ** The Lookaside structure holds configuration information about the
9994 ** lookaside malloc subsystem.  Each available memory allocation in
9995 ** the lookaside subsystem is stored on a linked list of LookasideSlot
9996 ** objects.
9997 **
9998 ** Lookaside allocations are only allowed for objects that are associated
9999 ** with a particular database connection.  Hence, schema information cannot
10000 ** be stored in lookaside because in shared cache mode the schema information
10001 ** is shared by multiple database connections.  Therefore, while parsing
10002 ** schema information, the Lookaside.bEnabled flag is cleared so that
10003 ** lookaside allocations are not used to construct the schema objects.
10004 */
10005 struct Lookaside {
10006   u16 sz;                 /* Size of each buffer in bytes */
10007   u8 bEnabled;            /* False to disable new lookaside allocations */
10008   u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
10009   int nOut;               /* Number of buffers currently checked out */
10010   int mxOut;              /* Highwater mark for nOut */
10011   int anStat[3];          /* 0: hits.  1: size misses.  2: full misses */
10012   LookasideSlot *pFree;   /* List of available buffers */
10013   void *pStart;           /* First byte of available memory space */
10014   void *pEnd;             /* First byte past end of available space */
10015 };
10016 struct LookasideSlot {
10017   LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
10018 };
10019
10020 /*
10021 ** A hash table for function definitions.
10022 **
10023 ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
10024 ** Collisions are on the FuncDef.pHash chain.
10025 */
10026 struct FuncDefHash {
10027   FuncDef *a[23];       /* Hash table for functions */
10028 };
10029
10030 /*
10031 ** Each database connection is an instance of the following structure.
10032 */
10033 struct sqlite3 {
10034   sqlite3_vfs *pVfs;            /* OS Interface */
10035   struct Vdbe *pVdbe;           /* List of active virtual machines */
10036   CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
10037   sqlite3_mutex *mutex;         /* Connection mutex */
10038   Db *aDb;                      /* All backends */
10039   int nDb;                      /* Number of backends currently in use */
10040   int flags;                    /* Miscellaneous flags. See below */
10041   i64 lastRowid;                /* ROWID of most recent insert (see above) */
10042   i64 szMmap;                   /* Default mmap_size setting */
10043   unsigned int openFlags;       /* Flags passed to sqlite3_vfs.xOpen() */
10044   int errCode;                  /* Most recent error code (SQLITE_*) */
10045   int errMask;                  /* & result codes with this before returning */
10046   u16 dbOptFlags;               /* Flags to enable/disable optimizations */
10047   u8 autoCommit;                /* The auto-commit flag. */
10048   u8 temp_store;                /* 1: file 2: memory 0: default */
10049   u8 mallocFailed;              /* True if we have seen a malloc failure */
10050   u8 dfltLockMode;              /* Default locking-mode for attached dbs */
10051   signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
10052   u8 suppressErr;               /* Do not issue error messages if true */
10053   u8 vtabOnConflict;            /* Value to return for s3_vtab_on_conflict() */
10054   u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
10055   int nextPagesize;             /* Pagesize after VACUUM if >0 */
10056   u32 magic;                    /* Magic number for detect library misuse */
10057   int nChange;                  /* Value returned by sqlite3_changes() */
10058   int nTotalChange;             /* Value returned by sqlite3_total_changes() */
10059   int aLimit[SQLITE_N_LIMIT];   /* Limits */
10060   struct sqlite3InitInfo {      /* Information used during initialization */
10061     int newTnum;                /* Rootpage of table being initialized */
10062     u8 iDb;                     /* Which db file is being initialized */
10063     u8 busy;                    /* TRUE if currently initializing */
10064     u8 orphanTrigger;           /* Last statement is orphaned TEMP trigger */
10065   } init;
10066   int activeVdbeCnt;            /* Number of VDBEs currently executing */
10067   int writeVdbeCnt;             /* Number of active VDBEs that are writing */
10068   int vdbeExecCnt;              /* Number of nested calls to VdbeExec() */
10069   int nExtension;               /* Number of loaded extensions */
10070   void **aExtension;            /* Array of shared library handles */
10071   void (*xTrace)(void*,const char*);        /* Trace function */
10072   void *pTraceArg;                          /* Argument to the trace function */
10073   void (*xProfile)(void*,const char*,u64);  /* Profiling function */
10074   void *pProfileArg;                        /* Argument to profile function */
10075   void *pCommitArg;                 /* Argument to xCommitCallback() */   
10076   int (*xCommitCallback)(void*);    /* Invoked at every commit. */
10077   void *pRollbackArg;               /* Argument to xRollbackCallback() */   
10078   void (*xRollbackCallback)(void*); /* Invoked at every commit. */
10079   void *pUpdateArg;
10080   void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
10081 #ifndef SQLITE_OMIT_WAL
10082   int (*xWalCallback)(void *, sqlite3 *, const char *, int);
10083   void *pWalArg;
10084 #endif
10085   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
10086   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
10087   void *pCollNeededArg;
10088   sqlite3_value *pErr;          /* Most recent error message */
10089   char *zErrMsg;                /* Most recent error message (UTF-8 encoded) */
10090   char *zErrMsg16;              /* Most recent error message (UTF-16 encoded) */
10091   union {
10092     volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
10093     double notUsed1;            /* Spacer */
10094   } u1;
10095   Lookaside lookaside;          /* Lookaside malloc configuration */
10096 #ifndef SQLITE_OMIT_AUTHORIZATION
10097   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
10098                                 /* Access authorization function */
10099   void *pAuthArg;               /* 1st argument to the access auth function */
10100 #endif
10101 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
10102   int (*xProgress)(void *);     /* The progress callback */
10103   void *pProgressArg;           /* Argument to the progress callback */
10104   int nProgressOps;             /* Number of opcodes for progress callback */
10105 #endif
10106 #ifndef SQLITE_OMIT_VIRTUALTABLE
10107   int nVTrans;                  /* Allocated size of aVTrans */
10108   Hash aModule;                 /* populated by sqlite3_create_module() */
10109   VtabCtx *pVtabCtx;            /* Context for active vtab connect/create */
10110   VTable **aVTrans;             /* Virtual tables with open transactions */
10111   VTable *pDisconnect;    /* Disconnect these in next sqlite3_prepare() */
10112 #endif
10113   FuncDefHash aFunc;            /* Hash table of connection functions */
10114   Hash aCollSeq;                /* All collating sequences */
10115   BusyHandler busyHandler;      /* Busy callback */
10116   Db aDbStatic[2];              /* Static space for the 2 default backends */
10117   Savepoint *pSavepoint;        /* List of active savepoints */
10118   int busyTimeout;              /* Busy handler timeout, in msec */
10119   int nSavepoint;               /* Number of non-transaction savepoints */
10120   int nStatement;               /* Number of nested statement-transactions  */
10121   i64 nDeferredCons;            /* Net deferred constraints this transaction. */
10122   int *pnBytesFreed;            /* If not NULL, increment this in DbFree() */
10123
10124 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
10125   /* The following variables are all protected by the STATIC_MASTER 
10126   ** mutex, not by sqlite3.mutex. They are used by code in notify.c. 
10127   **
10128   ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
10129   ** unlock so that it can proceed.
10130   **
10131   ** When X.pBlockingConnection==Y, that means that something that X tried
10132   ** tried to do recently failed with an SQLITE_LOCKED error due to locks
10133   ** held by Y.
10134   */
10135   sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
10136   sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */
10137   void *pUnlockArg;                     /* Argument to xUnlockNotify */
10138   void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
10139   sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */
10140 #endif
10141 };
10142
10143 /*
10144 ** A macro to discover the encoding of a database.
10145 */
10146 #define ENC(db) ((db)->aDb[0].pSchema->enc)
10147
10148 /*
10149 ** Possible values for the sqlite3.flags.
10150 */
10151 #define SQLITE_VdbeTrace      0x00000001  /* True to trace VDBE execution */
10152 #define SQLITE_InternChanges  0x00000002  /* Uncommitted Hash table changes */
10153 #define SQLITE_FullColNames   0x00000004  /* Show full column names on SELECT */
10154 #define SQLITE_ShortColNames  0x00000008  /* Show short columns names */
10155 #define SQLITE_CountRows      0x00000010  /* Count rows changed by INSERT, */
10156                                           /*   DELETE, or UPDATE and return */
10157                                           /*   the count using a callback. */
10158 #define SQLITE_NullCallback   0x00000020  /* Invoke the callback once if the */
10159                                           /*   result set is empty */
10160 #define SQLITE_SqlTrace       0x00000040  /* Debug print SQL as it executes */
10161 #define SQLITE_VdbeListing    0x00000080  /* Debug listings of VDBE programs */
10162 #define SQLITE_WriteSchema    0x00000100  /* OK to update SQLITE_MASTER */
10163 #define SQLITE_VdbeAddopTrace 0x00000200  /* Trace sqlite3VdbeAddOp() calls */
10164 #define SQLITE_IgnoreChecks   0x00000400  /* Do not enforce check constraints */
10165 #define SQLITE_ReadUncommitted 0x0000800  /* For shared-cache mode */
10166 #define SQLITE_LegacyFileFmt  0x00001000  /* Create new databases in format 1 */
10167 #define SQLITE_FullFSync      0x00002000  /* Use full fsync on the backend */
10168 #define SQLITE_CkptFullFSync  0x00004000  /* Use full fsync for checkpoint */
10169 #define SQLITE_RecoveryMode   0x00008000  /* Ignore schema errors */
10170 #define SQLITE_ReverseOrder   0x00010000  /* Reverse unordered SELECTs */
10171 #define SQLITE_RecTriggers    0x00020000  /* Enable recursive triggers */
10172 #define SQLITE_ForeignKeys    0x00040000  /* Enforce foreign key constraints  */
10173 #define SQLITE_AutoIndex      0x00080000  /* Enable automatic indexes */
10174 #define SQLITE_PreferBuiltin  0x00100000  /* Preference to built-in funcs */
10175 #define SQLITE_LoadExtension  0x00200000  /* Enable load_extension */
10176 #define SQLITE_EnableTrigger  0x00400000  /* True to enable triggers */
10177
10178 /*
10179 ** Bits of the sqlite3.dbOptFlags field that are used by the
10180 ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
10181 ** selectively disable various optimizations.
10182 */
10183 #define SQLITE_QueryFlattener 0x0001   /* Query flattening */
10184 #define SQLITE_ColumnCache    0x0002   /* Column cache */
10185 #define SQLITE_GroupByOrder   0x0004   /* GROUPBY cover of ORDERBY */
10186 #define SQLITE_FactorOutConst 0x0008   /* Constant factoring */
10187 #define SQLITE_IdxRealAsInt   0x0010   /* Store REAL as INT in indices */
10188 #define SQLITE_DistinctOpt    0x0020   /* DISTINCT using indexes */
10189 #define SQLITE_CoverIdxScan   0x0040   /* Covering index scans */
10190 #define SQLITE_OrderByIdxJoin 0x0080   /* ORDER BY of joins via index */
10191 #define SQLITE_SubqCoroutine  0x0100   /* Evaluate subqueries as coroutines */
10192 #define SQLITE_Transitive     0x0200   /* Transitive constraints */
10193 #define SQLITE_AllOpts        0xffff   /* All optimizations */
10194
10195 /*
10196 ** Macros for testing whether or not optimizations are enabled or disabled.
10197 */
10198 #ifndef SQLITE_OMIT_BUILTIN_TEST
10199 #define OptimizationDisabled(db, mask)  (((db)->dbOptFlags&(mask))!=0)
10200 #define OptimizationEnabled(db, mask)   (((db)->dbOptFlags&(mask))==0)
10201 #else
10202 #define OptimizationDisabled(db, mask)  0
10203 #define OptimizationEnabled(db, mask)   1
10204 #endif
10205
10206 /*
10207 ** Possible values for the sqlite.magic field.
10208 ** The numbers are obtained at random and have no special meaning, other
10209 ** than being distinct from one another.
10210 */
10211 #define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
10212 #define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
10213 #define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
10214 #define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
10215 #define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
10216 #define SQLITE_MAGIC_ZOMBIE   0x64cffc7f  /* Close with last statement close */
10217
10218 /*
10219 ** Each SQL function is defined by an instance of the following
10220 ** structure.  A pointer to this structure is stored in the sqlite.aFunc
10221 ** hash table.  When multiple functions have the same name, the hash table
10222 ** points to a linked list of these structures.
10223 */
10224 struct FuncDef {
10225   i16 nArg;            /* Number of arguments.  -1 means unlimited */
10226   u8 iPrefEnc;         /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
10227   u8 flags;            /* Some combination of SQLITE_FUNC_* */
10228   void *pUserData;     /* User data parameter */
10229   FuncDef *pNext;      /* Next function with same name */
10230   void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
10231   void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
10232   void (*xFinalize)(sqlite3_context*);                /* Aggregate finalizer */
10233   char *zName;         /* SQL name of the function. */
10234   FuncDef *pHash;      /* Next with a different name but the same hash */
10235   FuncDestructor *pDestructor;   /* Reference counted destructor function */
10236 };
10237
10238 /*
10239 ** This structure encapsulates a user-function destructor callback (as
10240 ** configured using create_function_v2()) and a reference counter. When
10241 ** create_function_v2() is called to create a function with a destructor,
10242 ** a single object of this type is allocated. FuncDestructor.nRef is set to 
10243 ** the number of FuncDef objects created (either 1 or 3, depending on whether
10244 ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
10245 ** member of each of the new FuncDef objects is set to point to the allocated
10246 ** FuncDestructor.
10247 **
10248 ** Thereafter, when one of the FuncDef objects is deleted, the reference
10249 ** count on this object is decremented. When it reaches 0, the destructor
10250 ** is invoked and the FuncDestructor structure freed.
10251 */
10252 struct FuncDestructor {
10253   int nRef;
10254   void (*xDestroy)(void *);
10255   void *pUserData;
10256 };
10257
10258 /*
10259 ** Possible values for FuncDef.flags.  Note that the _LENGTH and _TYPEOF
10260 ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG.  There
10261 ** are assert() statements in the code to verify this.
10262 */
10263 #define SQLITE_FUNC_LIKE     0x01 /* Candidate for the LIKE optimization */
10264 #define SQLITE_FUNC_CASE     0x02 /* Case-sensitive LIKE-type function */
10265 #define SQLITE_FUNC_EPHEM    0x04 /* Ephemeral.  Delete with VDBE */
10266 #define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */
10267 #define SQLITE_FUNC_COUNT    0x10 /* Built-in count(*) aggregate */
10268 #define SQLITE_FUNC_COALESCE 0x20 /* Built-in coalesce() or ifnull() function */
10269 #define SQLITE_FUNC_LENGTH   0x40 /* Built-in length() function */
10270 #define SQLITE_FUNC_TYPEOF   0x80 /* Built-in typeof() function */
10271
10272 /*
10273 ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
10274 ** used to create the initializers for the FuncDef structures.
10275 **
10276 **   FUNCTION(zName, nArg, iArg, bNC, xFunc)
10277 **     Used to create a scalar function definition of a function zName 
10278 **     implemented by C function xFunc that accepts nArg arguments. The
10279 **     value passed as iArg is cast to a (void*) and made available
10280 **     as the user-data (sqlite3_user_data()) for the function. If 
10281 **     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
10282 **
10283 **   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
10284 **     Used to create an aggregate function definition implemented by
10285 **     the C functions xStep and xFinal. The first four parameters
10286 **     are interpreted in the same way as the first 4 parameters to
10287 **     FUNCTION().
10288 **
10289 **   LIKEFUNC(zName, nArg, pArg, flags)
10290 **     Used to create a scalar function definition of a function zName 
10291 **     that accepts nArg arguments and is implemented by a call to C 
10292 **     function likeFunc. Argument pArg is cast to a (void *) and made
10293 **     available as the function user-data (sqlite3_user_data()). The
10294 **     FuncDef.flags variable is set to the value passed as the flags
10295 **     parameter.
10296 */
10297 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
10298   {nArg, SQLITE_UTF8, (bNC*SQLITE_FUNC_NEEDCOLL), \
10299    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
10300 #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
10301   {nArg, SQLITE_UTF8, (bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
10302    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
10303 #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
10304   {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
10305    pArg, 0, xFunc, 0, 0, #zName, 0, 0}
10306 #define LIKEFUNC(zName, nArg, arg, flags) \
10307   {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
10308 #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
10309   {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \
10310    SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
10311
10312 /*
10313 ** All current savepoints are stored in a linked list starting at
10314 ** sqlite3.pSavepoint. The first element in the list is the most recently
10315 ** opened savepoint. Savepoints are added to the list by the vdbe
10316 ** OP_Savepoint instruction.
10317 */
10318 struct Savepoint {
10319   char *zName;                        /* Savepoint name (nul-terminated) */
10320   i64 nDeferredCons;                  /* Number of deferred fk violations */
10321   Savepoint *pNext;                   /* Parent savepoint (if any) */
10322 };
10323
10324 /*
10325 ** The following are used as the second parameter to sqlite3Savepoint(),
10326 ** and as the P1 argument to the OP_Savepoint instruction.
10327 */
10328 #define SAVEPOINT_BEGIN      0
10329 #define SAVEPOINT_RELEASE    1
10330 #define SAVEPOINT_ROLLBACK   2
10331
10332
10333 /*
10334 ** Each SQLite module (virtual table definition) is defined by an
10335 ** instance of the following structure, stored in the sqlite3.aModule
10336 ** hash table.
10337 */
10338 struct Module {
10339   const sqlite3_module *pModule;       /* Callback pointers */
10340   const char *zName;                   /* Name passed to create_module() */
10341   void *pAux;                          /* pAux passed to create_module() */
10342   void (*xDestroy)(void *);            /* Module destructor function */
10343 };
10344
10345 /*
10346 ** information about each column of an SQL table is held in an instance
10347 ** of this structure.
10348 */
10349 struct Column {
10350   char *zName;     /* Name of this column */
10351   Expr *pDflt;     /* Default value of this column */
10352   char *zDflt;     /* Original text of the default value */
10353   char *zType;     /* Data type for this column */
10354   char *zColl;     /* Collating sequence.  If NULL, use the default */
10355   u8 notNull;      /* An OE_ code for handling a NOT NULL constraint */
10356   char affinity;   /* One of the SQLITE_AFF_... values */
10357   u16 colFlags;    /* Boolean properties.  See COLFLAG_ defines below */
10358 };
10359
10360 /* Allowed values for Column.colFlags:
10361 */
10362 #define COLFLAG_PRIMKEY  0x0001    /* Column is part of the primary key */
10363 #define COLFLAG_HIDDEN   0x0002    /* A hidden column in a virtual table */
10364
10365 /*
10366 ** A "Collating Sequence" is defined by an instance of the following
10367 ** structure. Conceptually, a collating sequence consists of a name and
10368 ** a comparison routine that defines the order of that sequence.
10369 **
10370 ** If CollSeq.xCmp is NULL, it means that the
10371 ** collating sequence is undefined.  Indices built on an undefined
10372 ** collating sequence may not be read or written.
10373 */
10374 struct CollSeq {
10375   char *zName;          /* Name of the collating sequence, UTF-8 encoded */
10376   u8 enc;               /* Text encoding handled by xCmp() */
10377   void *pUser;          /* First argument to xCmp() */
10378   int (*xCmp)(void*,int, const void*, int, const void*);
10379   void (*xDel)(void*);  /* Destructor for pUser */
10380 };
10381
10382 /*
10383 ** A sort order can be either ASC or DESC.
10384 */
10385 #define SQLITE_SO_ASC       0  /* Sort in ascending order */
10386 #define SQLITE_SO_DESC      1  /* Sort in ascending order */
10387
10388 /*
10389 ** Column affinity types.
10390 **
10391 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
10392 ** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
10393 ** the speed a little by numbering the values consecutively.  
10394 **
10395 ** But rather than start with 0 or 1, we begin with 'a'.  That way,
10396 ** when multiple affinity types are concatenated into a string and
10397 ** used as the P4 operand, they will be more readable.
10398 **
10399 ** Note also that the numeric types are grouped together so that testing
10400 ** for a numeric type is a single comparison.
10401 */
10402 #define SQLITE_AFF_TEXT     'a'
10403 #define SQLITE_AFF_NONE     'b'
10404 #define SQLITE_AFF_NUMERIC  'c'
10405 #define SQLITE_AFF_INTEGER  'd'
10406 #define SQLITE_AFF_REAL     'e'
10407
10408 #define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
10409
10410 /*
10411 ** The SQLITE_AFF_MASK values masks off the significant bits of an
10412 ** affinity value. 
10413 */
10414 #define SQLITE_AFF_MASK     0x67
10415
10416 /*
10417 ** Additional bit values that can be ORed with an affinity without
10418 ** changing the affinity.
10419 */
10420 #define SQLITE_JUMPIFNULL   0x08  /* jumps if either operand is NULL */
10421 #define SQLITE_STOREP2      0x10  /* Store result in reg[P2] rather than jump */
10422 #define SQLITE_NULLEQ       0x80  /* NULL=NULL */
10423
10424 /*
10425 ** An object of this type is created for each virtual table present in
10426 ** the database schema. 
10427 **
10428 ** If the database schema is shared, then there is one instance of this
10429 ** structure for each database connection (sqlite3*) that uses the shared
10430 ** schema. This is because each database connection requires its own unique
10431 ** instance of the sqlite3_vtab* handle used to access the virtual table 
10432 ** implementation. sqlite3_vtab* handles can not be shared between 
10433 ** database connections, even when the rest of the in-memory database 
10434 ** schema is shared, as the implementation often stores the database
10435 ** connection handle passed to it via the xConnect() or xCreate() method
10436 ** during initialization internally. This database connection handle may
10437 ** then be used by the virtual table implementation to access real tables 
10438 ** within the database. So that they appear as part of the callers 
10439 ** transaction, these accesses need to be made via the same database 
10440 ** connection as that used to execute SQL operations on the virtual table.
10441 **
10442 ** All VTable objects that correspond to a single table in a shared
10443 ** database schema are initially stored in a linked-list pointed to by
10444 ** the Table.pVTable member variable of the corresponding Table object.
10445 ** When an sqlite3_prepare() operation is required to access the virtual
10446 ** table, it searches the list for the VTable that corresponds to the
10447 ** database connection doing the preparing so as to use the correct
10448 ** sqlite3_vtab* handle in the compiled query.
10449 **
10450 ** When an in-memory Table object is deleted (for example when the
10451 ** schema is being reloaded for some reason), the VTable objects are not 
10452 ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed 
10453 ** immediately. Instead, they are moved from the Table.pVTable list to
10454 ** another linked list headed by the sqlite3.pDisconnect member of the
10455 ** corresponding sqlite3 structure. They are then deleted/xDisconnected 
10456 ** next time a statement is prepared using said sqlite3*. This is done
10457 ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
10458 ** Refer to comments above function sqlite3VtabUnlockList() for an
10459 ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
10460 ** list without holding the corresponding sqlite3.mutex mutex.
10461 **
10462 ** The memory for objects of this type is always allocated by 
10463 ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as 
10464 ** the first argument.
10465 */
10466 struct VTable {
10467   sqlite3 *db;              /* Database connection associated with this table */
10468   Module *pMod;             /* Pointer to module implementation */
10469   sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
10470   int nRef;                 /* Number of pointers to this structure */
10471   u8 bConstraint;           /* True if constraints are supported */
10472   int iSavepoint;           /* Depth of the SAVEPOINT stack */
10473   VTable *pNext;            /* Next in linked list (see above) */
10474 };
10475
10476 /*
10477 ** Each SQL table is represented in memory by an instance of the
10478 ** following structure.
10479 **
10480 ** Table.zName is the name of the table.  The case of the original
10481 ** CREATE TABLE statement is stored, but case is not significant for
10482 ** comparisons.
10483 **
10484 ** Table.nCol is the number of columns in this table.  Table.aCol is a
10485 ** pointer to an array of Column structures, one for each column.
10486 **
10487 ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
10488 ** the column that is that key.   Otherwise Table.iPKey is negative.  Note
10489 ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
10490 ** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
10491 ** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
10492 ** is generated for each row of the table.  TF_HasPrimaryKey is set if
10493 ** the table has any PRIMARY KEY, INTEGER or otherwise.
10494 **
10495 ** Table.tnum is the page number for the root BTree page of the table in the
10496 ** database file.  If Table.iDb is the index of the database table backend
10497 ** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
10498 ** holds temporary tables and indices.  If TF_Ephemeral is set
10499 ** then the table is stored in a file that is automatically deleted
10500 ** when the VDBE cursor to the table is closed.  In this case Table.tnum 
10501 ** refers VDBE cursor number that holds the table open, not to the root
10502 ** page number.  Transient tables are used to hold the results of a
10503 ** sub-query that appears instead of a real table name in the FROM clause 
10504 ** of a SELECT statement.
10505 */
10506 struct Table {
10507   char *zName;         /* Name of the table or view */
10508   Column *aCol;        /* Information about each column */
10509   Index *pIndex;       /* List of SQL indexes on this table. */
10510   Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
10511   FKey *pFKey;         /* Linked list of all foreign keys in this table */
10512   char *zColAff;       /* String defining the affinity of each column */
10513 #ifndef SQLITE_OMIT_CHECK
10514   ExprList *pCheck;    /* All CHECK constraints */
10515 #endif
10516   tRowcnt nRowEst;     /* Estimated rows in table - from sqlite_stat1 table */
10517   int tnum;            /* Root BTree node for this table (see note above) */
10518   i16 iPKey;           /* If not negative, use aCol[iPKey] as the primary key */
10519   i16 nCol;            /* Number of columns in this table */
10520   u16 nRef;            /* Number of pointers to this Table */
10521   u8 tabFlags;         /* Mask of TF_* values */
10522   u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
10523 #ifndef SQLITE_OMIT_ALTERTABLE
10524   int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
10525 #endif
10526 #ifndef SQLITE_OMIT_VIRTUALTABLE
10527   int nModuleArg;      /* Number of arguments to the module */
10528   char **azModuleArg;  /* Text of all module args. [0] is module name */
10529   VTable *pVTable;     /* List of VTable objects. */
10530 #endif
10531   Trigger *pTrigger;   /* List of triggers stored in pSchema */
10532   Schema *pSchema;     /* Schema that contains this table */
10533   Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
10534 };
10535
10536 /*
10537 ** Allowed values for Tabe.tabFlags.
10538 */
10539 #define TF_Readonly        0x01    /* Read-only system table */
10540 #define TF_Ephemeral       0x02    /* An ephemeral table */
10541 #define TF_HasPrimaryKey   0x04    /* Table has a primary key */
10542 #define TF_Autoincrement   0x08    /* Integer primary key is autoincrement */
10543 #define TF_Virtual         0x10    /* Is a virtual table */
10544
10545
10546 /*
10547 ** Test to see whether or not a table is a virtual table.  This is
10548 ** done as a macro so that it will be optimized out when virtual
10549 ** table support is omitted from the build.
10550 */
10551 #ifndef SQLITE_OMIT_VIRTUALTABLE
10552 #  define IsVirtual(X)      (((X)->tabFlags & TF_Virtual)!=0)
10553 #  define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
10554 #else
10555 #  define IsVirtual(X)      0
10556 #  define IsHiddenColumn(X) 0
10557 #endif
10558
10559 /*
10560 ** Each foreign key constraint is an instance of the following structure.
10561 **
10562 ** A foreign key is associated with two tables.  The "from" table is
10563 ** the table that contains the REFERENCES clause that creates the foreign
10564 ** key.  The "to" table is the table that is named in the REFERENCES clause.
10565 ** Consider this example:
10566 **
10567 **     CREATE TABLE ex1(
10568 **       a INTEGER PRIMARY KEY,
10569 **       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
10570 **     );
10571 **
10572 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
10573 **
10574 ** Each REFERENCES clause generates an instance of the following structure
10575 ** which is attached to the from-table.  The to-table need not exist when
10576 ** the from-table is created.  The existence of the to-table is not checked.
10577 */
10578 struct FKey {
10579   Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
10580   FKey *pNextFrom;  /* Next foreign key in pFrom */
10581   char *zTo;        /* Name of table that the key points to (aka: Parent) */
10582   FKey *pNextTo;    /* Next foreign key on table named zTo */
10583   FKey *pPrevTo;    /* Previous foreign key on table named zTo */
10584   int nCol;         /* Number of columns in this key */
10585   /* EV: R-30323-21917 */
10586   u8 isDeferred;    /* True if constraint checking is deferred till COMMIT */
10587   u8 aAction[2];          /* ON DELETE and ON UPDATE actions, respectively */
10588   Trigger *apTrigger[2];  /* Triggers for aAction[] actions */
10589   struct sColMap {  /* Mapping of columns in pFrom to columns in zTo */
10590     int iFrom;         /* Index of column in pFrom */
10591     char *zCol;        /* Name of column in zTo.  If 0 use PRIMARY KEY */
10592   } aCol[1];        /* One entry for each of nCol column s */
10593 };
10594
10595 /*
10596 ** SQLite supports many different ways to resolve a constraint
10597 ** error.  ROLLBACK processing means that a constraint violation
10598 ** causes the operation in process to fail and for the current transaction
10599 ** to be rolled back.  ABORT processing means the operation in process
10600 ** fails and any prior changes from that one operation are backed out,
10601 ** but the transaction is not rolled back.  FAIL processing means that
10602 ** the operation in progress stops and returns an error code.  But prior
10603 ** changes due to the same operation are not backed out and no rollback
10604 ** occurs.  IGNORE means that the particular row that caused the constraint
10605 ** error is not inserted or updated.  Processing continues and no error
10606 ** is returned.  REPLACE means that preexisting database rows that caused
10607 ** a UNIQUE constraint violation are removed so that the new insert or
10608 ** update can proceed.  Processing continues and no error is reported.
10609 **
10610 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
10611 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
10612 ** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
10613 ** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
10614 ** referenced table row is propagated into the row that holds the
10615 ** foreign key.
10616 ** 
10617 ** The following symbolic values are used to record which type
10618 ** of action to take.
10619 */
10620 #define OE_None     0   /* There is no constraint to check */
10621 #define OE_Rollback 1   /* Fail the operation and rollback the transaction */
10622 #define OE_Abort    2   /* Back out changes but do no rollback transaction */
10623 #define OE_Fail     3   /* Stop the operation but leave all prior changes */
10624 #define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
10625 #define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
10626
10627 #define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
10628 #define OE_SetNull  7   /* Set the foreign key value to NULL */
10629 #define OE_SetDflt  8   /* Set the foreign key value to its default */
10630 #define OE_Cascade  9   /* Cascade the changes */
10631
10632 #define OE_Default  99  /* Do whatever the default action is */
10633
10634
10635 /*
10636 ** An instance of the following structure is passed as the first
10637 ** argument to sqlite3VdbeKeyCompare and is used to control the 
10638 ** comparison of the two index keys.
10639 */
10640 struct KeyInfo {
10641   sqlite3 *db;        /* The database connection */
10642   u8 enc;             /* Text encoding - one of the SQLITE_UTF* values */
10643   u16 nField;         /* Number of entries in aColl[] */
10644   u8 *aSortOrder;     /* Sort order for each column.  May be NULL */
10645   CollSeq *aColl[1];  /* Collating sequence for each term of the key */
10646 };
10647
10648 /*
10649 ** An instance of the following structure holds information about a
10650 ** single index record that has already been parsed out into individual
10651 ** values.
10652 **
10653 ** A record is an object that contains one or more fields of data.
10654 ** Records are used to store the content of a table row and to store
10655 ** the key of an index.  A blob encoding of a record is created by
10656 ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
10657 ** OP_Column opcode.
10658 **
10659 ** This structure holds a record that has already been disassembled
10660 ** into its constituent fields.
10661 */
10662 struct UnpackedRecord {
10663   KeyInfo *pKeyInfo;  /* Collation and sort-order information */
10664   u16 nField;         /* Number of entries in apMem[] */
10665   u8 flags;           /* Boolean settings.  UNPACKED_... below */
10666   i64 rowid;          /* Used by UNPACKED_PREFIX_SEARCH */
10667   Mem *aMem;          /* Values */
10668 };
10669
10670 /*
10671 ** Allowed values of UnpackedRecord.flags
10672 */
10673 #define UNPACKED_INCRKEY       0x01  /* Make this key an epsilon larger */
10674 #define UNPACKED_PREFIX_MATCH  0x02  /* A prefix match is considered OK */
10675 #define UNPACKED_PREFIX_SEARCH 0x04  /* Ignore final (rowid) field */
10676
10677 /*
10678 ** Each SQL index is represented in memory by an
10679 ** instance of the following structure.
10680 **
10681 ** The columns of the table that are to be indexed are described
10682 ** by the aiColumn[] field of this structure.  For example, suppose
10683 ** we have the following table and index:
10684 **
10685 **     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
10686 **     CREATE INDEX Ex2 ON Ex1(c3,c1);
10687 **
10688 ** In the Table structure describing Ex1, nCol==3 because there are
10689 ** three columns in the table.  In the Index structure describing
10690 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
10691 ** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the 
10692 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
10693 ** The second column to be indexed (c1) has an index of 0 in
10694 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
10695 **
10696 ** The Index.onError field determines whether or not the indexed columns
10697 ** must be unique and what to do if they are not.  When Index.onError=OE_None,
10698 ** it means this is not a unique index.  Otherwise it is a unique index
10699 ** and the value of Index.onError indicate the which conflict resolution 
10700 ** algorithm to employ whenever an attempt is made to insert a non-unique
10701 ** element.
10702 */
10703 struct Index {
10704   char *zName;             /* Name of this index */
10705   int *aiColumn;           /* Which columns are used by this index.  1st is 0 */
10706   tRowcnt *aiRowEst;       /* From ANALYZE: Est. rows selected by each column */
10707   Table *pTable;           /* The SQL table being indexed */
10708   char *zColAff;           /* String defining the affinity of each column */
10709   Index *pNext;            /* The next index associated with the same table */
10710   Schema *pSchema;         /* Schema containing this index */
10711   u8 *aSortOrder;          /* for each column: True==DESC, False==ASC */
10712   char **azColl;           /* Array of collation sequence names for index */
10713   int tnum;                /* DB Page containing root of this index */
10714   u16 nColumn;             /* Number of columns in table used by this index */
10715   u8 onError;              /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
10716   unsigned autoIndex:2;    /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
10717   unsigned bUnordered:1;   /* Use this index for == or IN queries only */
10718 #ifdef SQLITE_ENABLE_STAT3
10719   int nSample;             /* Number of elements in aSample[] */
10720   tRowcnt avgEq;           /* Average nEq value for key values not in aSample */
10721   IndexSample *aSample;    /* Samples of the left-most key */
10722 #endif
10723 };
10724
10725 /*
10726 ** Each sample stored in the sqlite_stat3 table is represented in memory 
10727 ** using a structure of this type.  See documentation at the top of the
10728 ** analyze.c source file for additional information.
10729 */
10730 struct IndexSample {
10731   union {
10732     char *z;        /* Value if eType is SQLITE_TEXT or SQLITE_BLOB */
10733     double r;       /* Value if eType is SQLITE_FLOAT */
10734     i64 i;          /* Value if eType is SQLITE_INTEGER */
10735   } u;
10736   u8 eType;         /* SQLITE_NULL, SQLITE_INTEGER ... etc. */
10737   int nByte;        /* Size in byte of text or blob. */
10738   tRowcnt nEq;      /* Est. number of rows where the key equals this sample */
10739   tRowcnt nLt;      /* Est. number of rows where key is less than this sample */
10740   tRowcnt nDLt;     /* Est. number of distinct keys less than this sample */
10741 };
10742
10743 /*
10744 ** Each token coming out of the lexer is an instance of
10745 ** this structure.  Tokens are also used as part of an expression.
10746 **
10747 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
10748 ** may contain random values.  Do not make any assumptions about Token.dyn
10749 ** and Token.n when Token.z==0.
10750 */
10751 struct Token {
10752   const char *z;     /* Text of the token.  Not NULL-terminated! */
10753   unsigned int n;    /* Number of characters in this token */
10754 };
10755
10756 /*
10757 ** An instance of this structure contains information needed to generate
10758 ** code for a SELECT that contains aggregate functions.
10759 **
10760 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
10761 ** pointer to this structure.  The Expr.iColumn field is the index in
10762 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
10763 ** code for that node.
10764 **
10765 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
10766 ** original Select structure that describes the SELECT statement.  These
10767 ** fields do not need to be freed when deallocating the AggInfo structure.
10768 */
10769 struct AggInfo {
10770   u8 directMode;          /* Direct rendering mode means take data directly
10771                           ** from source tables rather than from accumulators */
10772   u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
10773                           ** than the source table */
10774   int sortingIdx;         /* Cursor number of the sorting index */
10775   int sortingIdxPTab;     /* Cursor number of pseudo-table */
10776   int nSortingColumn;     /* Number of columns in the sorting index */
10777   ExprList *pGroupBy;     /* The group by clause */
10778   struct AggInfo_col {    /* For each column used in source tables */
10779     Table *pTab;             /* Source table */
10780     int iTable;              /* Cursor number of the source table */
10781     int iColumn;             /* Column number within the source table */
10782     int iSorterColumn;       /* Column number in the sorting index */
10783     int iMem;                /* Memory location that acts as accumulator */
10784     Expr *pExpr;             /* The original expression */
10785   } *aCol;
10786   int nColumn;            /* Number of used entries in aCol[] */
10787   int nAccumulator;       /* Number of columns that show through to the output.
10788                           ** Additional columns are used only as parameters to
10789                           ** aggregate functions */
10790   struct AggInfo_func {   /* For each aggregate function */
10791     Expr *pExpr;             /* Expression encoding the function */
10792     FuncDef *pFunc;          /* The aggregate function implementation */
10793     int iMem;                /* Memory location that acts as accumulator */
10794     int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
10795   } *aFunc;
10796   int nFunc;              /* Number of entries in aFunc[] */
10797 };
10798
10799 /*
10800 ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
10801 ** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater
10802 ** than 32767 we have to make it 32-bit.  16-bit is preferred because
10803 ** it uses less memory in the Expr object, which is a big memory user
10804 ** in systems with lots of prepared statements.  And few applications
10805 ** need more than about 10 or 20 variables.  But some extreme users want
10806 ** to have prepared statements with over 32767 variables, and for them
10807 ** the option is available (at compile-time).
10808 */
10809 #if SQLITE_MAX_VARIABLE_NUMBER<=32767
10810 typedef i16 ynVar;
10811 #else
10812 typedef int ynVar;
10813 #endif
10814
10815 /*
10816 ** Each node of an expression in the parse tree is an instance
10817 ** of this structure.
10818 **
10819 ** Expr.op is the opcode. The integer parser token codes are reused
10820 ** as opcodes here. For example, the parser defines TK_GE to be an integer
10821 ** code representing the ">=" operator. This same integer code is reused
10822 ** to represent the greater-than-or-equal-to operator in the expression
10823 ** tree.
10824 **
10825 ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB, 
10826 ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
10827 ** the expression is a variable (TK_VARIABLE), then Expr.token contains the 
10828 ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
10829 ** then Expr.token contains the name of the function.
10830 **
10831 ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
10832 ** binary operator. Either or both may be NULL.
10833 **
10834 ** Expr.x.pList is a list of arguments if the expression is an SQL function,
10835 ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
10836 ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
10837 ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
10838 ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is 
10839 ** valid.
10840 **
10841 ** An expression of the form ID or ID.ID refers to a column in a table.
10842 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
10843 ** the integer cursor number of a VDBE cursor pointing to that table and
10844 ** Expr.iColumn is the column number for the specific column.  If the
10845 ** expression is used as a result in an aggregate SELECT, then the
10846 ** value is also stored in the Expr.iAgg column in the aggregate so that
10847 ** it can be accessed after all aggregates are computed.
10848 **
10849 ** If the expression is an unbound variable marker (a question mark 
10850 ** character '?' in the original SQL) then the Expr.iTable holds the index 
10851 ** number for that variable.
10852 **
10853 ** If the expression is a subquery then Expr.iColumn holds an integer
10854 ** register number containing the result of the subquery.  If the
10855 ** subquery gives a constant result, then iTable is -1.  If the subquery
10856 ** gives a different answer at different times during statement processing
10857 ** then iTable is the address of a subroutine that computes the subquery.
10858 **
10859 ** If the Expr is of type OP_Column, and the table it is selecting from
10860 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
10861 ** corresponding table definition.
10862 **
10863 ** ALLOCATION NOTES:
10864 **
10865 ** Expr objects can use a lot of memory space in database schema.  To
10866 ** help reduce memory requirements, sometimes an Expr object will be
10867 ** truncated.  And to reduce the number of memory allocations, sometimes
10868 ** two or more Expr objects will be stored in a single memory allocation,
10869 ** together with Expr.zToken strings.
10870 **
10871 ** If the EP_Reduced and EP_TokenOnly flags are set when
10872 ** an Expr object is truncated.  When EP_Reduced is set, then all
10873 ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
10874 ** are contained within the same memory allocation.  Note, however, that
10875 ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
10876 ** allocated, regardless of whether or not EP_Reduced is set.
10877 */
10878 struct Expr {
10879   u8 op;                 /* Operation performed by this node */
10880   char affinity;         /* The affinity of the column or 0 if not a column */
10881   u16 flags;             /* Various flags.  EP_* See below */
10882   union {
10883     char *zToken;          /* Token value. Zero terminated and dequoted */
10884     int iValue;            /* Non-negative integer value if EP_IntValue */
10885   } u;
10886
10887   /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
10888   ** space is allocated for the fields below this point. An attempt to
10889   ** access them will result in a segfault or malfunction. 
10890   *********************************************************************/
10891
10892   Expr *pLeft;           /* Left subnode */
10893   Expr *pRight;          /* Right subnode */
10894   union {
10895     ExprList *pList;     /* Function arguments or in "<expr> IN (<expr-list)" */
10896     Select *pSelect;     /* Used for sub-selects and "<expr> IN (<select>)" */
10897   } x;
10898
10899   /* If the EP_Reduced flag is set in the Expr.flags mask, then no
10900   ** space is allocated for the fields below this point. An attempt to
10901   ** access them will result in a segfault or malfunction.
10902   *********************************************************************/
10903
10904 #if SQLITE_MAX_EXPR_DEPTH>0
10905   int nHeight;           /* Height of the tree headed by this node */
10906 #endif
10907   int iTable;            /* TK_COLUMN: cursor number of table holding column
10908                          ** TK_REGISTER: register number
10909                          ** TK_TRIGGER: 1 -> new, 0 -> old */
10910   ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
10911                          ** TK_VARIABLE: variable number (always >= 1). */
10912   i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
10913   i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
10914   u8 flags2;             /* Second set of flags.  EP2_... */
10915   u8 op2;                /* TK_REGISTER: original value of Expr.op
10916                          ** TK_COLUMN: the value of p5 for OP_Column
10917                          ** TK_AGG_FUNCTION: nesting depth */
10918   AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
10919   Table *pTab;           /* Table for TK_COLUMN expressions. */
10920 };
10921
10922 /*
10923 ** The following are the meanings of bits in the Expr.flags field.
10924 */
10925 #define EP_FromJoin   0x0001  /* Originated in ON or USING clause of a join */
10926 #define EP_Agg        0x0002  /* Contains one or more aggregate functions */
10927 #define EP_Resolved   0x0004  /* IDs have been resolved to COLUMNs */
10928 #define EP_Error      0x0008  /* Expression contains one or more errors */
10929 #define EP_Distinct   0x0010  /* Aggregate function with DISTINCT keyword */
10930 #define EP_VarSelect  0x0020  /* pSelect is correlated, not constant */
10931 #define EP_DblQuoted  0x0040  /* token.z was originally in "..." */
10932 #define EP_InfixFunc  0x0080  /* True for an infix function: LIKE, GLOB, etc */
10933 #define EP_Collate    0x0100  /* Tree contains a TK_COLLATE opeartor */
10934 #define EP_FixedDest  0x0200  /* Result needed in a specific register */
10935 #define EP_IntValue   0x0400  /* Integer value contained in u.iValue */
10936 #define EP_xIsSelect  0x0800  /* x.pSelect is valid (otherwise x.pList is) */
10937 #define EP_Hint       0x1000  /* Not used */
10938 #define EP_Reduced    0x2000  /* Expr struct is EXPR_REDUCEDSIZE bytes only */
10939 #define EP_TokenOnly  0x4000  /* Expr struct is EXPR_TOKENONLYSIZE bytes only */
10940 #define EP_Static     0x8000  /* Held in memory not obtained from malloc() */
10941
10942 /*
10943 ** The following are the meanings of bits in the Expr.flags2 field.
10944 */
10945 #define EP2_MallocedToken  0x0001  /* Need to sqlite3DbFree() Expr.zToken */
10946 #define EP2_Irreducible    0x0002  /* Cannot EXPRDUP_REDUCE this Expr */
10947
10948 /*
10949 ** The pseudo-routine sqlite3ExprSetIrreducible sets the EP2_Irreducible
10950 ** flag on an expression structure.  This flag is used for VV&A only.  The
10951 ** routine is implemented as a macro that only works when in debugging mode,
10952 ** so as not to burden production code.
10953 */
10954 #ifdef SQLITE_DEBUG
10955 # define ExprSetIrreducible(X)  (X)->flags2 |= EP2_Irreducible
10956 #else
10957 # define ExprSetIrreducible(X)
10958 #endif
10959
10960 /*
10961 ** These macros can be used to test, set, or clear bits in the 
10962 ** Expr.flags field.
10963 */
10964 #define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))
10965 #define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)
10966 #define ExprSetProperty(E,P)     (E)->flags|=(P)
10967 #define ExprClearProperty(E,P)   (E)->flags&=~(P)
10968
10969 /*
10970 ** Macros to determine the number of bytes required by a normal Expr 
10971 ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags 
10972 ** and an Expr struct with the EP_TokenOnly flag set.
10973 */
10974 #define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
10975 #define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
10976 #define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
10977
10978 /*
10979 ** Flags passed to the sqlite3ExprDup() function. See the header comment 
10980 ** above sqlite3ExprDup() for details.
10981 */
10982 #define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
10983
10984 /*
10985 ** A list of expressions.  Each expression may optionally have a
10986 ** name.  An expr/name combination can be used in several ways, such
10987 ** as the list of "expr AS ID" fields following a "SELECT" or in the
10988 ** list of "ID = expr" items in an UPDATE.  A list of expressions can
10989 ** also be used as the argument to a function, in which case the a.zName
10990 ** field is not used.
10991 **
10992 ** By default the Expr.zSpan field holds a human-readable description of
10993 ** the expression that is used in the generation of error messages and
10994 ** column labels.  In this case, Expr.zSpan is typically the text of a
10995 ** column expression as it exists in a SELECT statement.  However, if
10996 ** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
10997 ** of the result column in the form: DATABASE.TABLE.COLUMN.  This later
10998 ** form is used for name resolution with nested FROM clauses.
10999 */
11000 struct ExprList {
11001   int nExpr;             /* Number of expressions on the list */
11002   int iECursor;          /* VDBE Cursor associated with this ExprList */
11003   struct ExprList_item { /* For each expression in the list */
11004     Expr *pExpr;            /* The list of expressions */
11005     char *zName;            /* Token associated with this expression */
11006     char *zSpan;            /* Original text of the expression */
11007     u8 sortOrder;           /* 1 for DESC or 0 for ASC */
11008     unsigned done :1;       /* A flag to indicate when processing is finished */
11009     unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
11010     u16 iOrderByCol;        /* For ORDER BY, column number in result set */
11011     u16 iAlias;             /* Index into Parse.aAlias[] for zName */
11012   } *a;                  /* Alloc a power of two greater or equal to nExpr */
11013 };
11014
11015 /*
11016 ** An instance of this structure is used by the parser to record both
11017 ** the parse tree for an expression and the span of input text for an
11018 ** expression.
11019 */
11020 struct ExprSpan {
11021   Expr *pExpr;          /* The expression parse tree */
11022   const char *zStart;   /* First character of input text */
11023   const char *zEnd;     /* One character past the end of input text */
11024 };
11025
11026 /*
11027 ** An instance of this structure can hold a simple list of identifiers,
11028 ** such as the list "a,b,c" in the following statements:
11029 **
11030 **      INSERT INTO t(a,b,c) VALUES ...;
11031 **      CREATE INDEX idx ON t(a,b,c);
11032 **      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
11033 **
11034 ** The IdList.a.idx field is used when the IdList represents the list of
11035 ** column names after a table name in an INSERT statement.  In the statement
11036 **
11037 **     INSERT INTO t(a,b,c) ...
11038 **
11039 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
11040 */
11041 struct IdList {
11042   struct IdList_item {
11043     char *zName;      /* Name of the identifier */
11044     int idx;          /* Index in some Table.aCol[] of a column named zName */
11045   } *a;
11046   int nId;         /* Number of identifiers on the list */
11047 };
11048
11049 /*
11050 ** The bitmask datatype defined below is used for various optimizations.
11051 **
11052 ** Changing this from a 64-bit to a 32-bit type limits the number of
11053 ** tables in a join to 32 instead of 64.  But it also reduces the size
11054 ** of the library by 738 bytes on ix86.
11055 */
11056 typedef u64 Bitmask;
11057
11058 /*
11059 ** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
11060 */
11061 #define BMS  ((int)(sizeof(Bitmask)*8))
11062
11063 /*
11064 ** The following structure describes the FROM clause of a SELECT statement.
11065 ** Each table or subquery in the FROM clause is a separate element of
11066 ** the SrcList.a[] array.
11067 **
11068 ** With the addition of multiple database support, the following structure
11069 ** can also be used to describe a particular table such as the table that
11070 ** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
11071 ** such a table must be a simple name: ID.  But in SQLite, the table can
11072 ** now be identified by a database name, a dot, then the table name: ID.ID.
11073 **
11074 ** The jointype starts out showing the join type between the current table
11075 ** and the next table on the list.  The parser builds the list this way.
11076 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
11077 ** jointype expresses the join between the table and the previous table.
11078 **
11079 ** In the colUsed field, the high-order bit (bit 63) is set if the table
11080 ** contains more than 63 columns and the 64-th or later column is used.
11081 */
11082 struct SrcList {
11083   i16 nSrc;        /* Number of tables or subqueries in the FROM clause */
11084   i16 nAlloc;      /* Number of entries allocated in a[] below */
11085   struct SrcList_item {
11086     Schema *pSchema;  /* Schema to which this item is fixed */
11087     char *zDatabase;  /* Name of database holding this table */
11088     char *zName;      /* Name of the table */
11089     char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
11090     Table *pTab;      /* An SQL table corresponding to zName */
11091     Select *pSelect;  /* A SELECT statement used in place of a table name */
11092     int addrFillSub;  /* Address of subroutine to manifest a subquery */
11093     int regReturn;    /* Register holding return address of addrFillSub */
11094     u8 jointype;      /* Type of join between this able and the previous */
11095     unsigned notIndexed :1;    /* True if there is a NOT INDEXED clause */
11096     unsigned isCorrelated :1;  /* True if sub-query is correlated */
11097     unsigned viaCoroutine :1;  /* Implemented as a co-routine */
11098 #ifndef SQLITE_OMIT_EXPLAIN
11099     u8 iSelectId;     /* If pSelect!=0, the id of the sub-select in EQP */
11100 #endif
11101     int iCursor;      /* The VDBE cursor number used to access this table */
11102     Expr *pOn;        /* The ON clause of a join */
11103     IdList *pUsing;   /* The USING clause of a join */
11104     Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
11105     char *zIndex;     /* Identifier from "INDEXED BY <zIndex>" clause */
11106     Index *pIndex;    /* Index structure corresponding to zIndex, if any */
11107   } a[1];             /* One entry for each identifier on the list */
11108 };
11109
11110 /*
11111 ** Permitted values of the SrcList.a.jointype field
11112 */
11113 #define JT_INNER     0x0001    /* Any kind of inner or cross join */
11114 #define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
11115 #define JT_NATURAL   0x0004    /* True for a "natural" join */
11116 #define JT_LEFT      0x0008    /* Left outer join */
11117 #define JT_RIGHT     0x0010    /* Right outer join */
11118 #define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
11119 #define JT_ERROR     0x0040    /* unknown or unsupported join type */
11120
11121
11122 /*
11123 ** A WherePlan object holds information that describes a lookup
11124 ** strategy.
11125 **
11126 ** This object is intended to be opaque outside of the where.c module.
11127 ** It is included here only so that that compiler will know how big it
11128 ** is.  None of the fields in this object should be used outside of
11129 ** the where.c module.
11130 **
11131 ** Within the union, pIdx is only used when wsFlags&WHERE_INDEXED is true.
11132 ** pTerm is only used when wsFlags&WHERE_MULTI_OR is true.  And pVtabIdx
11133 ** is only used when wsFlags&WHERE_VIRTUALTABLE is true.  It is never the
11134 ** case that more than one of these conditions is true.
11135 */
11136 struct WherePlan {
11137   u32 wsFlags;                   /* WHERE_* flags that describe the strategy */
11138   u16 nEq;                       /* Number of == constraints */
11139   u16 nOBSat;                    /* Number of ORDER BY terms satisfied */
11140   double nRow;                   /* Estimated number of rows (for EQP) */
11141   union {
11142     Index *pIdx;                   /* Index when WHERE_INDEXED is true */
11143     struct WhereTerm *pTerm;       /* WHERE clause term for OR-search */
11144     sqlite3_index_info *pVtabIdx;  /* Virtual table index to use */
11145   } u;
11146 };
11147
11148 /*
11149 ** For each nested loop in a WHERE clause implementation, the WhereInfo
11150 ** structure contains a single instance of this structure.  This structure
11151 ** is intended to be private to the where.c module and should not be
11152 ** access or modified by other modules.
11153 **
11154 ** The pIdxInfo field is used to help pick the best index on a
11155 ** virtual table.  The pIdxInfo pointer contains indexing
11156 ** information for the i-th table in the FROM clause before reordering.
11157 ** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
11158 ** All other information in the i-th WhereLevel object for the i-th table
11159 ** after FROM clause ordering.
11160 */
11161 struct WhereLevel {
11162   WherePlan plan;       /* query plan for this element of the FROM clause */
11163   int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
11164   int iTabCur;          /* The VDBE cursor used to access the table */
11165   int iIdxCur;          /* The VDBE cursor used to access pIdx */
11166   int addrBrk;          /* Jump here to break out of the loop */
11167   int addrNxt;          /* Jump here to start the next IN combination */
11168   int addrCont;         /* Jump here to continue with the next loop cycle */
11169   int addrFirst;        /* First instruction of interior of the loop */
11170   u8 iFrom;             /* Which entry in the FROM clause */
11171   u8 op, p5;            /* Opcode and P5 of the opcode that ends the loop */
11172   int p1, p2;           /* Operands of the opcode used to ends the loop */
11173   union {               /* Information that depends on plan.wsFlags */
11174     struct {
11175       int nIn;              /* Number of entries in aInLoop[] */
11176       struct InLoop {
11177         int iCur;              /* The VDBE cursor used by this IN operator */
11178         int addrInTop;         /* Top of the IN loop */
11179         u8 eEndLoopOp;         /* IN Loop terminator. OP_Next or OP_Prev */
11180       } *aInLoop;           /* Information about each nested IN operator */
11181     } in;                 /* Used when plan.wsFlags&WHERE_IN_ABLE */
11182     Index *pCovidx;       /* Possible covering index for WHERE_MULTI_OR */
11183   } u;
11184   double rOptCost;      /* "Optimal" cost for this level */
11185
11186   /* The following field is really not part of the current level.  But
11187   ** we need a place to cache virtual table index information for each
11188   ** virtual table in the FROM clause and the WhereLevel structure is
11189   ** a convenient place since there is one WhereLevel for each FROM clause
11190   ** element.
11191   */
11192   sqlite3_index_info *pIdxInfo;  /* Index info for n-th source table */
11193 };
11194
11195 /*
11196 ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
11197 ** and the WhereInfo.wctrlFlags member.
11198 */
11199 #define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
11200 #define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
11201 #define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
11202 #define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
11203 #define WHERE_DUPLICATES_OK    0x0008 /* Ok to return a row more than once */
11204 #define WHERE_OMIT_OPEN_CLOSE  0x0010 /* Table cursors are already open */
11205 #define WHERE_FORCE_TABLE      0x0020 /* Do not use an index-only search */
11206 #define WHERE_ONETABLE_ONLY    0x0040 /* Only code the 1st table in pTabList */
11207 #define WHERE_AND_ONLY         0x0080 /* Don't use indices for OR terms */
11208
11209 /*
11210 ** The WHERE clause processing routine has two halves.  The
11211 ** first part does the start of the WHERE loop and the second
11212 ** half does the tail of the WHERE loop.  An instance of
11213 ** this structure is returned by the first half and passed
11214 ** into the second half to give some continuity.
11215 */
11216 struct WhereInfo {
11217   Parse *pParse;            /* Parsing and code generating context */
11218   SrcList *pTabList;        /* List of tables in the join */
11219   u16 nOBSat;               /* Number of ORDER BY terms satisfied by indices */
11220   u16 wctrlFlags;           /* Flags originally passed to sqlite3WhereBegin() */
11221   u8 okOnePass;             /* Ok to use one-pass algorithm for UPDATE/DELETE */
11222   u8 untestedTerms;         /* Not all WHERE terms resolved by outer loop */
11223   u8 eDistinct;             /* One of the WHERE_DISTINCT_* values below */
11224   int iTop;                 /* The very beginning of the WHERE loop */
11225   int iContinue;            /* Jump here to continue with next record */
11226   int iBreak;               /* Jump here to break out of the loop */
11227   int nLevel;               /* Number of nested loop */
11228   struct WhereClause *pWC;  /* Decomposition of the WHERE clause */
11229   double savedNQueryLoop;   /* pParse->nQueryLoop outside the WHERE loop */
11230   double nRowOut;           /* Estimated number of output rows */
11231   WhereLevel a[1];          /* Information about each nest loop in WHERE */
11232 };
11233
11234 /* Allowed values for WhereInfo.eDistinct and DistinctCtx.eTnctType */
11235 #define WHERE_DISTINCT_NOOP      0  /* DISTINCT keyword not used */
11236 #define WHERE_DISTINCT_UNIQUE    1  /* No duplicates */
11237 #define WHERE_DISTINCT_ORDERED   2  /* All duplicates are adjacent */
11238 #define WHERE_DISTINCT_UNORDERED 3  /* Duplicates are scattered */
11239
11240 /*
11241 ** A NameContext defines a context in which to resolve table and column
11242 ** names.  The context consists of a list of tables (the pSrcList) field and
11243 ** a list of named expression (pEList).  The named expression list may
11244 ** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
11245 ** to the table being operated on by INSERT, UPDATE, or DELETE.  The
11246 ** pEList corresponds to the result set of a SELECT and is NULL for
11247 ** other statements.
11248 **
11249 ** NameContexts can be nested.  When resolving names, the inner-most 
11250 ** context is searched first.  If no match is found, the next outer
11251 ** context is checked.  If there is still no match, the next context
11252 ** is checked.  This process continues until either a match is found
11253 ** or all contexts are check.  When a match is found, the nRef member of
11254 ** the context containing the match is incremented. 
11255 **
11256 ** Each subquery gets a new NameContext.  The pNext field points to the
11257 ** NameContext in the parent query.  Thus the process of scanning the
11258 ** NameContext list corresponds to searching through successively outer
11259 ** subqueries looking for a match.
11260 */
11261 struct NameContext {
11262   Parse *pParse;       /* The parser */
11263   SrcList *pSrcList;   /* One or more tables used to resolve names */
11264   ExprList *pEList;    /* Optional list of named expressions */
11265   AggInfo *pAggInfo;   /* Information about aggregates at this level */
11266   NameContext *pNext;  /* Next outer name context.  NULL for outermost */
11267   int nRef;            /* Number of names resolved by this context */
11268   int nErr;            /* Number of errors encountered while resolving names */
11269   u8 ncFlags;          /* Zero or more NC_* flags defined below */
11270 };
11271
11272 /*
11273 ** Allowed values for the NameContext, ncFlags field.
11274 */
11275 #define NC_AllowAgg  0x01    /* Aggregate functions are allowed here */
11276 #define NC_HasAgg    0x02    /* One or more aggregate functions seen */
11277 #define NC_IsCheck   0x04    /* True if resolving names in a CHECK constraint */
11278 #define NC_InAggFunc 0x08    /* True if analyzing arguments to an agg func */
11279 #define NC_AsMaybe   0x10    /* Resolve to AS terms of the result set only
11280                              ** if no other resolution is available */
11281
11282 /*
11283 ** An instance of the following structure contains all information
11284 ** needed to generate code for a single SELECT statement.
11285 **
11286 ** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
11287 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
11288 ** limit and nOffset to the value of the offset (or 0 if there is not
11289 ** offset).  But later on, nLimit and nOffset become the memory locations
11290 ** in the VDBE that record the limit and offset counters.
11291 **
11292 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
11293 ** These addresses must be stored so that we can go back and fill in
11294 ** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
11295 ** the number of columns in P2 can be computed at the same time
11296 ** as the OP_OpenEphm instruction is coded because not
11297 ** enough information about the compound query is known at that point.
11298 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
11299 ** for the result set.  The KeyInfo for addrOpenEphm[2] contains collating
11300 ** sequences for the ORDER BY clause.
11301 */
11302 struct Select {
11303   ExprList *pEList;      /* The fields of the result */
11304   u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
11305   u16 selFlags;          /* Various SF_* values */
11306   int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
11307   int addrOpenEphm[3];   /* OP_OpenEphem opcodes related to this select */
11308   double nSelectRow;     /* Estimated number of result rows */
11309   SrcList *pSrc;         /* The FROM clause */
11310   Expr *pWhere;          /* The WHERE clause */
11311   ExprList *pGroupBy;    /* The GROUP BY clause */
11312   Expr *pHaving;         /* The HAVING clause */
11313   ExprList *pOrderBy;    /* The ORDER BY clause */
11314   Select *pPrior;        /* Prior select in a compound select statement */
11315   Select *pNext;         /* Next select to the left in a compound */
11316   Select *pRightmost;    /* Right-most select in a compound select statement */
11317   Expr *pLimit;          /* LIMIT expression. NULL means not used. */
11318   Expr *pOffset;         /* OFFSET expression. NULL means not used. */
11319 };
11320
11321 /*
11322 ** Allowed values for Select.selFlags.  The "SF" prefix stands for
11323 ** "Select Flag".
11324 */
11325 #define SF_Distinct        0x0001  /* Output should be DISTINCT */
11326 #define SF_Resolved        0x0002  /* Identifiers have been resolved */
11327 #define SF_Aggregate       0x0004  /* Contains aggregate functions */
11328 #define SF_UsesEphemeral   0x0008  /* Uses the OpenEphemeral opcode */
11329 #define SF_Expanded        0x0010  /* sqlite3SelectExpand() called on this */
11330 #define SF_HasTypeInfo     0x0020  /* FROM subqueries have Table metadata */
11331 #define SF_UseSorter       0x0040  /* Sort using a sorter */
11332 #define SF_Values          0x0080  /* Synthesized from VALUES clause */
11333 #define SF_Materialize     0x0100  /* Force materialization of views */
11334 #define SF_NestedFrom      0x0200  /* Part of a parenthesized FROM clause */
11335
11336
11337 /*
11338 ** The results of a select can be distributed in several ways.  The
11339 ** "SRT" prefix means "SELECT Result Type".
11340 */
11341 #define SRT_Union        1  /* Store result as keys in an index */
11342 #define SRT_Except       2  /* Remove result from a UNION index */
11343 #define SRT_Exists       3  /* Store 1 if the result is not empty */
11344 #define SRT_Discard      4  /* Do not save the results anywhere */
11345
11346 /* The ORDER BY clause is ignored for all of the above */
11347 #define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
11348
11349 #define SRT_Output       5  /* Output each row of result */
11350 #define SRT_Mem          6  /* Store result in a memory cell */
11351 #define SRT_Set          7  /* Store results as keys in an index */
11352 #define SRT_Table        8  /* Store result as data with an automatic rowid */
11353 #define SRT_EphemTab     9  /* Create transient tab and store like SRT_Table */
11354 #define SRT_Coroutine   10  /* Generate a single row of result */
11355
11356 /*
11357 ** An instance of this object describes where to put of the results of
11358 ** a SELECT statement.
11359 */
11360 struct SelectDest {
11361   u8 eDest;         /* How to dispose of the results.  On of SRT_* above. */
11362   char affSdst;     /* Affinity used when eDest==SRT_Set */
11363   int iSDParm;      /* A parameter used by the eDest disposal method */
11364   int iSdst;        /* Base register where results are written */
11365   int nSdst;        /* Number of registers allocated */
11366 };
11367
11368 /*
11369 ** During code generation of statements that do inserts into AUTOINCREMENT 
11370 ** tables, the following information is attached to the Table.u.autoInc.p
11371 ** pointer of each autoincrement table to record some side information that
11372 ** the code generator needs.  We have to keep per-table autoincrement
11373 ** information in case inserts are down within triggers.  Triggers do not
11374 ** normally coordinate their activities, but we do need to coordinate the
11375 ** loading and saving of autoincrement information.
11376 */
11377 struct AutoincInfo {
11378   AutoincInfo *pNext;   /* Next info block in a list of them all */
11379   Table *pTab;          /* Table this info block refers to */
11380   int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */
11381   int regCtr;           /* Memory register holding the rowid counter */
11382 };
11383
11384 /*
11385 ** Size of the column cache
11386 */
11387 #ifndef SQLITE_N_COLCACHE
11388 # define SQLITE_N_COLCACHE 10
11389 #endif
11390
11391 /*
11392 ** At least one instance of the following structure is created for each 
11393 ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
11394 ** statement. All such objects are stored in the linked list headed at
11395 ** Parse.pTriggerPrg and deleted once statement compilation has been
11396 ** completed.
11397 **
11398 ** A Vdbe sub-program that implements the body and WHEN clause of trigger
11399 ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
11400 ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
11401 ** The Parse.pTriggerPrg list never contains two entries with the same
11402 ** values for both pTrigger and orconf.
11403 **
11404 ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
11405 ** accessed (or set to 0 for triggers fired as a result of INSERT 
11406 ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
11407 ** a mask of new.* columns used by the program.
11408 */
11409 struct TriggerPrg {
11410   Trigger *pTrigger;      /* Trigger this program was coded from */
11411   TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
11412   SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
11413   int orconf;             /* Default ON CONFLICT policy */
11414   u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */
11415 };
11416
11417 /*
11418 ** The yDbMask datatype for the bitmask of all attached databases.
11419 */
11420 #if SQLITE_MAX_ATTACHED>30
11421   typedef sqlite3_uint64 yDbMask;
11422 #else
11423   typedef unsigned int yDbMask;
11424 #endif
11425
11426 /*
11427 ** An SQL parser context.  A copy of this structure is passed through
11428 ** the parser and down into all the parser action routine in order to
11429 ** carry around information that is global to the entire parse.
11430 **
11431 ** The structure is divided into two parts.  When the parser and code
11432 ** generate call themselves recursively, the first part of the structure
11433 ** is constant but the second part is reset at the beginning and end of
11434 ** each recursion.
11435 **
11436 ** The nTableLock and aTableLock variables are only used if the shared-cache 
11437 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
11438 ** used to store the set of table-locks required by the statement being
11439 ** compiled. Function sqlite3TableLock() is used to add entries to the
11440 ** list.
11441 */
11442 struct Parse {
11443   sqlite3 *db;         /* The main database structure */
11444   char *zErrMsg;       /* An error message */
11445   Vdbe *pVdbe;         /* An engine for executing database bytecode */
11446   int rc;              /* Return code from execution */
11447   u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
11448   u8 checkSchema;      /* Causes schema cookie check after an error */
11449   u8 nested;           /* Number of nested calls to the parser/code generator */
11450   u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
11451   u8 nTempInUse;       /* Number of aTempReg[] currently checked out */
11452   u8 nColCache;        /* Number of entries in aColCache[] */
11453   u8 iColCache;        /* Next entry in aColCache[] to replace */
11454   u8 isMultiWrite;     /* True if statement may modify/insert multiple rows */
11455   u8 mayAbort;         /* True if statement may throw an ABORT exception */
11456   int aTempReg[8];     /* Holding area for temporary registers */
11457   int nRangeReg;       /* Size of the temporary register block */
11458   int iRangeReg;       /* First register in temporary register block */
11459   int nErr;            /* Number of errors seen */
11460   int nTab;            /* Number of previously allocated VDBE cursors */
11461   int nMem;            /* Number of memory cells used so far */
11462   int nSet;            /* Number of sets used so far */
11463   int nOnce;           /* Number of OP_Once instructions so far */
11464   int ckBase;          /* Base register of data during check constraints */
11465   int iCacheLevel;     /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
11466   int iCacheCnt;       /* Counter used to generate aColCache[].lru values */
11467   struct yColCache {
11468     int iTable;           /* Table cursor number */
11469     int iColumn;          /* Table column number */
11470     u8 tempReg;           /* iReg is a temp register that needs to be freed */
11471     int iLevel;           /* Nesting level */
11472     int iReg;             /* Reg with value of this column. 0 means none. */
11473     int lru;              /* Least recently used entry has the smallest value */
11474   } aColCache[SQLITE_N_COLCACHE];  /* One for each column cache entry */
11475   yDbMask writeMask;   /* Start a write transaction on these databases */
11476   yDbMask cookieMask;  /* Bitmask of schema verified databases */
11477   int cookieGoto;      /* Address of OP_Goto to cookie verifier subroutine */
11478   int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
11479   int regRowid;        /* Register holding rowid of CREATE TABLE entry */
11480   int regRoot;         /* Register holding root page number for new objects */
11481   int nMaxArg;         /* Max args passed to user function by sub-program */
11482   Token constraintName;/* Name of the constraint currently being parsed */
11483 #ifndef SQLITE_OMIT_SHARED_CACHE
11484   int nTableLock;        /* Number of locks in aTableLock */
11485   TableLock *aTableLock; /* Required table locks for shared-cache mode */
11486 #endif
11487   AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
11488
11489   /* Information used while coding trigger programs. */
11490   Parse *pToplevel;    /* Parse structure for main program (or NULL) */
11491   Table *pTriggerTab;  /* Table triggers are being coded for */
11492   double nQueryLoop;   /* Estimated number of iterations of a query */
11493   u32 oldmask;         /* Mask of old.* columns referenced */
11494   u32 newmask;         /* Mask of new.* columns referenced */
11495   u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
11496   u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
11497   u8 disableTriggers;  /* True to disable triggers */
11498
11499   /* Above is constant between recursions.  Below is reset before and after
11500   ** each recursion */
11501
11502   int nVar;                 /* Number of '?' variables seen in the SQL so far */
11503   int nzVar;                /* Number of available slots in azVar[] */
11504   u8 explain;               /* True if the EXPLAIN flag is found on the query */
11505 #ifndef SQLITE_OMIT_VIRTUALTABLE
11506   u8 declareVtab;           /* True if inside sqlite3_declare_vtab() */
11507   int nVtabLock;            /* Number of virtual tables to lock */
11508 #endif
11509   int nAlias;               /* Number of aliased result set columns */
11510   int nHeight;              /* Expression tree height of current sub-select */
11511 #ifndef SQLITE_OMIT_EXPLAIN
11512   int iSelectId;            /* ID of current select for EXPLAIN output */
11513   int iNextSelectId;        /* Next available select ID for EXPLAIN output */
11514 #endif
11515   char **azVar;             /* Pointers to names of parameters */
11516   Vdbe *pReprepare;         /* VM being reprepared (sqlite3Reprepare()) */
11517   int *aAlias;              /* Register used to hold aliased result */
11518   const char *zTail;        /* All SQL text past the last semicolon parsed */
11519   Table *pNewTable;         /* A table being constructed by CREATE TABLE */
11520   Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
11521   const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
11522   Token sNameToken;         /* Token with unqualified schema object name */
11523   Token sLastToken;         /* The last token parsed */
11524 #ifndef SQLITE_OMIT_VIRTUALTABLE
11525   Token sArg;               /* Complete text of a module argument */
11526   Table **apVtabLock;       /* Pointer to virtual tables needing locking */
11527 #endif
11528   Table *pZombieTab;        /* List of Table objects to delete after code gen */
11529   TriggerPrg *pTriggerPrg;  /* Linked list of coded triggers */
11530 };
11531
11532 /*
11533 ** Return true if currently inside an sqlite3_declare_vtab() call.
11534 */
11535 #ifdef SQLITE_OMIT_VIRTUALTABLE
11536   #define IN_DECLARE_VTAB 0
11537 #else
11538   #define IN_DECLARE_VTAB (pParse->declareVtab)
11539 #endif
11540
11541 /*
11542 ** An instance of the following structure can be declared on a stack and used
11543 ** to save the Parse.zAuthContext value so that it can be restored later.
11544 */
11545 struct AuthContext {
11546   const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
11547   Parse *pParse;              /* The Parse structure */
11548 };
11549
11550 /*
11551 ** Bitfield flags for P5 value in various opcodes.
11552 */
11553 #define OPFLAG_NCHANGE       0x01    /* Set to update db->nChange */
11554 #define OPFLAG_LASTROWID     0x02    /* Set to update db->lastRowid */
11555 #define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
11556 #define OPFLAG_APPEND        0x08    /* This is likely to be an append */
11557 #define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
11558 #define OPFLAG_CLEARCACHE    0x20    /* Clear pseudo-table cache in OP_Column */
11559 #define OPFLAG_LENGTHARG     0x40    /* OP_Column only used for length() */
11560 #define OPFLAG_TYPEOFARG     0x80    /* OP_Column only used for typeof() */
11561 #define OPFLAG_BULKCSR       0x01    /* OP_Open** used to open bulk cursor */
11562 #define OPFLAG_P2ISREG       0x02    /* P2 to OP_Open** is a register number */
11563 #define OPFLAG_PERMUTE       0x01    /* OP_Compare: use the permutation */
11564
11565 /*
11566  * Each trigger present in the database schema is stored as an instance of
11567  * struct Trigger. 
11568  *
11569  * Pointers to instances of struct Trigger are stored in two ways.
11570  * 1. In the "trigHash" hash table (part of the sqlite3* that represents the 
11571  *    database). This allows Trigger structures to be retrieved by name.
11572  * 2. All triggers associated with a single table form a linked list, using the
11573  *    pNext member of struct Trigger. A pointer to the first element of the
11574  *    linked list is stored as the "pTrigger" member of the associated
11575  *    struct Table.
11576  *
11577  * The "step_list" member points to the first element of a linked list
11578  * containing the SQL statements specified as the trigger program.
11579  */
11580 struct Trigger {
11581   char *zName;            /* The name of the trigger                        */
11582   char *table;            /* The table or view to which the trigger applies */
11583   u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
11584   u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
11585   Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
11586   IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
11587                              the <column-list> is stored here */
11588   Schema *pSchema;        /* Schema containing the trigger */
11589   Schema *pTabSchema;     /* Schema containing the table */
11590   TriggerStep *step_list; /* Link list of trigger program steps             */
11591   Trigger *pNext;         /* Next trigger associated with the table */
11592 };
11593
11594 /*
11595 ** A trigger is either a BEFORE or an AFTER trigger.  The following constants
11596 ** determine which. 
11597 **
11598 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
11599 ** In that cases, the constants below can be ORed together.
11600 */
11601 #define TRIGGER_BEFORE  1
11602 #define TRIGGER_AFTER   2
11603
11604 /*
11605  * An instance of struct TriggerStep is used to store a single SQL statement
11606  * that is a part of a trigger-program. 
11607  *
11608  * Instances of struct TriggerStep are stored in a singly linked list (linked
11609  * using the "pNext" member) referenced by the "step_list" member of the 
11610  * associated struct Trigger instance. The first element of the linked list is
11611  * the first step of the trigger-program.
11612  * 
11613  * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
11614  * "SELECT" statement. The meanings of the other members is determined by the 
11615  * value of "op" as follows:
11616  *
11617  * (op == TK_INSERT)
11618  * orconf    -> stores the ON CONFLICT algorithm
11619  * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
11620  *              this stores a pointer to the SELECT statement. Otherwise NULL.
11621  * target    -> A token holding the quoted name of the table to insert into.
11622  * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
11623  *              this stores values to be inserted. Otherwise NULL.
11624  * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ... 
11625  *              statement, then this stores the column-names to be
11626  *              inserted into.
11627  *
11628  * (op == TK_DELETE)
11629  * target    -> A token holding the quoted name of the table to delete from.
11630  * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
11631  *              Otherwise NULL.
11632  * 
11633  * (op == TK_UPDATE)
11634  * target    -> A token holding the quoted name of the table to update rows of.
11635  * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
11636  *              Otherwise NULL.
11637  * pExprList -> A list of the columns to update and the expressions to update
11638  *              them to. See sqlite3Update() documentation of "pChanges"
11639  *              argument.
11640  * 
11641  */
11642 struct TriggerStep {
11643   u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
11644   u8 orconf;           /* OE_Rollback etc. */
11645   Trigger *pTrig;      /* The trigger that this step is a part of */
11646   Select *pSelect;     /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
11647   Token target;        /* Target table for DELETE, UPDATE, INSERT */
11648   Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
11649   ExprList *pExprList; /* SET clause for UPDATE.  VALUES clause for INSERT */
11650   IdList *pIdList;     /* Column names for INSERT */
11651   TriggerStep *pNext;  /* Next in the link-list */
11652   TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
11653 };
11654
11655 /*
11656 ** The following structure contains information used by the sqliteFix...
11657 ** routines as they walk the parse tree to make database references
11658 ** explicit.  
11659 */
11660 typedef struct DbFixer DbFixer;
11661 struct DbFixer {
11662   Parse *pParse;      /* The parsing context.  Error messages written here */
11663   Schema *pSchema;    /* Fix items to this schema */
11664   const char *zDb;    /* Make sure all objects are contained in this database */
11665   const char *zType;  /* Type of the container - used for error messages */
11666   const Token *pName; /* Name of the container - used for error messages */
11667 };
11668
11669 /*
11670 ** An objected used to accumulate the text of a string where we
11671 ** do not necessarily know how big the string will be in the end.
11672 */
11673 struct StrAccum {
11674   sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
11675   char *zBase;         /* A base allocation.  Not from malloc. */
11676   char *zText;         /* The string collected so far */
11677   int  nChar;          /* Length of the string so far */
11678   int  nAlloc;         /* Amount of space allocated in zText */
11679   int  mxAlloc;        /* Maximum allowed string length */
11680   u8   mallocFailed;   /* Becomes true if any memory allocation fails */
11681   u8   useMalloc;      /* 0: none,  1: sqlite3DbMalloc,  2: sqlite3_malloc */
11682   u8   tooBig;         /* Becomes true if string size exceeds limits */
11683 };
11684
11685 /*
11686 ** A pointer to this structure is used to communicate information
11687 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
11688 */
11689 typedef struct {
11690   sqlite3 *db;        /* The database being initialized */
11691   char **pzErrMsg;    /* Error message stored here */
11692   int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
11693   int rc;             /* Result code stored here */
11694 } InitData;
11695
11696 /*
11697 ** Structure containing global configuration data for the SQLite library.
11698 **
11699 ** This structure also contains some state information.
11700 */
11701 struct Sqlite3Config {
11702   int bMemstat;                     /* True to enable memory status */
11703   int bCoreMutex;                   /* True to enable core mutexing */
11704   int bFullMutex;                   /* True to enable full mutexing */
11705   int bOpenUri;                     /* True to interpret filenames as URIs */
11706   int bUseCis;                      /* Use covering indices for full-scans */
11707   int mxStrlen;                     /* Maximum string length */
11708   int szLookaside;                  /* Default lookaside buffer size */
11709   int nLookaside;                   /* Default lookaside buffer count */
11710   sqlite3_mem_methods m;            /* Low-level memory allocation interface */
11711   sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
11712   sqlite3_pcache_methods2 pcache2;  /* Low-level page-cache interface */
11713   void *pHeap;                      /* Heap storage space */
11714   int nHeap;                        /* Size of pHeap[] */
11715   int mnReq, mxReq;                 /* Min and max heap requests sizes */
11716   sqlite3_int64 szMmap;             /* mmap() space per open file */
11717   sqlite3_int64 mxMmap;             /* Maximum value for szMmap */
11718   void *pScratch;                   /* Scratch memory */
11719   int szScratch;                    /* Size of each scratch buffer */
11720   int nScratch;                     /* Number of scratch buffers */
11721   void *pPage;                      /* Page cache memory */
11722   int szPage;                       /* Size of each page in pPage[] */
11723   int nPage;                        /* Number of pages in pPage[] */
11724   int mxParserStack;                /* maximum depth of the parser stack */
11725   int sharedCacheEnabled;           /* true if shared-cache mode enabled */
11726   /* The above might be initialized to non-zero.  The following need to always
11727   ** initially be zero, however. */
11728   int isInit;                       /* True after initialization has finished */
11729   int inProgress;                   /* True while initialization in progress */
11730   int isMutexInit;                  /* True after mutexes are initialized */
11731   int isMallocInit;                 /* True after malloc is initialized */
11732   int isPCacheInit;                 /* True after malloc is initialized */
11733   sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
11734   int nRefInitMutex;                /* Number of users of pInitMutex */
11735   void (*xLog)(void*,int,const char*); /* Function for logging */
11736   void *pLogArg;                       /* First argument to xLog() */
11737   int bLocaltimeFault;              /* True to fail localtime() calls */
11738 #ifdef SQLITE_ENABLE_SQLLOG
11739   void(*xSqllog)(void*,sqlite3*,const char*, int);
11740   void *pSqllogArg;
11741 #endif
11742 };
11743
11744 /*
11745 ** Context pointer passed down through the tree-walk.
11746 */
11747 struct Walker {
11748   int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
11749   int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
11750   Parse *pParse;                            /* Parser context.  */
11751   int walkerDepth;                          /* Number of subqueries */
11752   u8 bSelectDepthFirst;                     /* Do subqueries first */
11753   union {                                   /* Extra data for callback */
11754     NameContext *pNC;                          /* Naming context */
11755     int i;                                     /* Integer value */
11756     SrcList *pSrcList;                         /* FROM clause */
11757     struct SrcCount *pSrcCount;                /* Counting column references */
11758   } u;
11759 };
11760
11761 /* Forward declarations */
11762 SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
11763 SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
11764 SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
11765 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
11766 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
11767
11768 /*
11769 ** Return code from the parse-tree walking primitives and their
11770 ** callbacks.
11771 */
11772 #define WRC_Continue    0   /* Continue down into children */
11773 #define WRC_Prune       1   /* Omit children but continue walking siblings */
11774 #define WRC_Abort       2   /* Abandon the tree walk */
11775
11776 /*
11777 ** Assuming zIn points to the first byte of a UTF-8 character,
11778 ** advance zIn to point to the first byte of the next UTF-8 character.
11779 */
11780 #define SQLITE_SKIP_UTF8(zIn) {                        \
11781   if( (*(zIn++))>=0xc0 ){                              \
11782     while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
11783   }                                                    \
11784 }
11785
11786 /*
11787 ** The SQLITE_*_BKPT macros are substitutes for the error codes with
11788 ** the same name but without the _BKPT suffix.  These macros invoke
11789 ** routines that report the line-number on which the error originated
11790 ** using sqlite3_log().  The routines also provide a convenient place
11791 ** to set a debugger breakpoint.
11792 */
11793 SQLITE_PRIVATE int sqlite3CorruptError(int);
11794 SQLITE_PRIVATE int sqlite3MisuseError(int);
11795 SQLITE_PRIVATE int sqlite3CantopenError(int);
11796 #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
11797 #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
11798 #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
11799
11800
11801 /*
11802 ** FTS4 is really an extension for FTS3.  It is enabled using the
11803 ** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
11804 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
11805 */
11806 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
11807 # define SQLITE_ENABLE_FTS3
11808 #endif
11809
11810 /*
11811 ** The ctype.h header is needed for non-ASCII systems.  It is also
11812 ** needed by FTS3 when FTS3 is included in the amalgamation.
11813 */
11814 #if !defined(SQLITE_ASCII) || \
11815     (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
11816 # include <ctype.h>
11817 #endif
11818
11819 /*
11820 ** The following macros mimic the standard library functions toupper(),
11821 ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
11822 ** sqlite versions only work for ASCII characters, regardless of locale.
11823 */
11824 #ifdef SQLITE_ASCII
11825 # define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
11826 # define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
11827 # define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
11828 # define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
11829 # define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
11830 # define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
11831 # define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
11832 #else
11833 # define sqlite3Toupper(x)   toupper((unsigned char)(x))
11834 # define sqlite3Isspace(x)   isspace((unsigned char)(x))
11835 # define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
11836 # define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
11837 # define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
11838 # define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
11839 # define sqlite3Tolower(x)   tolower((unsigned char)(x))
11840 #endif
11841
11842 /*
11843 ** Internal function prototypes
11844 */
11845 #define sqlite3StrICmp sqlite3_stricmp
11846 SQLITE_PRIVATE int sqlite3Strlen30(const char*);
11847 #define sqlite3StrNICmp sqlite3_strnicmp
11848
11849 SQLITE_PRIVATE int sqlite3MallocInit(void);
11850 SQLITE_PRIVATE void sqlite3MallocEnd(void);
11851 SQLITE_PRIVATE void *sqlite3Malloc(int);
11852 SQLITE_PRIVATE void *sqlite3MallocZero(int);
11853 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
11854 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
11855 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
11856 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
11857 SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
11858 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
11859 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
11860 SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
11861 SQLITE_PRIVATE int sqlite3MallocSize(void*);
11862 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
11863 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
11864 SQLITE_PRIVATE void sqlite3ScratchFree(void*);
11865 SQLITE_PRIVATE void *sqlite3PageMalloc(int);
11866 SQLITE_PRIVATE void sqlite3PageFree(void*);
11867 SQLITE_PRIVATE void sqlite3MemSetDefault(void);
11868 SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
11869 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
11870
11871 /*
11872 ** On systems with ample stack space and that support alloca(), make
11873 ** use of alloca() to obtain space for large automatic objects.  By default,
11874 ** obtain space from malloc().
11875 **
11876 ** The alloca() routine never returns NULL.  This will cause code paths
11877 ** that deal with sqlite3StackAlloc() failures to be unreachable.
11878 */
11879 #ifdef SQLITE_USE_ALLOCA
11880 # define sqlite3StackAllocRaw(D,N)   alloca(N)
11881 # define sqlite3StackAllocZero(D,N)  memset(alloca(N), 0, N)
11882 # define sqlite3StackFree(D,P)       
11883 #else
11884 # define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)
11885 # define sqlite3StackAllocZero(D,N)  sqlite3DbMallocZero(D,N)
11886 # define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)
11887 #endif
11888
11889 #ifdef SQLITE_ENABLE_MEMSYS3
11890 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
11891 #endif
11892 #ifdef SQLITE_ENABLE_MEMSYS5
11893 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
11894 #endif
11895
11896
11897 #ifndef SQLITE_MUTEX_OMIT
11898 SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
11899 SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3NoopMutex(void);
11900 SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
11901 SQLITE_PRIVATE   int sqlite3MutexInit(void);
11902 SQLITE_PRIVATE   int sqlite3MutexEnd(void);
11903 #endif
11904
11905 SQLITE_PRIVATE int sqlite3StatusValue(int);
11906 SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
11907 SQLITE_PRIVATE void sqlite3StatusSet(int, int);
11908
11909 #ifndef SQLITE_OMIT_FLOATING_POINT
11910 SQLITE_PRIVATE   int sqlite3IsNaN(double);
11911 #else
11912 # define sqlite3IsNaN(X)  0
11913 #endif
11914
11915 SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
11916 #ifndef SQLITE_OMIT_TRACE
11917 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
11918 #endif
11919 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
11920 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
11921 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
11922 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
11923 SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
11924 #endif
11925 #if defined(SQLITE_TEST)
11926 SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
11927 #endif
11928
11929 /* Output formatting for SQLITE_TESTCTRL_EXPLAIN */
11930 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
11931 SQLITE_PRIVATE   void sqlite3ExplainBegin(Vdbe*);
11932 SQLITE_PRIVATE   void sqlite3ExplainPrintf(Vdbe*, const char*, ...);
11933 SQLITE_PRIVATE   void sqlite3ExplainNL(Vdbe*);
11934 SQLITE_PRIVATE   void sqlite3ExplainPush(Vdbe*);
11935 SQLITE_PRIVATE   void sqlite3ExplainPop(Vdbe*);
11936 SQLITE_PRIVATE   void sqlite3ExplainFinish(Vdbe*);
11937 SQLITE_PRIVATE   void sqlite3ExplainSelect(Vdbe*, Select*);
11938 SQLITE_PRIVATE   void sqlite3ExplainExpr(Vdbe*, Expr*);
11939 SQLITE_PRIVATE   void sqlite3ExplainExprList(Vdbe*, ExprList*);
11940 SQLITE_PRIVATE   const char *sqlite3VdbeExplanation(Vdbe*);
11941 #else
11942 # define sqlite3ExplainBegin(X)
11943 # define sqlite3ExplainSelect(A,B)
11944 # define sqlite3ExplainExpr(A,B)
11945 # define sqlite3ExplainExprList(A,B)
11946 # define sqlite3ExplainFinish(X)
11947 # define sqlite3VdbeExplanation(X) 0
11948 #endif
11949
11950
11951 SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
11952 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
11953 SQLITE_PRIVATE int sqlite3Dequote(char*);
11954 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
11955 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
11956 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
11957 SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
11958 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
11959 SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
11960 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
11961 SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
11962 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
11963 SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
11964 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
11965 SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
11966 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
11967 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
11968 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
11969 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
11970 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
11971 SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
11972 SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
11973 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
11974 SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
11975 SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
11976 SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
11977 SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
11978 SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
11979 SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
11980 SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
11981 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
11982 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
11983 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
11984 SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
11985 SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
11986 SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
11987 SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
11988 SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
11989 SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
11990 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
11991 SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
11992 SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
11993 SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
11994                     sqlite3_vfs**,char**,char **);
11995 SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
11996 SQLITE_PRIVATE int sqlite3CodeOnce(Parse *);
11997
11998 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
11999 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
12000 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
12001 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
12002 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
12003 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
12004 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
12005
12006 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
12007 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
12008 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
12009 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);
12010 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
12011
12012 SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
12013
12014 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
12015 SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
12016 #else
12017 # define sqlite3ViewGetColumnNames(A,B) 0
12018 #endif
12019
12020 SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
12021 SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
12022 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
12023 #ifndef SQLITE_OMIT_AUTOINCREMENT
12024 SQLITE_PRIVATE   void sqlite3AutoincrementBegin(Parse *pParse);
12025 SQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);
12026 #else
12027 # define sqlite3AutoincrementBegin(X)
12028 # define sqlite3AutoincrementEnd(X)
12029 #endif
12030 SQLITE_PRIVATE int sqlite3CodeCoroutine(Parse*, Select*, SelectDest*);
12031 SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
12032 SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
12033 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
12034 SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
12035 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
12036 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
12037 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
12038                                       Token*, Select*, Expr*, IdList*);
12039 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
12040 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
12041 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
12042 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
12043 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
12044 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
12045 SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
12046                         Token*, int, int);
12047 SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
12048 SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
12049 SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
12050                          Expr*,ExprList*,u16,Expr*,Expr*);
12051 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
12052 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
12053 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
12054 SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
12055 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
12056 SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,Expr*,char*);
12057 #endif
12058 SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
12059 SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
12060 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
12061 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
12062 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
12063 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
12064 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
12065 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
12066 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
12067 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int);
12068 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
12069 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
12070 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
12071 SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
12072 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
12073 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
12074 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
12075 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
12076 SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
12077 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
12078 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
12079 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
12080 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
12081 SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,int isView,struct SrcList_item *);
12082 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
12083 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
12084 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
12085 SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
12086 SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
12087 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
12088 SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*);
12089 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*);
12090 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
12091 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
12092 SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
12093 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
12094 SQLITE_PRIVATE void sqlite3PrngSaveState(void);
12095 SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
12096 SQLITE_PRIVATE void sqlite3PrngResetState(void);
12097 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
12098 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
12099 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
12100 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
12101 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
12102 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
12103 SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
12104 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
12105 SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
12106 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
12107 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
12108 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
12109 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
12110 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
12111 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
12112 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
12113 SQLITE_PRIVATE int sqlite3IsRowid(const char*);
12114 SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int);
12115 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
12116 SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
12117 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
12118                                      int*,int,int,int,int,int*);
12119 SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
12120 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
12121 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
12122 SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
12123 SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
12124 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, int);
12125 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
12126 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
12127 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
12128 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
12129 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
12130 SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
12131 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,u8);
12132 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
12133 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
12134 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
12135 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
12136 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
12137 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
12138
12139 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
12140 SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
12141 #endif
12142
12143 #ifndef SQLITE_OMIT_TRIGGER
12144 SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
12145                            Expr*,int, int);
12146 SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
12147 SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
12148 SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
12149 SQLITE_PRIVATE   Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
12150 SQLITE_PRIVATE   Trigger *sqlite3TriggerList(Parse *, Table *);
12151 SQLITE_PRIVATE   void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
12152                             int, int, int);
12153 SQLITE_PRIVATE   void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
12154   void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
12155 SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
12156 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
12157 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
12158                                         ExprList*,Select*,u8);
12159 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
12160 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
12161 SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
12162 SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
12163 SQLITE_PRIVATE   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
12164 # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
12165 #else
12166 # define sqlite3TriggersExist(B,C,D,E,F) 0
12167 # define sqlite3DeleteTrigger(A,B)
12168 # define sqlite3DropTriggerPtr(A,B)
12169 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
12170 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
12171 # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
12172 # define sqlite3TriggerList(X, Y) 0
12173 # define sqlite3ParseToplevel(p) p
12174 # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
12175 #endif
12176
12177 SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
12178 SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
12179 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
12180 #ifndef SQLITE_OMIT_AUTHORIZATION
12181 SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
12182 SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
12183 SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
12184 SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
12185 SQLITE_PRIVATE   int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
12186 #else
12187 # define sqlite3AuthRead(a,b,c,d)
12188 # define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
12189 # define sqlite3AuthContextPush(a,b,c)
12190 # define sqlite3AuthContextPop(a)  ((void)(a))
12191 #endif
12192 SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
12193 SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
12194 SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
12195 SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
12196 SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
12197 SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
12198 SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
12199 SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
12200 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
12201 SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
12202 SQLITE_PRIVATE int sqlite3Atoi(const char*);
12203 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
12204 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
12205 SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
12206
12207 /*
12208 ** Routines to read and write variable-length integers.  These used to
12209 ** be defined locally, but now we use the varint routines in the util.c
12210 ** file.  Code should use the MACRO forms below, as the Varint32 versions
12211 ** are coded to assume the single byte case is already handled (which 
12212 ** the MACRO form does).
12213 */
12214 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
12215 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
12216 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
12217 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
12218 SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
12219
12220 /*
12221 ** The header of a record consists of a sequence variable-length integers.
12222 ** These integers are almost always small and are encoded as a single byte.
12223 ** The following macros take advantage this fact to provide a fast encode
12224 ** and decode of the integers in a record header.  It is faster for the common
12225 ** case where the integer is a single byte.  It is a little slower when the
12226 ** integer is two or more bytes.  But overall it is faster.
12227 **
12228 ** The following expressions are equivalent:
12229 **
12230 **     x = sqlite3GetVarint32( A, &B );
12231 **     x = sqlite3PutVarint32( A, B );
12232 **
12233 **     x = getVarint32( A, B );
12234 **     x = putVarint32( A, B );
12235 **
12236 */
12237 #define getVarint32(A,B)  \
12238   (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
12239 #define putVarint32(A,B)  \
12240   (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
12241   sqlite3PutVarint32((A),(B)))
12242 #define getVarint    sqlite3GetVarint
12243 #define putVarint    sqlite3PutVarint
12244
12245
12246 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
12247 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
12248 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
12249 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
12250 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
12251 SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
12252 SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
12253 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
12254 SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
12255 SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
12256
12257 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) || \
12258     defined(SQLITE_DEBUG_OS_TRACE)
12259 SQLITE_PRIVATE const char *sqlite3ErrName(int);
12260 #endif
12261
12262 SQLITE_PRIVATE const char *sqlite3ErrStr(int);
12263 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
12264 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
12265 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
12266 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
12267 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, Token*);
12268 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
12269 SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
12270 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
12271 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
12272 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
12273 SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
12274 SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
12275 SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
12276 SQLITE_PRIVATE int sqlite3AbsInt32(int);
12277 #ifdef SQLITE_ENABLE_8_3_NAMES
12278 SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
12279 #else
12280 # define sqlite3FileSuffix3(X,Y)
12281 #endif
12282 SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,int);
12283
12284 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
12285 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
12286 SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8, 
12287                         void(*)(void*));
12288 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
12289 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
12290 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
12291 #ifdef SQLITE_ENABLE_STAT3
12292 SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *, u8, char *, int, int *);
12293 #endif
12294 SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
12295 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
12296 #ifndef SQLITE_AMALGAMATION
12297 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
12298 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
12299 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
12300 SQLITE_PRIVATE const Token sqlite3IntTokens[];
12301 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
12302 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
12303 #ifndef SQLITE_OMIT_WSD
12304 SQLITE_PRIVATE int sqlite3PendingByte;
12305 #endif
12306 #endif
12307 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
12308 SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
12309 SQLITE_PRIVATE void sqlite3AlterFunctions(void);
12310 SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
12311 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
12312 SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
12313 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
12314 SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
12315 SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
12316 SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
12317 SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
12318 SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
12319 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
12320 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
12321 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
12322 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
12323 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
12324 SQLITE_PRIVATE char sqlite3AffinityType(const char*);
12325 SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
12326 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
12327 SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
12328 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
12329 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
12330 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
12331 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
12332 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
12333 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
12334 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
12335 SQLITE_PRIVATE void sqlite3SchemaClear(void *);
12336 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
12337 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
12338 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
12339 SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *, 
12340   void (*)(sqlite3_context*,int,sqlite3_value **),
12341   void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
12342   FuncDestructor *pDestructor
12343 );
12344 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
12345 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
12346
12347 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
12348 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
12349 SQLITE_PRIVATE void sqlite3AppendSpace(StrAccum*,int);
12350 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
12351 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
12352 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
12353 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
12354
12355 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
12356 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
12357
12358 /*
12359 ** The interface to the LEMON-generated parser
12360 */
12361 SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
12362 SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
12363 SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
12364 #ifdef YYTRACKMAXSTACKDEPTH
12365 SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);
12366 #endif
12367
12368 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
12369 #ifndef SQLITE_OMIT_LOAD_EXTENSION
12370 SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
12371 #else
12372 # define sqlite3CloseExtensions(X)
12373 #endif
12374
12375 #ifndef SQLITE_OMIT_SHARED_CACHE
12376 SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
12377 #else
12378   #define sqlite3TableLock(v,w,x,y,z)
12379 #endif
12380
12381 #ifdef SQLITE_TEST
12382 SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
12383 #endif
12384
12385 #ifdef SQLITE_OMIT_VIRTUALTABLE
12386 #  define sqlite3VtabClear(Y)
12387 #  define sqlite3VtabSync(X,Y) SQLITE_OK
12388 #  define sqlite3VtabRollback(X)
12389 #  define sqlite3VtabCommit(X)
12390 #  define sqlite3VtabInSync(db) 0
12391 #  define sqlite3VtabLock(X) 
12392 #  define sqlite3VtabUnlock(X)
12393 #  define sqlite3VtabUnlockList(X)
12394 #  define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
12395 #  define sqlite3GetVTable(X,Y)  ((VTable*)0)
12396 #else
12397 SQLITE_PRIVATE    void sqlite3VtabClear(sqlite3 *db, Table*);
12398 SQLITE_PRIVATE    void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
12399 SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, char **);
12400 SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
12401 SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
12402 SQLITE_PRIVATE    void sqlite3VtabLock(VTable *);
12403 SQLITE_PRIVATE    void sqlite3VtabUnlock(VTable *);
12404 SQLITE_PRIVATE    void sqlite3VtabUnlockList(sqlite3*);
12405 SQLITE_PRIVATE    int sqlite3VtabSavepoint(sqlite3 *, int, int);
12406 SQLITE_PRIVATE    VTable *sqlite3GetVTable(sqlite3*, Table*);
12407 #  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
12408 #endif
12409 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
12410 SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
12411 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
12412 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
12413 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
12414 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
12415 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
12416 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
12417 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
12418 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
12419 SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
12420 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
12421 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
12422 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
12423 SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
12424 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
12425 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
12426 SQLITE_PRIVATE const char *sqlite3JournalModename(int);
12427 #ifndef SQLITE_OMIT_WAL
12428 SQLITE_PRIVATE   int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
12429 SQLITE_PRIVATE   int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
12430 #endif
12431
12432 /* Declarations for functions in fkey.c. All of these are replaced by
12433 ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
12434 ** key functionality is available. If OMIT_TRIGGER is defined but
12435 ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
12436 ** this case foreign keys are parsed, but no other functionality is 
12437 ** provided (enforcement of FK constraints requires the triggers sub-system).
12438 */
12439 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
12440 SQLITE_PRIVATE   void sqlite3FkCheck(Parse*, Table*, int, int);
12441 SQLITE_PRIVATE   void sqlite3FkDropTable(Parse*, SrcList *, Table*);
12442 SQLITE_PRIVATE   void sqlite3FkActions(Parse*, Table*, ExprList*, int);
12443 SQLITE_PRIVATE   int sqlite3FkRequired(Parse*, Table*, int*, int);
12444 SQLITE_PRIVATE   u32 sqlite3FkOldmask(Parse*, Table*);
12445 SQLITE_PRIVATE   FKey *sqlite3FkReferences(Table *);
12446 #else
12447   #define sqlite3FkActions(a,b,c,d)
12448   #define sqlite3FkCheck(a,b,c,d)
12449   #define sqlite3FkDropTable(a,b,c)
12450   #define sqlite3FkOldmask(a,b)      0
12451   #define sqlite3FkRequired(a,b,c,d) 0
12452 #endif
12453 #ifndef SQLITE_OMIT_FOREIGN_KEY
12454 SQLITE_PRIVATE   void sqlite3FkDelete(sqlite3 *, Table*);
12455 SQLITE_PRIVATE   int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
12456 #else
12457   #define sqlite3FkDelete(a,b)
12458   #define sqlite3FkLocateIndex(a,b,c,d,e)
12459 #endif
12460
12461
12462 /*
12463 ** Available fault injectors.  Should be numbered beginning with 0.
12464 */
12465 #define SQLITE_FAULTINJECTOR_MALLOC     0
12466 #define SQLITE_FAULTINJECTOR_COUNT      1
12467
12468 /*
12469 ** The interface to the code in fault.c used for identifying "benign"
12470 ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
12471 ** is not defined.
12472 */
12473 #ifndef SQLITE_OMIT_BUILTIN_TEST
12474 SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);
12475 SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);
12476 #else
12477   #define sqlite3BeginBenignMalloc()
12478   #define sqlite3EndBenignMalloc()
12479 #endif
12480
12481 #define IN_INDEX_ROWID           1
12482 #define IN_INDEX_EPH             2
12483 #define IN_INDEX_INDEX_ASC       3
12484 #define IN_INDEX_INDEX_DESC      4
12485 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
12486
12487 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
12488 SQLITE_PRIVATE   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
12489 SQLITE_PRIVATE   int sqlite3JournalSize(sqlite3_vfs *);
12490 SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
12491 SQLITE_PRIVATE   int sqlite3JournalExists(sqlite3_file *p);
12492 #else
12493   #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
12494   #define sqlite3JournalExists(p) 1
12495 #endif
12496
12497 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
12498 SQLITE_PRIVATE int sqlite3MemJournalSize(void);
12499 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
12500
12501 #if SQLITE_MAX_EXPR_DEPTH>0
12502 SQLITE_PRIVATE   void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
12503 SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
12504 SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
12505 #else
12506   #define sqlite3ExprSetHeight(x,y)
12507   #define sqlite3SelectExprHeight(x) 0
12508   #define sqlite3ExprCheckHeight(x,y)
12509 #endif
12510
12511 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
12512 SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
12513
12514 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
12515 SQLITE_PRIVATE   void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
12516 SQLITE_PRIVATE   void sqlite3ConnectionUnlocked(sqlite3 *db);
12517 SQLITE_PRIVATE   void sqlite3ConnectionClosed(sqlite3 *db);
12518 #else
12519   #define sqlite3ConnectionBlocked(x,y)
12520   #define sqlite3ConnectionUnlocked(x)
12521   #define sqlite3ConnectionClosed(x)
12522 #endif
12523
12524 #ifdef SQLITE_DEBUG
12525 SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
12526 #endif
12527
12528 /*
12529 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
12530 ** sqlite3IoTrace is a pointer to a printf-like routine used to
12531 ** print I/O tracing messages. 
12532 */
12533 #ifdef SQLITE_ENABLE_IOTRACE
12534 # define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
12535 SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
12536 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
12537 #else
12538 # define IOTRACE(A)
12539 # define sqlite3VdbeIOTraceSql(X)
12540 #endif
12541
12542 /*
12543 ** These routines are available for the mem2.c debugging memory allocator
12544 ** only.  They are used to verify that different "types" of memory
12545 ** allocations are properly tracked by the system.
12546 **
12547 ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
12548 ** the MEMTYPE_* macros defined below.  The type must be a bitmask with
12549 ** a single bit set.
12550 **
12551 ** sqlite3MemdebugHasType() returns true if any of the bits in its second
12552 ** argument match the type set by the previous sqlite3MemdebugSetType().
12553 ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
12554 **
12555 ** sqlite3MemdebugNoType() returns true if none of the bits in its second
12556 ** argument match the type set by the previous sqlite3MemdebugSetType().
12557 **
12558 ** Perhaps the most important point is the difference between MEMTYPE_HEAP
12559 ** and MEMTYPE_LOOKASIDE.  If an allocation is MEMTYPE_LOOKASIDE, that means
12560 ** it might have been allocated by lookaside, except the allocation was
12561 ** too large or lookaside was already full.  It is important to verify
12562 ** that allocations that might have been satisfied by lookaside are not
12563 ** passed back to non-lookaside free() routines.  Asserts such as the
12564 ** example above are placed on the non-lookaside free() routines to verify
12565 ** this constraint. 
12566 **
12567 ** All of this is no-op for a production build.  It only comes into
12568 ** play when the SQLITE_MEMDEBUG compile-time option is used.
12569 */
12570 #ifdef SQLITE_MEMDEBUG
12571 SQLITE_PRIVATE   void sqlite3MemdebugSetType(void*,u8);
12572 SQLITE_PRIVATE   int sqlite3MemdebugHasType(void*,u8);
12573 SQLITE_PRIVATE   int sqlite3MemdebugNoType(void*,u8);
12574 #else
12575 # define sqlite3MemdebugSetType(X,Y)  /* no-op */
12576 # define sqlite3MemdebugHasType(X,Y)  1
12577 # define sqlite3MemdebugNoType(X,Y)   1
12578 #endif
12579 #define MEMTYPE_HEAP       0x01  /* General heap allocations */
12580 #define MEMTYPE_LOOKASIDE  0x02  /* Might have been lookaside memory */
12581 #define MEMTYPE_SCRATCH    0x04  /* Scratch allocations */
12582 #define MEMTYPE_PCACHE     0x08  /* Page cache allocations */
12583 #define MEMTYPE_DB         0x10  /* Uses sqlite3DbMalloc, not sqlite_malloc */
12584
12585 #endif /* _SQLITEINT_H_ */
12586
12587 /************** End of sqliteInt.h *******************************************/
12588 /************** Begin file global.c ******************************************/
12589 /*
12590 ** 2008 June 13
12591 **
12592 ** The author disclaims copyright to this source code.  In place of
12593 ** a legal notice, here is a blessing:
12594 **
12595 **    May you do good and not evil.
12596 **    May you find forgiveness for yourself and forgive others.
12597 **    May you share freely, never taking more than you give.
12598 **
12599 *************************************************************************
12600 **
12601 ** This file contains definitions of global variables and contants.
12602 */
12603
12604 /* An array to map all upper-case characters into their corresponding
12605 ** lower-case character. 
12606 **
12607 ** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
12608 ** handle case conversions for the UTF character set since the tables
12609 ** involved are nearly as big or bigger than SQLite itself.
12610 */
12611 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
12612 #ifdef SQLITE_ASCII
12613       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
12614      18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
12615      36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
12616      54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
12617     104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
12618     122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
12619     108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
12620     126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
12621     144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
12622     162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
12623     180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
12624     198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
12625     216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
12626     234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
12627     252,253,254,255
12628 #endif
12629 #ifdef SQLITE_EBCDIC
12630       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
12631      16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
12632      32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
12633      48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
12634      64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
12635      80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
12636      96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
12637     112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
12638     128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
12639     144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
12640     160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
12641     176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
12642     192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
12643     208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
12644     224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
12645     239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
12646 #endif
12647 };
12648
12649 /*
12650 ** The following 256 byte lookup table is used to support SQLites built-in
12651 ** equivalents to the following standard library functions:
12652 **
12653 **   isspace()                        0x01
12654 **   isalpha()                        0x02
12655 **   isdigit()                        0x04
12656 **   isalnum()                        0x06
12657 **   isxdigit()                       0x08
12658 **   toupper()                        0x20
12659 **   SQLite identifier character      0x40
12660 **
12661 ** Bit 0x20 is set if the mapped character requires translation to upper
12662 ** case. i.e. if the character is a lower-case ASCII character.
12663 ** If x is a lower-case ASCII character, then its upper-case equivalent
12664 ** is (x - 0x20). Therefore toupper() can be implemented as:
12665 **
12666 **   (x & ~(map[x]&0x20))
12667 **
12668 ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
12669 ** array. tolower() is used more often than toupper() by SQLite.
12670 **
12671 ** Bit 0x40 is set if the character non-alphanumeric and can be used in an 
12672 ** SQLite identifier.  Identifiers are alphanumerics, "_", "$", and any
12673 ** non-ASCII UTF character. Hence the test for whether or not a character is
12674 ** part of an identifier is 0x46.
12675 **
12676 ** SQLite's versions are identical to the standard versions assuming a
12677 ** locale of "C". They are implemented as macros in sqliteInt.h.
12678 */
12679 #ifdef SQLITE_ASCII
12680 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
12681   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
12682   0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
12683   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
12684   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
12685   0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,  /* 20..27     !"#$%&' */
12686   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
12687   0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
12688   0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */
12689
12690   0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
12691   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
12692   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
12693   0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40,  /* 58..5f    XYZ[\]^_ */
12694   0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
12695   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
12696   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
12697   0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */
12698
12699   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 80..87    ........ */
12700   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 88..8f    ........ */
12701   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 90..97    ........ */
12702   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 98..9f    ........ */
12703   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a0..a7    ........ */
12704   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a8..af    ........ */
12705   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b0..b7    ........ */
12706   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b8..bf    ........ */
12707
12708   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c0..c7    ........ */
12709   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c8..cf    ........ */
12710   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d0..d7    ........ */
12711   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d8..df    ........ */
12712   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */
12713   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */
12714   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
12715   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
12716 };
12717 #endif
12718
12719 #ifndef SQLITE_USE_URI
12720 # define  SQLITE_USE_URI 0
12721 #endif
12722
12723 #ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN
12724 # define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
12725 #endif
12726
12727 /*
12728 ** The following singleton contains the global configuration for
12729 ** the SQLite library.
12730 */
12731 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
12732    SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
12733    1,                         /* bCoreMutex */
12734    SQLITE_THREADSAFE==1,      /* bFullMutex */
12735    SQLITE_USE_URI,            /* bOpenUri */
12736    SQLITE_ALLOW_COVERING_INDEX_SCAN,   /* bUseCis */
12737    0x7ffffffe,                /* mxStrlen */
12738    128,                       /* szLookaside */
12739    500,                       /* nLookaside */
12740    {0,0,0,0,0,0,0,0},         /* m */
12741    {0,0,0,0,0,0,0,0,0},       /* mutex */
12742    {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
12743    (void*)0,                  /* pHeap */
12744    0,                         /* nHeap */
12745    0, 0,                      /* mnHeap, mxHeap */
12746    SQLITE_DEFAULT_MMAP_SIZE,  /* szMmap */
12747    SQLITE_MAX_MMAP_SIZE,      /* mxMmap */
12748    (void*)0,                  /* pScratch */
12749    0,                         /* szScratch */
12750    0,                         /* nScratch */
12751    (void*)0,                  /* pPage */
12752    0,                         /* szPage */
12753    0,                         /* nPage */
12754    0,                         /* mxParserStack */
12755    0,                         /* sharedCacheEnabled */
12756    /* All the rest should always be initialized to zero */
12757    0,                         /* isInit */
12758    0,                         /* inProgress */
12759    0,                         /* isMutexInit */
12760    0,                         /* isMallocInit */
12761    0,                         /* isPCacheInit */
12762    0,                         /* pInitMutex */
12763    0,                         /* nRefInitMutex */
12764    0,                         /* xLog */
12765    0,                         /* pLogArg */
12766    0,                         /* bLocaltimeFault */
12767 #ifdef SQLITE_ENABLE_SQLLOG
12768    0,                         /* xSqllog */
12769    0                          /* pSqllogArg */
12770 #endif
12771 };
12772
12773
12774 /*
12775 ** Hash table for global functions - functions common to all
12776 ** database connections.  After initialization, this table is
12777 ** read-only.
12778 */
12779 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
12780
12781 /*
12782 ** Constant tokens for values 0 and 1.
12783 */
12784 SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
12785    { "0", 1 },
12786    { "1", 1 }
12787 };
12788
12789
12790 /*
12791 ** The value of the "pending" byte must be 0x40000000 (1 byte past the
12792 ** 1-gibabyte boundary) in a compatible database.  SQLite never uses
12793 ** the database page that contains the pending byte.  It never attempts
12794 ** to read or write that page.  The pending byte page is set assign
12795 ** for use by the VFS layers as space for managing file locks.
12796 **
12797 ** During testing, it is often desirable to move the pending byte to
12798 ** a different position in the file.  This allows code that has to
12799 ** deal with the pending byte to run on files that are much smaller
12800 ** than 1 GiB.  The sqlite3_test_control() interface can be used to
12801 ** move the pending byte.
12802 **
12803 ** IMPORTANT:  Changing the pending byte to any value other than
12804 ** 0x40000000 results in an incompatible database file format!
12805 ** Changing the pending byte during operating results in undefined
12806 ** and dileterious behavior.
12807 */
12808 #ifndef SQLITE_OMIT_WSD
12809 SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
12810 #endif
12811
12812 /*
12813 ** Properties of opcodes.  The OPFLG_INITIALIZER macro is
12814 ** created by mkopcodeh.awk during compilation.  Data is obtained
12815 ** from the comments following the "case OP_xxxx:" statements in
12816 ** the vdbe.c file.  
12817 */
12818 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
12819
12820 /************** End of global.c **********************************************/
12821 /************** Begin file ctime.c *******************************************/
12822 /*
12823 ** 2010 February 23
12824 **
12825 ** The author disclaims copyright to this source code.  In place of
12826 ** a legal notice, here is a blessing:
12827 **
12828 **    May you do good and not evil.
12829 **    May you find forgiveness for yourself and forgive others.
12830 **    May you share freely, never taking more than you give.
12831 **
12832 *************************************************************************
12833 **
12834 ** This file implements routines used to report what compile-time options
12835 ** SQLite was built with.
12836 */
12837
12838 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
12839
12840
12841 /*
12842 ** An array of names of all compile-time options.  This array should 
12843 ** be sorted A-Z.
12844 **
12845 ** This array looks large, but in a typical installation actually uses
12846 ** only a handful of compile-time options, so most times this array is usually
12847 ** rather short and uses little memory space.
12848 */
12849 static const char * const azCompileOpt[] = {
12850
12851 /* These macros are provided to "stringify" the value of the define
12852 ** for those options in which the value is meaningful. */
12853 #define CTIMEOPT_VAL_(opt) #opt
12854 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
12855
12856 #ifdef SQLITE_32BIT_ROWID
12857   "32BIT_ROWID",
12858 #endif
12859 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
12860   "4_BYTE_ALIGNED_MALLOC",
12861 #endif
12862 #ifdef SQLITE_CASE_SENSITIVE_LIKE
12863   "CASE_SENSITIVE_LIKE",
12864 #endif
12865 #ifdef SQLITE_CHECK_PAGES
12866   "CHECK_PAGES",
12867 #endif
12868 #ifdef SQLITE_COVERAGE_TEST
12869   "COVERAGE_TEST",
12870 #endif
12871 #ifdef SQLITE_DEBUG
12872   "DEBUG",
12873 #endif
12874 #ifdef SQLITE_DEFAULT_LOCKING_MODE
12875   "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
12876 #endif
12877 #if defined(SQLITE_DEFAULT_MMAP_SIZE) && !defined(SQLITE_DEFAULT_MMAP_SIZE_xc)
12878   "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),
12879 #endif
12880 #ifdef SQLITE_DISABLE_DIRSYNC
12881   "DISABLE_DIRSYNC",
12882 #endif
12883 #ifdef SQLITE_DISABLE_LFS
12884   "DISABLE_LFS",
12885 #endif
12886 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
12887   "ENABLE_ATOMIC_WRITE",
12888 #endif
12889 #ifdef SQLITE_ENABLE_CEROD
12890   "ENABLE_CEROD",
12891 #endif
12892 #ifdef SQLITE_ENABLE_COLUMN_METADATA
12893   "ENABLE_COLUMN_METADATA",
12894 #endif
12895 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
12896   "ENABLE_EXPENSIVE_ASSERT",
12897 #endif
12898 #ifdef SQLITE_ENABLE_FTS1
12899   "ENABLE_FTS1",
12900 #endif
12901 #ifdef SQLITE_ENABLE_FTS2
12902   "ENABLE_FTS2",
12903 #endif
12904 #ifdef SQLITE_ENABLE_FTS3
12905   "ENABLE_FTS3",
12906 #endif
12907 #ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
12908   "ENABLE_FTS3_PARENTHESIS",
12909 #endif
12910 #ifdef SQLITE_ENABLE_FTS4
12911   "ENABLE_FTS4",
12912 #endif
12913 #ifdef SQLITE_ENABLE_ICU
12914   "ENABLE_ICU",
12915 #endif
12916 #ifdef SQLITE_ENABLE_IOTRACE
12917   "ENABLE_IOTRACE",
12918 #endif
12919 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
12920   "ENABLE_LOAD_EXTENSION",
12921 #endif
12922 #ifdef SQLITE_ENABLE_LOCKING_STYLE
12923   "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
12924 #endif
12925 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
12926   "ENABLE_MEMORY_MANAGEMENT",
12927 #endif
12928 #ifdef SQLITE_ENABLE_MEMSYS3
12929   "ENABLE_MEMSYS3",
12930 #endif
12931 #ifdef SQLITE_ENABLE_MEMSYS5
12932   "ENABLE_MEMSYS5",
12933 #endif
12934 #ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK
12935   "ENABLE_OVERSIZE_CELL_CHECK",
12936 #endif
12937 #ifdef SQLITE_ENABLE_RTREE
12938   "ENABLE_RTREE",
12939 #endif
12940 #ifdef SQLITE_ENABLE_STAT3
12941   "ENABLE_STAT3",
12942 #endif
12943 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
12944   "ENABLE_UNLOCK_NOTIFY",
12945 #endif
12946 #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
12947   "ENABLE_UPDATE_DELETE_LIMIT",
12948 #endif
12949 #ifdef SQLITE_HAS_CODEC
12950   "HAS_CODEC",
12951 #endif
12952 #ifdef SQLITE_HAVE_ISNAN
12953   "HAVE_ISNAN",
12954 #endif
12955 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
12956   "HOMEGROWN_RECURSIVE_MUTEX",
12957 #endif
12958 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
12959   "IGNORE_AFP_LOCK_ERRORS",
12960 #endif
12961 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
12962   "IGNORE_FLOCK_LOCK_ERRORS",
12963 #endif
12964 #ifdef SQLITE_INT64_TYPE
12965   "INT64_TYPE",
12966 #endif
12967 #ifdef SQLITE_LOCK_TRACE
12968   "LOCK_TRACE",
12969 #endif
12970 #if defined(SQLITE_MAX_MMAP_SIZE) && !defined(SQLITE_MAX_MMAP_SIZE_xc)
12971   "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
12972 #endif
12973 #ifdef SQLITE_MAX_SCHEMA_RETRY
12974   "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
12975 #endif
12976 #ifdef SQLITE_MEMDEBUG
12977   "MEMDEBUG",
12978 #endif
12979 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
12980   "MIXED_ENDIAN_64BIT_FLOAT",
12981 #endif
12982 #ifdef SQLITE_NO_SYNC
12983   "NO_SYNC",
12984 #endif
12985 #ifdef SQLITE_OMIT_ALTERTABLE
12986   "OMIT_ALTERTABLE",
12987 #endif
12988 #ifdef SQLITE_OMIT_ANALYZE
12989   "OMIT_ANALYZE",
12990 #endif
12991 #ifdef SQLITE_OMIT_ATTACH
12992   "OMIT_ATTACH",
12993 #endif
12994 #ifdef SQLITE_OMIT_AUTHORIZATION
12995   "OMIT_AUTHORIZATION",
12996 #endif
12997 #ifdef SQLITE_OMIT_AUTOINCREMENT
12998   "OMIT_AUTOINCREMENT",
12999 #endif
13000 #ifdef SQLITE_OMIT_AUTOINIT
13001   "OMIT_AUTOINIT",
13002 #endif
13003 #ifdef SQLITE_OMIT_AUTOMATIC_INDEX
13004   "OMIT_AUTOMATIC_INDEX",
13005 #endif
13006 #ifdef SQLITE_OMIT_AUTORESET
13007   "OMIT_AUTORESET",
13008 #endif
13009 #ifdef SQLITE_OMIT_AUTOVACUUM
13010   "OMIT_AUTOVACUUM",
13011 #endif
13012 #ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION
13013   "OMIT_BETWEEN_OPTIMIZATION",
13014 #endif
13015 #ifdef SQLITE_OMIT_BLOB_LITERAL
13016   "OMIT_BLOB_LITERAL",
13017 #endif
13018 #ifdef SQLITE_OMIT_BTREECOUNT
13019   "OMIT_BTREECOUNT",
13020 #endif
13021 #ifdef SQLITE_OMIT_BUILTIN_TEST
13022   "OMIT_BUILTIN_TEST",
13023 #endif
13024 #ifdef SQLITE_OMIT_CAST
13025   "OMIT_CAST",
13026 #endif
13027 #ifdef SQLITE_OMIT_CHECK
13028   "OMIT_CHECK",
13029 #endif
13030 #ifdef SQLITE_OMIT_COMPLETE
13031   "OMIT_COMPLETE",
13032 #endif
13033 #ifdef SQLITE_OMIT_COMPOUND_SELECT
13034   "OMIT_COMPOUND_SELECT",
13035 #endif
13036 #ifdef SQLITE_OMIT_DATETIME_FUNCS
13037   "OMIT_DATETIME_FUNCS",
13038 #endif
13039 #ifdef SQLITE_OMIT_DECLTYPE
13040   "OMIT_DECLTYPE",
13041 #endif
13042 #ifdef SQLITE_OMIT_DEPRECATED
13043   "OMIT_DEPRECATED",
13044 #endif
13045 #ifdef SQLITE_OMIT_DISKIO
13046   "OMIT_DISKIO",
13047 #endif
13048 #ifdef SQLITE_OMIT_EXPLAIN
13049   "OMIT_EXPLAIN",
13050 #endif
13051 #ifdef SQLITE_OMIT_FLAG_PRAGMAS
13052   "OMIT_FLAG_PRAGMAS",
13053 #endif
13054 #ifdef SQLITE_OMIT_FLOATING_POINT
13055   "OMIT_FLOATING_POINT",
13056 #endif
13057 #ifdef SQLITE_OMIT_FOREIGN_KEY
13058   "OMIT_FOREIGN_KEY",
13059 #endif
13060 #ifdef SQLITE_OMIT_GET_TABLE
13061   "OMIT_GET_TABLE",
13062 #endif
13063 #ifdef SQLITE_OMIT_INCRBLOB
13064   "OMIT_INCRBLOB",
13065 #endif
13066 #ifdef SQLITE_OMIT_INTEGRITY_CHECK
13067   "OMIT_INTEGRITY_CHECK",
13068 #endif
13069 #ifdef SQLITE_OMIT_LIKE_OPTIMIZATION
13070   "OMIT_LIKE_OPTIMIZATION",
13071 #endif
13072 #ifdef SQLITE_OMIT_LOAD_EXTENSION
13073   "OMIT_LOAD_EXTENSION",
13074 #endif
13075 #ifdef SQLITE_OMIT_LOCALTIME
13076   "OMIT_LOCALTIME",
13077 #endif
13078 #ifdef SQLITE_OMIT_LOOKASIDE
13079   "OMIT_LOOKASIDE",
13080 #endif
13081 #ifdef SQLITE_OMIT_MEMORYDB
13082   "OMIT_MEMORYDB",
13083 #endif
13084 #ifdef SQLITE_OMIT_OR_OPTIMIZATION
13085   "OMIT_OR_OPTIMIZATION",
13086 #endif
13087 #ifdef SQLITE_OMIT_PAGER_PRAGMAS
13088   "OMIT_PAGER_PRAGMAS",
13089 #endif
13090 #ifdef SQLITE_OMIT_PRAGMA
13091   "OMIT_PRAGMA",
13092 #endif
13093 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
13094   "OMIT_PROGRESS_CALLBACK",
13095 #endif
13096 #ifdef SQLITE_OMIT_QUICKBALANCE
13097   "OMIT_QUICKBALANCE",
13098 #endif
13099 #ifdef SQLITE_OMIT_REINDEX
13100   "OMIT_REINDEX",
13101 #endif
13102 #ifdef SQLITE_OMIT_SCHEMA_PRAGMAS
13103   "OMIT_SCHEMA_PRAGMAS",
13104 #endif
13105 #ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
13106   "OMIT_SCHEMA_VERSION_PRAGMAS",
13107 #endif
13108 #ifdef SQLITE_OMIT_SHARED_CACHE
13109   "OMIT_SHARED_CACHE",
13110 #endif
13111 #ifdef SQLITE_OMIT_SUBQUERY
13112   "OMIT_SUBQUERY",
13113 #endif
13114 #ifdef SQLITE_OMIT_TCL_VARIABLE
13115   "OMIT_TCL_VARIABLE",
13116 #endif
13117 #ifdef SQLITE_OMIT_TEMPDB
13118   "OMIT_TEMPDB",
13119 #endif
13120 #ifdef SQLITE_OMIT_TRACE
13121   "OMIT_TRACE",
13122 #endif
13123 #ifdef SQLITE_OMIT_TRIGGER
13124   "OMIT_TRIGGER",
13125 #endif
13126 #ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
13127   "OMIT_TRUNCATE_OPTIMIZATION",
13128 #endif
13129 #ifdef SQLITE_OMIT_UTF16
13130   "OMIT_UTF16",
13131 #endif
13132 #ifdef SQLITE_OMIT_VACUUM
13133   "OMIT_VACUUM",
13134 #endif
13135 #ifdef SQLITE_OMIT_VIEW
13136   "OMIT_VIEW",
13137 #endif
13138 #ifdef SQLITE_OMIT_VIRTUALTABLE
13139   "OMIT_VIRTUALTABLE",
13140 #endif
13141 #ifdef SQLITE_OMIT_WAL
13142   "OMIT_WAL",
13143 #endif
13144 #ifdef SQLITE_OMIT_WSD
13145   "OMIT_WSD",
13146 #endif
13147 #ifdef SQLITE_OMIT_XFER_OPT
13148   "OMIT_XFER_OPT",
13149 #endif
13150 #ifdef SQLITE_PERFORMANCE_TRACE
13151   "PERFORMANCE_TRACE",
13152 #endif
13153 #ifdef SQLITE_PROXY_DEBUG
13154   "PROXY_DEBUG",
13155 #endif
13156 #ifdef SQLITE_RTREE_INT_ONLY
13157   "RTREE_INT_ONLY",
13158 #endif
13159 #ifdef SQLITE_SECURE_DELETE
13160   "SECURE_DELETE",
13161 #endif
13162 #ifdef SQLITE_SMALL_STACK
13163   "SMALL_STACK",
13164 #endif
13165 #ifdef SQLITE_SOUNDEX
13166   "SOUNDEX",
13167 #endif
13168 #ifdef SQLITE_TCL
13169   "TCL",
13170 #endif
13171 #if defined(SQLITE_TEMP_STORE) && !defined(SQLITE_TEMP_STORE_xc)
13172   "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
13173 #endif
13174 #ifdef SQLITE_TEST
13175   "TEST",
13176 #endif
13177 #if defined(SQLITE_THREADSAFE)
13178   "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
13179 #endif
13180 #ifdef SQLITE_USE_ALLOCA
13181   "USE_ALLOCA",
13182 #endif
13183 #ifdef SQLITE_ZERO_MALLOC
13184   "ZERO_MALLOC"
13185 #endif
13186 };
13187
13188 /*
13189 ** Given the name of a compile-time option, return true if that option
13190 ** was used and false if not.
13191 **
13192 ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
13193 ** is not required for a match.
13194 */
13195 SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
13196   int i, n;
13197   if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
13198   n = sqlite3Strlen30(zOptName);
13199
13200   /* Since ArraySize(azCompileOpt) is normally in single digits, a
13201   ** linear search is adequate.  No need for a binary search. */
13202   for(i=0; i<ArraySize(azCompileOpt); i++){
13203     if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
13204      && sqlite3CtypeMap[(unsigned char)azCompileOpt[i][n]]==0
13205     ){
13206       return 1;
13207     }
13208   }
13209   return 0;
13210 }
13211
13212 /*
13213 ** Return the N-th compile-time option string.  If N is out of range,
13214 ** return a NULL pointer.
13215 */
13216 SQLITE_API const char *sqlite3_compileoption_get(int N){
13217   if( N>=0 && N<ArraySize(azCompileOpt) ){
13218     return azCompileOpt[N];
13219   }
13220   return 0;
13221 }
13222
13223 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
13224
13225 /************** End of ctime.c ***********************************************/
13226 /************** Begin file status.c ******************************************/
13227 /*
13228 ** 2008 June 18
13229 **
13230 ** The author disclaims copyright to this source code.  In place of
13231 ** a legal notice, here is a blessing:
13232 **
13233 **    May you do good and not evil.
13234 **    May you find forgiveness for yourself and forgive others.
13235 **    May you share freely, never taking more than you give.
13236 **
13237 *************************************************************************
13238 **
13239 ** This module implements the sqlite3_status() interface and related
13240 ** functionality.
13241 */
13242 /************** Include vdbeInt.h in the middle of status.c ******************/
13243 /************** Begin file vdbeInt.h *****************************************/
13244 /*
13245 ** 2003 September 6
13246 **
13247 ** The author disclaims copyright to this source code.  In place of
13248 ** a legal notice, here is a blessing:
13249 **
13250 **    May you do good and not evil.
13251 **    May you find forgiveness for yourself and forgive others.
13252 **    May you share freely, never taking more than you give.
13253 **
13254 *************************************************************************
13255 ** This is the header file for information that is private to the
13256 ** VDBE.  This information used to all be at the top of the single
13257 ** source code file "vdbe.c".  When that file became too big (over
13258 ** 6000 lines long) it was split up into several smaller files and
13259 ** this header information was factored out.
13260 */
13261 #ifndef _VDBEINT_H_
13262 #define _VDBEINT_H_
13263
13264 /*
13265 ** The maximum number of times that a statement will try to reparse
13266 ** itself before giving up and returning SQLITE_SCHEMA.
13267 */
13268 #ifndef SQLITE_MAX_SCHEMA_RETRY
13269 # define SQLITE_MAX_SCHEMA_RETRY 50
13270 #endif
13271
13272 /*
13273 ** SQL is translated into a sequence of instructions to be
13274 ** executed by a virtual machine.  Each instruction is an instance
13275 ** of the following structure.
13276 */
13277 typedef struct VdbeOp Op;
13278
13279 /*
13280 ** Boolean values
13281 */
13282 typedef unsigned char Bool;
13283
13284 /* Opaque type used by code in vdbesort.c */
13285 typedef struct VdbeSorter VdbeSorter;
13286
13287 /* Opaque type used by the explainer */
13288 typedef struct Explain Explain;
13289
13290 /*
13291 ** A cursor is a pointer into a single BTree within a database file.
13292 ** The cursor can seek to a BTree entry with a particular key, or
13293 ** loop over all entries of the Btree.  You can also insert new BTree
13294 ** entries or retrieve the key or data from the entry that the cursor
13295 ** is currently pointing to.
13296 ** 
13297 ** Every cursor that the virtual machine has open is represented by an
13298 ** instance of the following structure.
13299 */
13300 struct VdbeCursor {
13301   BtCursor *pCursor;    /* The cursor structure of the backend */
13302   Btree *pBt;           /* Separate file holding temporary table */
13303   KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
13304   int iDb;              /* Index of cursor database in db->aDb[] (or -1) */
13305   int pseudoTableReg;   /* Register holding pseudotable content. */
13306   int nField;           /* Number of fields in the header */
13307   Bool zeroed;          /* True if zeroed out and ready for reuse */
13308   Bool rowidIsValid;    /* True if lastRowid is valid */
13309   Bool atFirst;         /* True if pointing to first entry */
13310   Bool useRandomRowid;  /* Generate new record numbers semi-randomly */
13311   Bool nullRow;         /* True if pointing to a row with no data */
13312   Bool deferredMoveto;  /* A call to sqlite3BtreeMoveto() is needed */
13313   Bool isTable;         /* True if a table requiring integer keys */
13314   Bool isIndex;         /* True if an index containing keys only - no data */
13315   Bool isOrdered;       /* True if the underlying table is BTREE_UNORDERED */
13316   Bool isSorter;        /* True if a new-style sorter */
13317   Bool multiPseudo;     /* Multi-register pseudo-cursor */
13318   sqlite3_vtab_cursor *pVtabCursor;  /* The cursor for a virtual table */
13319   const sqlite3_module *pModule;     /* Module for cursor pVtabCursor */
13320   i64 seqCount;         /* Sequence counter */
13321   i64 movetoTarget;     /* Argument to the deferred sqlite3BtreeMoveto() */
13322   i64 lastRowid;        /* Last rowid from a Next or NextIdx operation */
13323   VdbeSorter *pSorter;  /* Sorter object for OP_SorterOpen cursors */
13324
13325   /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or 
13326   ** OP_IsUnique opcode on this cursor. */
13327   int seekResult;
13328
13329   /* Cached information about the header for the data record that the
13330   ** cursor is currently pointing to.  Only valid if cacheStatus matches
13331   ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of
13332   ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
13333   ** the cache is out of date.
13334   **
13335   ** aRow might point to (ephemeral) data for the current row, or it might
13336   ** be NULL.
13337   */
13338   u32 cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
13339   int payloadSize;      /* Total number of bytes in the record */
13340   u32 *aType;           /* Type values for all entries in the record */
13341   u32 *aOffset;         /* Cached offsets to the start of each columns data */
13342   u8 *aRow;             /* Data for the current row, if all on one page */
13343 };
13344 typedef struct VdbeCursor VdbeCursor;
13345
13346 /*
13347 ** When a sub-program is executed (OP_Program), a structure of this type
13348 ** is allocated to store the current value of the program counter, as
13349 ** well as the current memory cell array and various other frame specific
13350 ** values stored in the Vdbe struct. When the sub-program is finished, 
13351 ** these values are copied back to the Vdbe from the VdbeFrame structure,
13352 ** restoring the state of the VM to as it was before the sub-program
13353 ** began executing.
13354 **
13355 ** The memory for a VdbeFrame object is allocated and managed by a memory
13356 ** cell in the parent (calling) frame. When the memory cell is deleted or
13357 ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
13358 ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
13359 ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
13360 ** this instead of deleting the VdbeFrame immediately is to avoid recursive
13361 ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
13362 ** child frame are released.
13363 **
13364 ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
13365 ** set to NULL if the currently executing frame is the main program.
13366 */
13367 typedef struct VdbeFrame VdbeFrame;
13368 struct VdbeFrame {
13369   Vdbe *v;                /* VM this frame belongs to */
13370   VdbeFrame *pParent;     /* Parent of this frame, or NULL if parent is main */
13371   Op *aOp;                /* Program instructions for parent frame */
13372   Mem *aMem;              /* Array of memory cells for parent frame */
13373   u8 *aOnceFlag;          /* Array of OP_Once flags for parent frame */
13374   VdbeCursor **apCsr;     /* Array of Vdbe cursors for parent frame */
13375   void *token;            /* Copy of SubProgram.token */
13376   i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */
13377   int nCursor;            /* Number of entries in apCsr */
13378   int pc;                 /* Program Counter in parent (calling) frame */
13379   int nOp;                /* Size of aOp array */
13380   int nMem;               /* Number of entries in aMem */
13381   int nOnceFlag;          /* Number of entries in aOnceFlag */
13382   int nChildMem;          /* Number of memory cells for child frame */
13383   int nChildCsr;          /* Number of cursors for child frame */
13384   int nChange;            /* Statement changes (Vdbe.nChanges)     */
13385 };
13386
13387 #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
13388
13389 /*
13390 ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
13391 */
13392 #define CACHE_STALE 0
13393
13394 /*
13395 ** Internally, the vdbe manipulates nearly all SQL values as Mem
13396 ** structures. Each Mem struct may cache multiple representations (string,
13397 ** integer etc.) of the same value.
13398 */
13399 struct Mem {
13400   sqlite3 *db;        /* The associated database connection */
13401   char *z;            /* String or BLOB value */
13402   double r;           /* Real value */
13403   union {
13404     i64 i;              /* Integer value used when MEM_Int is set in flags */
13405     int nZero;          /* Used when bit MEM_Zero is set in flags */
13406     FuncDef *pDef;      /* Used only when flags==MEM_Agg */
13407     RowSet *pRowSet;    /* Used only when flags==MEM_RowSet */
13408     VdbeFrame *pFrame;  /* Used when flags==MEM_Frame */
13409   } u;
13410   int n;              /* Number of characters in string value, excluding '\0' */
13411   u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
13412   u8  type;           /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
13413   u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
13414 #ifdef SQLITE_DEBUG
13415   Mem *pScopyFrom;    /* This Mem is a shallow copy of pScopyFrom */
13416   void *pFiller;      /* So that sizeof(Mem) is a multiple of 8 */
13417 #endif
13418   void (*xDel)(void *);  /* If not null, call this function to delete Mem.z */
13419   char *zMalloc;      /* Dynamic buffer allocated by sqlite3_malloc() */
13420 };
13421
13422 /* One or more of the following flags are set to indicate the validOK
13423 ** representations of the value stored in the Mem struct.
13424 **
13425 ** If the MEM_Null flag is set, then the value is an SQL NULL value.
13426 ** No other flags may be set in this case.
13427 **
13428 ** If the MEM_Str flag is set then Mem.z points at a string representation.
13429 ** Usually this is encoded in the same unicode encoding as the main
13430 ** database (see below for exceptions). If the MEM_Term flag is also
13431 ** set, then the string is nul terminated. The MEM_Int and MEM_Real 
13432 ** flags may coexist with the MEM_Str flag.
13433 */
13434 #define MEM_Null      0x0001   /* Value is NULL */
13435 #define MEM_Str       0x0002   /* Value is a string */
13436 #define MEM_Int       0x0004   /* Value is an integer */
13437 #define MEM_Real      0x0008   /* Value is a real number */
13438 #define MEM_Blob      0x0010   /* Value is a BLOB */
13439 #define MEM_RowSet    0x0020   /* Value is a RowSet object */
13440 #define MEM_Frame     0x0040   /* Value is a VdbeFrame object */
13441 #define MEM_Invalid   0x0080   /* Value is undefined */
13442 #define MEM_Cleared   0x0100   /* NULL set by OP_Null, not from data */
13443 #define MEM_TypeMask  0x01ff   /* Mask of type bits */
13444
13445
13446 /* Whenever Mem contains a valid string or blob representation, one of
13447 ** the following flags must be set to determine the memory management
13448 ** policy for Mem.z.  The MEM_Term flag tells us whether or not the
13449 ** string is \000 or \u0000 terminated
13450 */
13451 #define MEM_Term      0x0200   /* String rep is nul terminated */
13452 #define MEM_Dyn       0x0400   /* Need to call sqliteFree() on Mem.z */
13453 #define MEM_Static    0x0800   /* Mem.z points to a static string */
13454 #define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
13455 #define MEM_Agg       0x2000   /* Mem.z points to an agg function context */
13456 #define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */
13457 #ifdef SQLITE_OMIT_INCRBLOB
13458   #undef MEM_Zero
13459   #define MEM_Zero 0x0000
13460 #endif
13461
13462 /*
13463 ** Clear any existing type flags from a Mem and replace them with f
13464 */
13465 #define MemSetTypeFlag(p, f) \
13466    ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
13467
13468 /*
13469 ** Return true if a memory cell is not marked as invalid.  This macro
13470 ** is for use inside assert() statements only.
13471 */
13472 #ifdef SQLITE_DEBUG
13473 #define memIsValid(M)  ((M)->flags & MEM_Invalid)==0
13474 #endif
13475
13476
13477 /* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
13478 ** additional information about auxiliary information bound to arguments
13479 ** of the function.  This is used to implement the sqlite3_get_auxdata()
13480 ** and sqlite3_set_auxdata() APIs.  The "auxdata" is some auxiliary data
13481 ** that can be associated with a constant argument to a function.  This
13482 ** allows functions such as "regexp" to compile their constant regular
13483 ** expression argument once and reused the compiled code for multiple
13484 ** invocations.
13485 */
13486 struct VdbeFunc {
13487   FuncDef *pFunc;               /* The definition of the function */
13488   int nAux;                     /* Number of entries allocated for apAux[] */
13489   struct AuxData {
13490     void *pAux;                   /* Aux data for the i-th argument */
13491     void (*xDelete)(void *);      /* Destructor for the aux data */
13492   } apAux[1];                   /* One slot for each function argument */
13493 };
13494
13495 /*
13496 ** The "context" argument for a installable function.  A pointer to an
13497 ** instance of this structure is the first argument to the routines used
13498 ** implement the SQL functions.
13499 **
13500 ** There is a typedef for this structure in sqlite.h.  So all routines,
13501 ** even the public interface to SQLite, can use a pointer to this structure.
13502 ** But this file is the only place where the internal details of this
13503 ** structure are known.
13504 **
13505 ** This structure is defined inside of vdbeInt.h because it uses substructures
13506 ** (Mem) which are only defined there.
13507 */
13508 struct sqlite3_context {
13509   FuncDef *pFunc;       /* Pointer to function information.  MUST BE FIRST */
13510   VdbeFunc *pVdbeFunc;  /* Auxilary data, if created. */
13511   Mem s;                /* The return value is stored here */
13512   Mem *pMem;            /* Memory cell used to store aggregate context */
13513   CollSeq *pColl;       /* Collating sequence */
13514   int isError;          /* Error code returned by the function. */
13515   int skipFlag;         /* Skip skip accumulator loading if true */
13516 };
13517
13518 /*
13519 ** An Explain object accumulates indented output which is helpful
13520 ** in describing recursive data structures.
13521 */
13522 struct Explain {
13523   Vdbe *pVdbe;       /* Attach the explanation to this Vdbe */
13524   StrAccum str;      /* The string being accumulated */
13525   int nIndent;       /* Number of elements in aIndent */
13526   u16 aIndent[100];  /* Levels of indentation */
13527   char zBase[100];   /* Initial space */
13528 };
13529
13530 /* A bitfield type for use inside of structures.  Always follow with :N where
13531 ** N is the number of bits.
13532 */
13533 typedef unsigned bft;  /* Bit Field Type */
13534
13535 /*
13536 ** An instance of the virtual machine.  This structure contains the complete
13537 ** state of the virtual machine.
13538 **
13539 ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
13540 ** is really a pointer to an instance of this structure.
13541 **
13542 ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
13543 ** any virtual table method invocations made by the vdbe program. It is
13544 ** set to 2 for xDestroy method calls and 1 for all other methods. This
13545 ** variable is used for two purposes: to allow xDestroy methods to execute
13546 ** "DROP TABLE" statements and to prevent some nasty side effects of
13547 ** malloc failure when SQLite is invoked recursively by a virtual table 
13548 ** method function.
13549 */
13550 struct Vdbe {
13551   sqlite3 *db;            /* The database connection that owns this statement */
13552   Op *aOp;                /* Space to hold the virtual machine's program */
13553   Mem *aMem;              /* The memory locations */
13554   Mem **apArg;            /* Arguments to currently executing user function */
13555   Mem *aColName;          /* Column names to return */
13556   Mem *pResultSet;        /* Pointer to an array of results */
13557   int nMem;               /* Number of memory locations currently allocated */
13558   int nOp;                /* Number of instructions in the program */
13559   int nOpAlloc;           /* Number of slots allocated for aOp[] */
13560   int nLabel;             /* Number of labels used */
13561   int *aLabel;            /* Space to hold the labels */
13562   u16 nResColumn;         /* Number of columns in one row of the result set */
13563   int nCursor;            /* Number of slots in apCsr[] */
13564   u32 magic;              /* Magic number for sanity checking */
13565   char *zErrMsg;          /* Error message written here */
13566   Vdbe *pPrev,*pNext;     /* Linked list of VDBEs with the same Vdbe.db */
13567   VdbeCursor **apCsr;     /* One element of this array for each open cursor */
13568   Mem *aVar;              /* Values for the OP_Variable opcode. */
13569   char **azVar;           /* Name of variables */
13570   ynVar nVar;             /* Number of entries in aVar[] */
13571   ynVar nzVar;            /* Number of entries in azVar[] */
13572   u32 cacheCtr;           /* VdbeCursor row cache generation counter */
13573   int pc;                 /* The program counter */
13574   int rc;                 /* Value to return */
13575   u8 errorAction;         /* Recovery action to do in case of an error */
13576   u8 minWriteFileFormat;  /* Minimum file format for writable database files */
13577   bft explain:2;          /* True if EXPLAIN present on SQL command */
13578   bft inVtabMethod:2;     /* See comments above */
13579   bft changeCntOn:1;      /* True to update the change-counter */
13580   bft expired:1;          /* True if the VM needs to be recompiled */
13581   bft runOnlyOnce:1;      /* Automatically expire on reset */
13582   bft usesStmtJournal:1;  /* True if uses a statement journal */
13583   bft readOnly:1;         /* True for read-only statements */
13584   bft isPrepareV2:1;      /* True if prepared with prepare_v2() */
13585   bft doingRerun:1;       /* True if rerunning after an auto-reprepare */
13586   int nChange;            /* Number of db changes made since last reset */
13587   yDbMask btreeMask;      /* Bitmask of db->aDb[] entries referenced */
13588   yDbMask lockMask;       /* Subset of btreeMask that requires a lock */
13589   int iStatement;         /* Statement number (or 0 if has not opened stmt) */
13590   int aCounter[3];        /* Counters used by sqlite3_stmt_status() */
13591 #ifndef SQLITE_OMIT_TRACE
13592   i64 startTime;          /* Time when query started - used for profiling */
13593 #endif
13594   i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
13595   i64 nStmtDefCons;       /* Number of def. constraints when stmt started */
13596   char *zSql;             /* Text of the SQL statement that generated this */
13597   void *pFree;            /* Free this when deleting the vdbe */
13598 #ifdef SQLITE_DEBUG
13599   FILE *trace;            /* Write an execution trace here, if not NULL */
13600 #endif
13601 #ifdef SQLITE_ENABLE_TREE_EXPLAIN
13602   Explain *pExplain;      /* The explainer */
13603   char *zExplain;         /* Explanation of data structures */
13604 #endif
13605   VdbeFrame *pFrame;      /* Parent frame */
13606   VdbeFrame *pDelFrame;   /* List of frame objects to free on VM reset */
13607   int nFrame;             /* Number of frames in pFrame list */
13608   u32 expmask;            /* Binding to these vars invalidates VM */
13609   SubProgram *pProgram;   /* Linked list of all sub-programs used by VM */
13610   int nOnceFlag;          /* Size of array aOnceFlag[] */
13611   u8 *aOnceFlag;          /* Flags for OP_Once */
13612 };
13613
13614 /*
13615 ** The following are allowed values for Vdbe.magic
13616 */
13617 #define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
13618 #define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
13619 #define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
13620 #define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
13621
13622 /*
13623 ** Function prototypes
13624 */
13625 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
13626 void sqliteVdbePopStack(Vdbe*,int);
13627 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
13628 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
13629 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
13630 #endif
13631 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
13632 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
13633 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
13634 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
13635 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
13636
13637 int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
13638 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
13639 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *);
13640 SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
13641 SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
13642 SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
13643 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
13644 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
13645 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
13646 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
13647 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
13648 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
13649 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
13650 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
13651 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
13652 #ifdef SQLITE_OMIT_FLOATING_POINT
13653 # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
13654 #else
13655 SQLITE_PRIVATE   void sqlite3VdbeMemSetDouble(Mem*, double);
13656 #endif
13657 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
13658 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
13659 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
13660 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
13661 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
13662 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
13663 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
13664 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
13665 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
13666 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
13667 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
13668 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
13669 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
13670 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
13671 #define VdbeMemRelease(X)  \
13672   if((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame)) \
13673     sqlite3VdbeMemReleaseExternal(X);
13674 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
13675 SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
13676 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
13677 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
13678 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
13679 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
13680 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem);
13681 SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
13682
13683 SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, VdbeCursor *);
13684 SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
13685 SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
13686 SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *, int *);
13687 SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *, const VdbeCursor *, int *);
13688 SQLITE_PRIVATE int sqlite3VdbeSorterWrite(sqlite3 *, const VdbeCursor *, Mem *);
13689 SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int *);
13690
13691 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
13692 SQLITE_PRIVATE   void sqlite3VdbeEnter(Vdbe*);
13693 SQLITE_PRIVATE   void sqlite3VdbeLeave(Vdbe*);
13694 #else
13695 # define sqlite3VdbeEnter(X)
13696 # define sqlite3VdbeLeave(X)
13697 #endif
13698
13699 #ifdef SQLITE_DEBUG
13700 SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
13701 #endif
13702
13703 #ifndef SQLITE_OMIT_FOREIGN_KEY
13704 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
13705 #else
13706 # define sqlite3VdbeCheckFk(p,i) 0
13707 #endif
13708
13709 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
13710 #ifdef SQLITE_DEBUG
13711 SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
13712 SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
13713 #endif
13714 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
13715
13716 #ifndef SQLITE_OMIT_INCRBLOB
13717 SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
13718   #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
13719 #else
13720   #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
13721   #define ExpandBlob(P) SQLITE_OK
13722 #endif
13723
13724 #endif /* !defined(_VDBEINT_H_) */
13725
13726 /************** End of vdbeInt.h *********************************************/
13727 /************** Continuing where we left off in status.c *********************/
13728
13729 /*
13730 ** Variables in which to record status information.
13731 */
13732 typedef struct sqlite3StatType sqlite3StatType;
13733 static SQLITE_WSD struct sqlite3StatType {
13734   int nowValue[10];         /* Current value */
13735   int mxValue[10];          /* Maximum value */
13736 } sqlite3Stat = { {0,}, {0,} };
13737
13738
13739 /* The "wsdStat" macro will resolve to the status information
13740 ** state vector.  If writable static data is unsupported on the target,
13741 ** we have to locate the state vector at run-time.  In the more common
13742 ** case where writable static data is supported, wsdStat can refer directly
13743 ** to the "sqlite3Stat" state vector declared above.
13744 */
13745 #ifdef SQLITE_OMIT_WSD
13746 # define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
13747 # define wsdStat x[0]
13748 #else
13749 # define wsdStatInit
13750 # define wsdStat sqlite3Stat
13751 #endif
13752
13753 /*
13754 ** Return the current value of a status parameter.
13755 */
13756 SQLITE_PRIVATE int sqlite3StatusValue(int op){
13757   wsdStatInit;
13758   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
13759   return wsdStat.nowValue[op];
13760 }
13761
13762 /*
13763 ** Add N to the value of a status record.  It is assumed that the
13764 ** caller holds appropriate locks.
13765 */
13766 SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
13767   wsdStatInit;
13768   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
13769   wsdStat.nowValue[op] += N;
13770   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
13771     wsdStat.mxValue[op] = wsdStat.nowValue[op];
13772   }
13773 }
13774
13775 /*
13776 ** Set the value of a status to X.
13777 */
13778 SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
13779   wsdStatInit;
13780   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
13781   wsdStat.nowValue[op] = X;
13782   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
13783     wsdStat.mxValue[op] = wsdStat.nowValue[op];
13784   }
13785 }
13786
13787 /*
13788 ** Query status information.
13789 **
13790 ** This implementation assumes that reading or writing an aligned
13791 ** 32-bit integer is an atomic operation.  If that assumption is not true,
13792 ** then this routine is not threadsafe.
13793 */
13794 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
13795   wsdStatInit;
13796   if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
13797     return SQLITE_MISUSE_BKPT;
13798   }
13799   *pCurrent = wsdStat.nowValue[op];
13800   *pHighwater = wsdStat.mxValue[op];
13801   if( resetFlag ){
13802     wsdStat.mxValue[op] = wsdStat.nowValue[op];
13803   }
13804   return SQLITE_OK;
13805 }
13806
13807 /*
13808 ** Query status information for a single database connection
13809 */
13810 SQLITE_API int sqlite3_db_status(
13811   sqlite3 *db,          /* The database connection whose status is desired */
13812   int op,               /* Status verb */
13813   int *pCurrent,        /* Write current value here */
13814   int *pHighwater,      /* Write high-water mark here */
13815   int resetFlag         /* Reset high-water mark if true */
13816 ){
13817   int rc = SQLITE_OK;   /* Return code */
13818   sqlite3_mutex_enter(db->mutex);
13819   switch( op ){
13820     case SQLITE_DBSTATUS_LOOKASIDE_USED: {
13821       *pCurrent = db->lookaside.nOut;
13822       *pHighwater = db->lookaside.mxOut;
13823       if( resetFlag ){
13824         db->lookaside.mxOut = db->lookaside.nOut;
13825       }
13826       break;
13827     }
13828
13829     case SQLITE_DBSTATUS_LOOKASIDE_HIT:
13830     case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
13831     case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
13832       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
13833       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
13834       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
13835       assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
13836       assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
13837       *pCurrent = 0;
13838       *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
13839       if( resetFlag ){
13840         db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
13841       }
13842       break;
13843     }
13844
13845     /* 
13846     ** Return an approximation for the amount of memory currently used
13847     ** by all pagers associated with the given database connection.  The
13848     ** highwater mark is meaningless and is returned as zero.
13849     */
13850     case SQLITE_DBSTATUS_CACHE_USED: {
13851       int totalUsed = 0;
13852       int i;
13853       sqlite3BtreeEnterAll(db);
13854       for(i=0; i<db->nDb; i++){
13855         Btree *pBt = db->aDb[i].pBt;
13856         if( pBt ){
13857           Pager *pPager = sqlite3BtreePager(pBt);
13858           totalUsed += sqlite3PagerMemUsed(pPager);
13859         }
13860       }
13861       sqlite3BtreeLeaveAll(db);
13862       *pCurrent = totalUsed;
13863       *pHighwater = 0;
13864       break;
13865     }
13866
13867     /*
13868     ** *pCurrent gets an accurate estimate of the amount of memory used
13869     ** to store the schema for all databases (main, temp, and any ATTACHed
13870     ** databases.  *pHighwater is set to zero.
13871     */
13872     case SQLITE_DBSTATUS_SCHEMA_USED: {
13873       int i;                      /* Used to iterate through schemas */
13874       int nByte = 0;              /* Used to accumulate return value */
13875
13876       sqlite3BtreeEnterAll(db);
13877       db->pnBytesFreed = &nByte;
13878       for(i=0; i<db->nDb; i++){
13879         Schema *pSchema = db->aDb[i].pSchema;
13880         if( ALWAYS(pSchema!=0) ){
13881           HashElem *p;
13882
13883           nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
13884               pSchema->tblHash.count 
13885             + pSchema->trigHash.count
13886             + pSchema->idxHash.count
13887             + pSchema->fkeyHash.count
13888           );
13889           nByte += sqlite3MallocSize(pSchema->tblHash.ht);
13890           nByte += sqlite3MallocSize(pSchema->trigHash.ht);
13891           nByte += sqlite3MallocSize(pSchema->idxHash.ht);
13892           nByte += sqlite3MallocSize(pSchema->fkeyHash.ht);
13893
13894           for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
13895             sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
13896           }
13897           for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
13898             sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
13899           }
13900         }
13901       }
13902       db->pnBytesFreed = 0;
13903       sqlite3BtreeLeaveAll(db);
13904
13905       *pHighwater = 0;
13906       *pCurrent = nByte;
13907       break;
13908     }
13909
13910     /*
13911     ** *pCurrent gets an accurate estimate of the amount of memory used
13912     ** to store all prepared statements.
13913     ** *pHighwater is set to zero.
13914     */
13915     case SQLITE_DBSTATUS_STMT_USED: {
13916       struct Vdbe *pVdbe;         /* Used to iterate through VMs */
13917       int nByte = 0;              /* Used to accumulate return value */
13918
13919       db->pnBytesFreed = &nByte;
13920       for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
13921         sqlite3VdbeClearObject(db, pVdbe);
13922         sqlite3DbFree(db, pVdbe);
13923       }
13924       db->pnBytesFreed = 0;
13925
13926       *pHighwater = 0;
13927       *pCurrent = nByte;
13928
13929       break;
13930     }
13931
13932     /*
13933     ** Set *pCurrent to the total cache hits or misses encountered by all
13934     ** pagers the database handle is connected to. *pHighwater is always set 
13935     ** to zero.
13936     */
13937     case SQLITE_DBSTATUS_CACHE_HIT:
13938     case SQLITE_DBSTATUS_CACHE_MISS:
13939     case SQLITE_DBSTATUS_CACHE_WRITE:{
13940       int i;
13941       int nRet = 0;
13942       assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
13943       assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
13944
13945       for(i=0; i<db->nDb; i++){
13946         if( db->aDb[i].pBt ){
13947           Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
13948           sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
13949         }
13950       }
13951       *pHighwater = 0;
13952       *pCurrent = nRet;
13953       break;
13954     }
13955
13956     default: {
13957       rc = SQLITE_ERROR;
13958     }
13959   }
13960   sqlite3_mutex_leave(db->mutex);
13961   return rc;
13962 }
13963
13964 /************** End of status.c **********************************************/
13965 /************** Begin file date.c ********************************************/
13966 /*
13967 ** 2003 October 31
13968 **
13969 ** The author disclaims copyright to this source code.  In place of
13970 ** a legal notice, here is a blessing:
13971 **
13972 **    May you do good and not evil.
13973 **    May you find forgiveness for yourself and forgive others.
13974 **    May you share freely, never taking more than you give.
13975 **
13976 *************************************************************************
13977 ** This file contains the C functions that implement date and time
13978 ** functions for SQLite.  
13979 **
13980 ** There is only one exported symbol in this file - the function
13981 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
13982 ** All other code has file scope.
13983 **
13984 ** SQLite processes all times and dates as Julian Day numbers.  The
13985 ** dates and times are stored as the number of days since noon
13986 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
13987 ** calendar system. 
13988 **
13989 ** 1970-01-01 00:00:00 is JD 2440587.5
13990 ** 2000-01-01 00:00:00 is JD 2451544.5
13991 **
13992 ** This implemention requires years to be expressed as a 4-digit number
13993 ** which means that only dates between 0000-01-01 and 9999-12-31 can
13994 ** be represented, even though julian day numbers allow a much wider
13995 ** range of dates.
13996 **
13997 ** The Gregorian calendar system is used for all dates and times,
13998 ** even those that predate the Gregorian calendar.  Historians usually
13999 ** use the Julian calendar for dates prior to 1582-10-15 and for some
14000 ** dates afterwards, depending on locale.  Beware of this difference.
14001 **
14002 ** The conversion algorithms are implemented based on descriptions
14003 ** in the following text:
14004 **
14005 **      Jean Meeus
14006 **      Astronomical Algorithms, 2nd Edition, 1998
14007 **      ISBM 0-943396-61-1
14008 **      Willmann-Bell, Inc
14009 **      Richmond, Virginia (USA)
14010 */
14011 /* #include <stdlib.h> */
14012 /* #include <assert.h> */
14013 #include <time.h>
14014
14015 #ifndef SQLITE_OMIT_DATETIME_FUNCS
14016
14017
14018 /*
14019 ** A structure for holding a single date and time.
14020 */
14021 typedef struct DateTime DateTime;
14022 struct DateTime {
14023   sqlite3_int64 iJD; /* The julian day number times 86400000 */
14024   int Y, M, D;       /* Year, month, and day */
14025   int h, m;          /* Hour and minutes */
14026   int tz;            /* Timezone offset in minutes */
14027   double s;          /* Seconds */
14028   char validYMD;     /* True (1) if Y,M,D are valid */
14029   char validHMS;     /* True (1) if h,m,s are valid */
14030   char validJD;      /* True (1) if iJD is valid */
14031   char validTZ;      /* True (1) if tz is valid */
14032 };
14033
14034
14035 /*
14036 ** Convert zDate into one or more integers.  Additional arguments
14037 ** come in groups of 5 as follows:
14038 **
14039 **       N       number of digits in the integer
14040 **       min     minimum allowed value of the integer
14041 **       max     maximum allowed value of the integer
14042 **       nextC   first character after the integer
14043 **       pVal    where to write the integers value.
14044 **
14045 ** Conversions continue until one with nextC==0 is encountered.
14046 ** The function returns the number of successful conversions.
14047 */
14048 static int getDigits(const char *zDate, ...){
14049   va_list ap;
14050   int val;
14051   int N;
14052   int min;
14053   int max;
14054   int nextC;
14055   int *pVal;
14056   int cnt = 0;
14057   va_start(ap, zDate);
14058   do{
14059     N = va_arg(ap, int);
14060     min = va_arg(ap, int);
14061     max = va_arg(ap, int);
14062     nextC = va_arg(ap, int);
14063     pVal = va_arg(ap, int*);
14064     val = 0;
14065     while( N-- ){
14066       if( !sqlite3Isdigit(*zDate) ){
14067         goto end_getDigits;
14068       }
14069       val = val*10 + *zDate - '0';
14070       zDate++;
14071     }
14072     if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
14073       goto end_getDigits;
14074     }
14075     *pVal = val;
14076     zDate++;
14077     cnt++;
14078   }while( nextC );
14079 end_getDigits:
14080   va_end(ap);
14081   return cnt;
14082 }
14083
14084 /*
14085 ** Parse a timezone extension on the end of a date-time.
14086 ** The extension is of the form:
14087 **
14088 **        (+/-)HH:MM
14089 **
14090 ** Or the "zulu" notation:
14091 **
14092 **        Z
14093 **
14094 ** If the parse is successful, write the number of minutes
14095 ** of change in p->tz and return 0.  If a parser error occurs,
14096 ** return non-zero.
14097 **
14098 ** A missing specifier is not considered an error.
14099 */
14100 static int parseTimezone(const char *zDate, DateTime *p){
14101   int sgn = 0;
14102   int nHr, nMn;
14103   int c;
14104   while( sqlite3Isspace(*zDate) ){ zDate++; }
14105   p->tz = 0;
14106   c = *zDate;
14107   if( c=='-' ){
14108     sgn = -1;
14109   }else if( c=='+' ){
14110     sgn = +1;
14111   }else if( c=='Z' || c=='z' ){
14112     zDate++;
14113     goto zulu_time;
14114   }else{
14115     return c!=0;
14116   }
14117   zDate++;
14118   if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
14119     return 1;
14120   }
14121   zDate += 5;
14122   p->tz = sgn*(nMn + nHr*60);
14123 zulu_time:
14124   while( sqlite3Isspace(*zDate) ){ zDate++; }
14125   return *zDate!=0;
14126 }
14127
14128 /*
14129 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
14130 ** The HH, MM, and SS must each be exactly 2 digits.  The
14131 ** fractional seconds FFFF can be one or more digits.
14132 **
14133 ** Return 1 if there is a parsing error and 0 on success.
14134 */
14135 static int parseHhMmSs(const char *zDate, DateTime *p){
14136   int h, m, s;
14137   double ms = 0.0;
14138   if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
14139     return 1;
14140   }
14141   zDate += 5;
14142   if( *zDate==':' ){
14143     zDate++;
14144     if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
14145       return 1;
14146     }
14147     zDate += 2;
14148     if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
14149       double rScale = 1.0;
14150       zDate++;
14151       while( sqlite3Isdigit(*zDate) ){
14152         ms = ms*10.0 + *zDate - '0';
14153         rScale *= 10.0;
14154         zDate++;
14155       }
14156       ms /= rScale;
14157     }
14158   }else{
14159     s = 0;
14160   }
14161   p->validJD = 0;
14162   p->validHMS = 1;
14163   p->h = h;
14164   p->m = m;
14165   p->s = s + ms;
14166   if( parseTimezone(zDate, p) ) return 1;
14167   p->validTZ = (p->tz!=0)?1:0;
14168   return 0;
14169 }
14170
14171 /*
14172 ** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
14173 ** that the YYYY-MM-DD is according to the Gregorian calendar.
14174 **
14175 ** Reference:  Meeus page 61
14176 */
14177 static void computeJD(DateTime *p){
14178   int Y, M, D, A, B, X1, X2;
14179
14180   if( p->validJD ) return;
14181   if( p->validYMD ){
14182     Y = p->Y;
14183     M = p->M;
14184     D = p->D;
14185   }else{
14186     Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
14187     M = 1;
14188     D = 1;
14189   }
14190   if( M<=2 ){
14191     Y--;
14192     M += 12;
14193   }
14194   A = Y/100;
14195   B = 2 - A + (A/4);
14196   X1 = 36525*(Y+4716)/100;
14197   X2 = 306001*(M+1)/10000;
14198   p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
14199   p->validJD = 1;
14200   if( p->validHMS ){
14201     p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
14202     if( p->validTZ ){
14203       p->iJD -= p->tz*60000;
14204       p->validYMD = 0;
14205       p->validHMS = 0;
14206       p->validTZ = 0;
14207     }
14208   }
14209 }
14210
14211 /*
14212 ** Parse dates of the form
14213 **
14214 **     YYYY-MM-DD HH:MM:SS.FFF
14215 **     YYYY-MM-DD HH:MM:SS
14216 **     YYYY-MM-DD HH:MM
14217 **     YYYY-MM-DD
14218 **
14219 ** Write the result into the DateTime structure and return 0
14220 ** on success and 1 if the input string is not a well-formed
14221 ** date.
14222 */
14223 static int parseYyyyMmDd(const char *zDate, DateTime *p){
14224   int Y, M, D, neg;
14225
14226   if( zDate[0]=='-' ){
14227     zDate++;
14228     neg = 1;
14229   }else{
14230     neg = 0;
14231   }
14232   if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
14233     return 1;
14234   }
14235   zDate += 10;
14236   while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
14237   if( parseHhMmSs(zDate, p)==0 ){
14238     /* We got the time */
14239   }else if( *zDate==0 ){
14240     p->validHMS = 0;
14241   }else{
14242     return 1;
14243   }
14244   p->validJD = 0;
14245   p->validYMD = 1;
14246   p->Y = neg ? -Y : Y;
14247   p->M = M;
14248   p->D = D;
14249   if( p->validTZ ){
14250     computeJD(p);
14251   }
14252   return 0;
14253 }
14254
14255 /*
14256 ** Set the time to the current time reported by the VFS.
14257 **
14258 ** Return the number of errors.
14259 */
14260 static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
14261   sqlite3 *db = sqlite3_context_db_handle(context);
14262   if( sqlite3OsCurrentTimeInt64(db->pVfs, &p->iJD)==SQLITE_OK ){
14263     p->validJD = 1;
14264     return 0;
14265   }else{
14266     return 1;
14267   }
14268 }
14269
14270 /*
14271 ** Attempt to parse the given string into a Julian Day Number.  Return
14272 ** the number of errors.
14273 **
14274 ** The following are acceptable forms for the input string:
14275 **
14276 **      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
14277 **      DDDD.DD 
14278 **      now
14279 **
14280 ** In the first form, the +/-HH:MM is always optional.  The fractional
14281 ** seconds extension (the ".FFF") is optional.  The seconds portion
14282 ** (":SS.FFF") is option.  The year and date can be omitted as long
14283 ** as there is a time string.  The time string can be omitted as long
14284 ** as there is a year and date.
14285 */
14286 static int parseDateOrTime(
14287   sqlite3_context *context, 
14288   const char *zDate, 
14289   DateTime *p
14290 ){
14291   double r;
14292   if( parseYyyyMmDd(zDate,p)==0 ){
14293     return 0;
14294   }else if( parseHhMmSs(zDate, p)==0 ){
14295     return 0;
14296   }else if( sqlite3StrICmp(zDate,"now")==0){
14297     return setDateTimeToCurrent(context, p);
14298   }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
14299     p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
14300     p->validJD = 1;
14301     return 0;
14302   }
14303   return 1;
14304 }
14305
14306 /*
14307 ** Compute the Year, Month, and Day from the julian day number.
14308 */
14309 static void computeYMD(DateTime *p){
14310   int Z, A, B, C, D, E, X1;
14311   if( p->validYMD ) return;
14312   if( !p->validJD ){
14313     p->Y = 2000;
14314     p->M = 1;
14315     p->D = 1;
14316   }else{
14317     Z = (int)((p->iJD + 43200000)/86400000);
14318     A = (int)((Z - 1867216.25)/36524.25);
14319     A = Z + 1 + A - (A/4);
14320     B = A + 1524;
14321     C = (int)((B - 122.1)/365.25);
14322     D = (36525*C)/100;
14323     E = (int)((B-D)/30.6001);
14324     X1 = (int)(30.6001*E);
14325     p->D = B - D - X1;
14326     p->M = E<14 ? E-1 : E-13;
14327     p->Y = p->M>2 ? C - 4716 : C - 4715;
14328   }
14329   p->validYMD = 1;
14330 }
14331
14332 /*
14333 ** Compute the Hour, Minute, and Seconds from the julian day number.
14334 */
14335 static void computeHMS(DateTime *p){
14336   int s;
14337   if( p->validHMS ) return;
14338   computeJD(p);
14339   s = (int)((p->iJD + 43200000) % 86400000);
14340   p->s = s/1000.0;
14341   s = (int)p->s;
14342   p->s -= s;
14343   p->h = s/3600;
14344   s -= p->h*3600;
14345   p->m = s/60;
14346   p->s += s - p->m*60;
14347   p->validHMS = 1;
14348 }
14349
14350 /*
14351 ** Compute both YMD and HMS
14352 */
14353 static void computeYMD_HMS(DateTime *p){
14354   computeYMD(p);
14355   computeHMS(p);
14356 }
14357
14358 /*
14359 ** Clear the YMD and HMS and the TZ
14360 */
14361 static void clearYMD_HMS_TZ(DateTime *p){
14362   p->validYMD = 0;
14363   p->validHMS = 0;
14364   p->validTZ = 0;
14365 }
14366
14367 /*
14368 ** On recent Windows platforms, the localtime_s() function is available
14369 ** as part of the "Secure CRT". It is essentially equivalent to 
14370 ** localtime_r() available under most POSIX platforms, except that the 
14371 ** order of the parameters is reversed.
14372 **
14373 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
14374 **
14375 ** If the user has not indicated to use localtime_r() or localtime_s()
14376 ** already, check for an MSVC build environment that provides 
14377 ** localtime_s().
14378 */
14379 #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
14380      defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
14381 #define HAVE_LOCALTIME_S 1
14382 #endif
14383
14384 #ifndef SQLITE_OMIT_LOCALTIME
14385 /*
14386 ** The following routine implements the rough equivalent of localtime_r()
14387 ** using whatever operating-system specific localtime facility that
14388 ** is available.  This routine returns 0 on success and
14389 ** non-zero on any kind of error.
14390 **
14391 ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
14392 ** routine will always fail.
14393 */
14394 static int osLocaltime(time_t *t, struct tm *pTm){
14395   int rc;
14396 #if (!defined(HAVE_LOCALTIME_R) || !HAVE_LOCALTIME_R) \
14397       && (!defined(HAVE_LOCALTIME_S) || !HAVE_LOCALTIME_S)
14398   struct tm *pX;
14399 #if SQLITE_THREADSAFE>0
14400   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
14401 #endif
14402   sqlite3_mutex_enter(mutex);
14403   pX = localtime(t);
14404 #ifndef SQLITE_OMIT_BUILTIN_TEST
14405   if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
14406 #endif
14407   if( pX ) *pTm = *pX;
14408   sqlite3_mutex_leave(mutex);
14409   rc = pX==0;
14410 #else
14411 #ifndef SQLITE_OMIT_BUILTIN_TEST
14412   if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
14413 #endif
14414 #if defined(HAVE_LOCALTIME_R) && HAVE_LOCALTIME_R
14415   rc = localtime_r(t, pTm)==0;
14416 #else
14417   rc = localtime_s(pTm, t);
14418 #endif /* HAVE_LOCALTIME_R */
14419 #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
14420   return rc;
14421 }
14422 #endif /* SQLITE_OMIT_LOCALTIME */
14423
14424
14425 #ifndef SQLITE_OMIT_LOCALTIME
14426 /*
14427 ** Compute the difference (in milliseconds) between localtime and UTC
14428 ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
14429 ** return this value and set *pRc to SQLITE_OK. 
14430 **
14431 ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
14432 ** is undefined in this case.
14433 */
14434 static sqlite3_int64 localtimeOffset(
14435   DateTime *p,                    /* Date at which to calculate offset */
14436   sqlite3_context *pCtx,          /* Write error here if one occurs */
14437   int *pRc                        /* OUT: Error code. SQLITE_OK or ERROR */
14438 ){
14439   DateTime x, y;
14440   time_t t;
14441   struct tm sLocal;
14442
14443   /* Initialize the contents of sLocal to avoid a compiler warning. */
14444   memset(&sLocal, 0, sizeof(sLocal));
14445
14446   x = *p;
14447   computeYMD_HMS(&x);
14448   if( x.Y<1971 || x.Y>=2038 ){
14449     x.Y = 2000;
14450     x.M = 1;
14451     x.D = 1;
14452     x.h = 0;
14453     x.m = 0;
14454     x.s = 0.0;
14455   } else {
14456     int s = (int)(x.s + 0.5);
14457     x.s = s;
14458   }
14459   x.tz = 0;
14460   x.validJD = 0;
14461   computeJD(&x);
14462   t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
14463   if( osLocaltime(&t, &sLocal) ){
14464     sqlite3_result_error(pCtx, "local time unavailable", -1);
14465     *pRc = SQLITE_ERROR;
14466     return 0;
14467   }
14468   y.Y = sLocal.tm_year + 1900;
14469   y.M = sLocal.tm_mon + 1;
14470   y.D = sLocal.tm_mday;
14471   y.h = sLocal.tm_hour;
14472   y.m = sLocal.tm_min;
14473   y.s = sLocal.tm_sec;
14474   y.validYMD = 1;
14475   y.validHMS = 1;
14476   y.validJD = 0;
14477   y.validTZ = 0;
14478   computeJD(&y);
14479   *pRc = SQLITE_OK;
14480   return y.iJD - x.iJD;
14481 }
14482 #endif /* SQLITE_OMIT_LOCALTIME */
14483
14484 /*
14485 ** Process a modifier to a date-time stamp.  The modifiers are
14486 ** as follows:
14487 **
14488 **     NNN days
14489 **     NNN hours
14490 **     NNN minutes
14491 **     NNN.NNNN seconds
14492 **     NNN months
14493 **     NNN years
14494 **     start of month
14495 **     start of year
14496 **     start of week
14497 **     start of day
14498 **     weekday N
14499 **     unixepoch
14500 **     localtime
14501 **     utc
14502 **
14503 ** Return 0 on success and 1 if there is any kind of error. If the error
14504 ** is in a system call (i.e. localtime()), then an error message is written
14505 ** to context pCtx. If the error is an unrecognized modifier, no error is
14506 ** written to pCtx.
14507 */
14508 static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){
14509   int rc = 1;
14510   int n;
14511   double r;
14512   char *z, zBuf[30];
14513   z = zBuf;
14514   for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
14515     z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
14516   }
14517   z[n] = 0;
14518   switch( z[0] ){
14519 #ifndef SQLITE_OMIT_LOCALTIME
14520     case 'l': {
14521       /*    localtime
14522       **
14523       ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
14524       ** show local time.
14525       */
14526       if( strcmp(z, "localtime")==0 ){
14527         computeJD(p);
14528         p->iJD += localtimeOffset(p, pCtx, &rc);
14529         clearYMD_HMS_TZ(p);
14530       }
14531       break;
14532     }
14533 #endif
14534     case 'u': {
14535       /*
14536       **    unixepoch
14537       **
14538       ** Treat the current value of p->iJD as the number of
14539       ** seconds since 1970.  Convert to a real julian day number.
14540       */
14541       if( strcmp(z, "unixepoch")==0 && p->validJD ){
14542         p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
14543         clearYMD_HMS_TZ(p);
14544         rc = 0;
14545       }
14546 #ifndef SQLITE_OMIT_LOCALTIME
14547       else if( strcmp(z, "utc")==0 ){
14548         sqlite3_int64 c1;
14549         computeJD(p);
14550         c1 = localtimeOffset(p, pCtx, &rc);
14551         if( rc==SQLITE_OK ){
14552           p->iJD -= c1;
14553           clearYMD_HMS_TZ(p);
14554           p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
14555         }
14556       }
14557 #endif
14558       break;
14559     }
14560     case 'w': {
14561       /*
14562       **    weekday N
14563       **
14564       ** Move the date to the same time on the next occurrence of
14565       ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
14566       ** date is already on the appropriate weekday, this is a no-op.
14567       */
14568       if( strncmp(z, "weekday ", 8)==0
14569                && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
14570                && (n=(int)r)==r && n>=0 && r<7 ){
14571         sqlite3_int64 Z;
14572         computeYMD_HMS(p);
14573         p->validTZ = 0;
14574         p->validJD = 0;
14575         computeJD(p);
14576         Z = ((p->iJD + 129600000)/86400000) % 7;
14577         if( Z>n ) Z -= 7;
14578         p->iJD += (n - Z)*86400000;
14579         clearYMD_HMS_TZ(p);
14580         rc = 0;
14581       }
14582       break;
14583     }
14584     case 's': {
14585       /*
14586       **    start of TTTTT
14587       **
14588       ** Move the date backwards to the beginning of the current day,
14589       ** or month or year.
14590       */
14591       if( strncmp(z, "start of ", 9)!=0 ) break;
14592       z += 9;
14593       computeYMD(p);
14594       p->validHMS = 1;
14595       p->h = p->m = 0;
14596       p->s = 0.0;
14597       p->validTZ = 0;
14598       p->validJD = 0;
14599       if( strcmp(z,"month")==0 ){
14600         p->D = 1;
14601         rc = 0;
14602       }else if( strcmp(z,"year")==0 ){
14603         computeYMD(p);
14604         p->M = 1;
14605         p->D = 1;
14606         rc = 0;
14607       }else if( strcmp(z,"day")==0 ){
14608         rc = 0;
14609       }
14610       break;
14611     }
14612     case '+':
14613     case '-':
14614     case '0':
14615     case '1':
14616     case '2':
14617     case '3':
14618     case '4':
14619     case '5':
14620     case '6':
14621     case '7':
14622     case '8':
14623     case '9': {
14624       double rRounder;
14625       for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
14626       if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
14627         rc = 1;
14628         break;
14629       }
14630       if( z[n]==':' ){
14631         /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
14632         ** specified number of hours, minutes, seconds, and fractional seconds
14633         ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
14634         ** omitted.
14635         */
14636         const char *z2 = z;
14637         DateTime tx;
14638         sqlite3_int64 day;
14639         if( !sqlite3Isdigit(*z2) ) z2++;
14640         memset(&tx, 0, sizeof(tx));
14641         if( parseHhMmSs(z2, &tx) ) break;
14642         computeJD(&tx);
14643         tx.iJD -= 43200000;
14644         day = tx.iJD/86400000;
14645         tx.iJD -= day*86400000;
14646         if( z[0]=='-' ) tx.iJD = -tx.iJD;
14647         computeJD(p);
14648         clearYMD_HMS_TZ(p);
14649         p->iJD += tx.iJD;
14650         rc = 0;
14651         break;
14652       }
14653       z += n;
14654       while( sqlite3Isspace(*z) ) z++;
14655       n = sqlite3Strlen30(z);
14656       if( n>10 || n<3 ) break;
14657       if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
14658       computeJD(p);
14659       rc = 0;
14660       rRounder = r<0 ? -0.5 : +0.5;
14661       if( n==3 && strcmp(z,"day")==0 ){
14662         p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
14663       }else if( n==4 && strcmp(z,"hour")==0 ){
14664         p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
14665       }else if( n==6 && strcmp(z,"minute")==0 ){
14666         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
14667       }else if( n==6 && strcmp(z,"second")==0 ){
14668         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
14669       }else if( n==5 && strcmp(z,"month")==0 ){
14670         int x, y;
14671         computeYMD_HMS(p);
14672         p->M += (int)r;
14673         x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
14674         p->Y += x;
14675         p->M -= x*12;
14676         p->validJD = 0;
14677         computeJD(p);
14678         y = (int)r;
14679         if( y!=r ){
14680           p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
14681         }
14682       }else if( n==4 && strcmp(z,"year")==0 ){
14683         int y = (int)r;
14684         computeYMD_HMS(p);
14685         p->Y += y;
14686         p->validJD = 0;
14687         computeJD(p);
14688         if( y!=r ){
14689           p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
14690         }
14691       }else{
14692         rc = 1;
14693       }
14694       clearYMD_HMS_TZ(p);
14695       break;
14696     }
14697     default: {
14698       break;
14699     }
14700   }
14701   return rc;
14702 }
14703
14704 /*
14705 ** Process time function arguments.  argv[0] is a date-time stamp.
14706 ** argv[1] and following are modifiers.  Parse them all and write
14707 ** the resulting time into the DateTime structure p.  Return 0
14708 ** on success and 1 if there are any errors.
14709 **
14710 ** If there are zero parameters (if even argv[0] is undefined)
14711 ** then assume a default value of "now" for argv[0].
14712 */
14713 static int isDate(
14714   sqlite3_context *context, 
14715   int argc, 
14716   sqlite3_value **argv, 
14717   DateTime *p
14718 ){
14719   int i;
14720   const unsigned char *z;
14721   int eType;
14722   memset(p, 0, sizeof(*p));
14723   if( argc==0 ){
14724     return setDateTimeToCurrent(context, p);
14725   }
14726   if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
14727                    || eType==SQLITE_INTEGER ){
14728     p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
14729     p->validJD = 1;
14730   }else{
14731     z = sqlite3_value_text(argv[0]);
14732     if( !z || parseDateOrTime(context, (char*)z, p) ){
14733       return 1;
14734     }
14735   }
14736   for(i=1; i<argc; i++){
14737     z = sqlite3_value_text(argv[i]);
14738     if( z==0 || parseModifier(context, (char*)z, p) ) return 1;
14739   }
14740   return 0;
14741 }
14742
14743
14744 /*
14745 ** The following routines implement the various date and time functions
14746 ** of SQLite.
14747 */
14748
14749 /*
14750 **    julianday( TIMESTRING, MOD, MOD, ...)
14751 **
14752 ** Return the julian day number of the date specified in the arguments
14753 */
14754 static void juliandayFunc(
14755   sqlite3_context *context,
14756   int argc,
14757   sqlite3_value **argv
14758 ){
14759   DateTime x;
14760   if( isDate(context, argc, argv, &x)==0 ){
14761     computeJD(&x);
14762     sqlite3_result_double(context, x.iJD/86400000.0);
14763   }
14764 }
14765
14766 /*
14767 **    datetime( TIMESTRING, MOD, MOD, ...)
14768 **
14769 ** Return YYYY-MM-DD HH:MM:SS
14770 */
14771 static void datetimeFunc(
14772   sqlite3_context *context,
14773   int argc,
14774   sqlite3_value **argv
14775 ){
14776   DateTime x;
14777   if( isDate(context, argc, argv, &x)==0 ){
14778     char zBuf[100];
14779     computeYMD_HMS(&x);
14780     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
14781                      x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
14782     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
14783   }
14784 }
14785
14786 /*
14787 **    time( TIMESTRING, MOD, MOD, ...)
14788 **
14789 ** Return HH:MM:SS
14790 */
14791 static void timeFunc(
14792   sqlite3_context *context,
14793   int argc,
14794   sqlite3_value **argv
14795 ){
14796   DateTime x;
14797   if( isDate(context, argc, argv, &x)==0 ){
14798     char zBuf[100];
14799     computeHMS(&x);
14800     sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
14801     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
14802   }
14803 }
14804
14805 /*
14806 **    date( TIMESTRING, MOD, MOD, ...)
14807 **
14808 ** Return YYYY-MM-DD
14809 */
14810 static void dateFunc(
14811   sqlite3_context *context,
14812   int argc,
14813   sqlite3_value **argv
14814 ){
14815   DateTime x;
14816   if( isDate(context, argc, argv, &x)==0 ){
14817     char zBuf[100];
14818     computeYMD(&x);
14819     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
14820     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
14821   }
14822 }
14823
14824 /*
14825 **    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
14826 **
14827 ** Return a string described by FORMAT.  Conversions as follows:
14828 **
14829 **   %d  day of month
14830 **   %f  ** fractional seconds  SS.SSS
14831 **   %H  hour 00-24
14832 **   %j  day of year 000-366
14833 **   %J  ** Julian day number
14834 **   %m  month 01-12
14835 **   %M  minute 00-59
14836 **   %s  seconds since 1970-01-01
14837 **   %S  seconds 00-59
14838 **   %w  day of week 0-6  sunday==0
14839 **   %W  week of year 00-53
14840 **   %Y  year 0000-9999
14841 **   %%  %
14842 */
14843 static void strftimeFunc(
14844   sqlite3_context *context,
14845   int argc,
14846   sqlite3_value **argv
14847 ){
14848   DateTime x;
14849   u64 n;
14850   size_t i,j;
14851   char *z;
14852   sqlite3 *db;
14853   const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
14854   char zBuf[100];
14855   if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
14856   db = sqlite3_context_db_handle(context);
14857   for(i=0, n=1; zFmt[i]; i++, n++){
14858     if( zFmt[i]=='%' ){
14859       switch( zFmt[i+1] ){
14860         case 'd':
14861         case 'H':
14862         case 'm':
14863         case 'M':
14864         case 'S':
14865         case 'W':
14866           n++;
14867           /* fall thru */
14868         case 'w':
14869         case '%':
14870           break;
14871         case 'f':
14872           n += 8;
14873           break;
14874         case 'j':
14875           n += 3;
14876           break;
14877         case 'Y':
14878           n += 8;
14879           break;
14880         case 's':
14881         case 'J':
14882           n += 50;
14883           break;
14884         default:
14885           return;  /* ERROR.  return a NULL */
14886       }
14887       i++;
14888     }
14889   }
14890   testcase( n==sizeof(zBuf)-1 );
14891   testcase( n==sizeof(zBuf) );
14892   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
14893   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
14894   if( n<sizeof(zBuf) ){
14895     z = zBuf;
14896   }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
14897     sqlite3_result_error_toobig(context);
14898     return;
14899   }else{
14900     z = sqlite3DbMallocRaw(db, (int)n);
14901     if( z==0 ){
14902       sqlite3_result_error_nomem(context);
14903       return;
14904     }
14905   }
14906   computeJD(&x);
14907   computeYMD_HMS(&x);
14908   for(i=j=0; zFmt[i]; i++){
14909     if( zFmt[i]!='%' ){
14910       z[j++] = zFmt[i];
14911     }else{
14912       i++;
14913       switch( zFmt[i] ){
14914         case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
14915         case 'f': {
14916           double s = x.s;
14917           if( s>59.999 ) s = 59.999;
14918           sqlite3_snprintf(7, &z[j],"%06.3f", s);
14919           j += sqlite3Strlen30(&z[j]);
14920           break;
14921         }
14922         case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
14923         case 'W': /* Fall thru */
14924         case 'j': {
14925           int nDay;             /* Number of days since 1st day of year */
14926           DateTime y = x;
14927           y.validJD = 0;
14928           y.M = 1;
14929           y.D = 1;
14930           computeJD(&y);
14931           nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
14932           if( zFmt[i]=='W' ){
14933             int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
14934             wd = (int)(((x.iJD+43200000)/86400000)%7);
14935             sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
14936             j += 2;
14937           }else{
14938             sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
14939             j += 3;
14940           }
14941           break;
14942         }
14943         case 'J': {
14944           sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
14945           j+=sqlite3Strlen30(&z[j]);
14946           break;
14947         }
14948         case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
14949         case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
14950         case 's': {
14951           sqlite3_snprintf(30,&z[j],"%lld",
14952                            (i64)(x.iJD/1000 - 21086676*(i64)10000));
14953           j += sqlite3Strlen30(&z[j]);
14954           break;
14955         }
14956         case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
14957         case 'w': {
14958           z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
14959           break;
14960         }
14961         case 'Y': {
14962           sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
14963           break;
14964         }
14965         default:   z[j++] = '%'; break;
14966       }
14967     }
14968   }
14969   z[j] = 0;
14970   sqlite3_result_text(context, z, -1,
14971                       z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
14972 }
14973
14974 /*
14975 ** current_time()
14976 **
14977 ** This function returns the same value as time('now').
14978 */
14979 static void ctimeFunc(
14980   sqlite3_context *context,
14981   int NotUsed,
14982   sqlite3_value **NotUsed2
14983 ){
14984   UNUSED_PARAMETER2(NotUsed, NotUsed2);
14985   timeFunc(context, 0, 0);
14986 }
14987
14988 /*
14989 ** current_date()
14990 **
14991 ** This function returns the same value as date('now').
14992 */
14993 static void cdateFunc(
14994   sqlite3_context *context,
14995   int NotUsed,
14996   sqlite3_value **NotUsed2
14997 ){
14998   UNUSED_PARAMETER2(NotUsed, NotUsed2);
14999   dateFunc(context, 0, 0);
15000 }
15001
15002 /*
15003 ** current_timestamp()
15004 **
15005 ** This function returns the same value as datetime('now').
15006 */
15007 static void ctimestampFunc(
15008   sqlite3_context *context,
15009   int NotUsed,
15010   sqlite3_value **NotUsed2
15011 ){
15012   UNUSED_PARAMETER2(NotUsed, NotUsed2);
15013   datetimeFunc(context, 0, 0);
15014 }
15015 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
15016
15017 #ifdef SQLITE_OMIT_DATETIME_FUNCS
15018 /*
15019 ** If the library is compiled to omit the full-scale date and time
15020 ** handling (to get a smaller binary), the following minimal version
15021 ** of the functions current_time(), current_date() and current_timestamp()
15022 ** are included instead. This is to support column declarations that
15023 ** include "DEFAULT CURRENT_TIME" etc.
15024 **
15025 ** This function uses the C-library functions time(), gmtime()
15026 ** and strftime(). The format string to pass to strftime() is supplied
15027 ** as the user-data for the function.
15028 */
15029 static void currentTimeFunc(
15030   sqlite3_context *context,
15031   int argc,
15032   sqlite3_value **argv
15033 ){
15034   time_t t;
15035   char *zFormat = (char *)sqlite3_user_data(context);
15036   sqlite3 *db;
15037   sqlite3_int64 iT;
15038   struct tm *pTm;
15039   struct tm sNow;
15040   char zBuf[20];
15041
15042   UNUSED_PARAMETER(argc);
15043   UNUSED_PARAMETER(argv);
15044
15045   db = sqlite3_context_db_handle(context);
15046   if( sqlite3OsCurrentTimeInt64(db->pVfs, &iT) ) return;
15047   t = iT/1000 - 10000*(sqlite3_int64)21086676;
15048 #ifdef HAVE_GMTIME_R
15049   pTm = gmtime_r(&t, &sNow);
15050 #else
15051   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
15052   pTm = gmtime(&t);
15053   if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
15054   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
15055 #endif
15056   if( pTm ){
15057     strftime(zBuf, 20, zFormat, &sNow);
15058     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
15059   }
15060 }
15061 #endif
15062
15063 /*
15064 ** This function registered all of the above C functions as SQL
15065 ** functions.  This should be the only routine in this file with
15066 ** external linkage.
15067 */
15068 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
15069   static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
15070 #ifndef SQLITE_OMIT_DATETIME_FUNCS
15071     FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
15072     FUNCTION(date,             -1, 0, 0, dateFunc      ),
15073     FUNCTION(time,             -1, 0, 0, timeFunc      ),
15074     FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
15075     FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
15076     FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
15077     FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
15078     FUNCTION(current_date,      0, 0, 0, cdateFunc     ),
15079 #else
15080     STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
15081     STR_FUNCTION(current_date,      0, "%Y-%m-%d",          0, currentTimeFunc),
15082     STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
15083 #endif
15084   };
15085   int i;
15086   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
15087   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
15088
15089   for(i=0; i<ArraySize(aDateTimeFuncs); i++){
15090     sqlite3FuncDefInsert(pHash, &aFunc[i]);
15091   }
15092 }
15093
15094 /************** End of date.c ************************************************/
15095 /************** Begin file os.c **********************************************/
15096 /*
15097 ** 2005 November 29
15098 **
15099 ** The author disclaims copyright to this source code.  In place of
15100 ** a legal notice, here is a blessing:
15101 **
15102 **    May you do good and not evil.
15103 **    May you find forgiveness for yourself and forgive others.
15104 **    May you share freely, never taking more than you give.
15105 **
15106 ******************************************************************************
15107 **
15108 ** This file contains OS interface code that is common to all
15109 ** architectures.
15110 */
15111 #define _SQLITE_OS_C_ 1
15112 #undef _SQLITE_OS_C_
15113
15114 /*
15115 ** The default SQLite sqlite3_vfs implementations do not allocate
15116 ** memory (actually, os_unix.c allocates a small amount of memory
15117 ** from within OsOpen()), but some third-party implementations may.
15118 ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
15119 ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
15120 **
15121 ** The following functions are instrumented for malloc() failure 
15122 ** testing:
15123 **
15124 **     sqlite3OsRead()
15125 **     sqlite3OsWrite()
15126 **     sqlite3OsSync()
15127 **     sqlite3OsFileSize()
15128 **     sqlite3OsLock()
15129 **     sqlite3OsCheckReservedLock()
15130 **     sqlite3OsFileControl()
15131 **     sqlite3OsShmMap()
15132 **     sqlite3OsOpen()
15133 **     sqlite3OsDelete()
15134 **     sqlite3OsAccess()
15135 **     sqlite3OsFullPathname()
15136 **
15137 */
15138 #if defined(SQLITE_TEST)
15139 SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
15140   #define DO_OS_MALLOC_TEST(x)                                       \
15141   if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) {  \
15142     void *pTstAlloc = sqlite3Malloc(10);                             \
15143     if (!pTstAlloc) return SQLITE_IOERR_NOMEM;                       \
15144     sqlite3_free(pTstAlloc);                                         \
15145   }
15146 #else
15147   #define DO_OS_MALLOC_TEST(x)
15148 #endif
15149
15150 /*
15151 ** The following routines are convenience wrappers around methods
15152 ** of the sqlite3_file object.  This is mostly just syntactic sugar. All
15153 ** of this would be completely automatic if SQLite were coded using
15154 ** C++ instead of plain old C.
15155 */
15156 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
15157   int rc = SQLITE_OK;
15158   if( pId->pMethods ){
15159     rc = pId->pMethods->xClose(pId);
15160     pId->pMethods = 0;
15161   }
15162   return rc;
15163 }
15164 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
15165   DO_OS_MALLOC_TEST(id);
15166   return id->pMethods->xRead(id, pBuf, amt, offset);
15167 }
15168 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
15169   DO_OS_MALLOC_TEST(id);
15170   return id->pMethods->xWrite(id, pBuf, amt, offset);
15171 }
15172 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
15173   return id->pMethods->xTruncate(id, size);
15174 }
15175 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
15176   DO_OS_MALLOC_TEST(id);
15177   return id->pMethods->xSync(id, flags);
15178 }
15179 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
15180   DO_OS_MALLOC_TEST(id);
15181   return id->pMethods->xFileSize(id, pSize);
15182 }
15183 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
15184   DO_OS_MALLOC_TEST(id);
15185   return id->pMethods->xLock(id, lockType);
15186 }
15187 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
15188   return id->pMethods->xUnlock(id, lockType);
15189 }
15190 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
15191   DO_OS_MALLOC_TEST(id);
15192   return id->pMethods->xCheckReservedLock(id, pResOut);
15193 }
15194
15195 /*
15196 ** Use sqlite3OsFileControl() when we are doing something that might fail
15197 ** and we need to know about the failures.  Use sqlite3OsFileControlHint()
15198 ** when simply tossing information over the wall to the VFS and we do not
15199 ** really care if the VFS receives and understands the information since it
15200 ** is only a hint and can be safely ignored.  The sqlite3OsFileControlHint()
15201 ** routine has no return value since the return value would be meaningless.
15202 */
15203 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
15204   DO_OS_MALLOC_TEST(id);
15205   return id->pMethods->xFileControl(id, op, pArg);
15206 }
15207 SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
15208   (void)id->pMethods->xFileControl(id, op, pArg);
15209 }
15210
15211 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
15212   int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
15213   return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
15214 }
15215 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
15216   return id->pMethods->xDeviceCharacteristics(id);
15217 }
15218 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
15219   return id->pMethods->xShmLock(id, offset, n, flags);
15220 }
15221 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
15222   id->pMethods->xShmBarrier(id);
15223 }
15224 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
15225   return id->pMethods->xShmUnmap(id, deleteFlag);
15226 }
15227 SQLITE_PRIVATE int sqlite3OsShmMap(
15228   sqlite3_file *id,               /* Database file handle */
15229   int iPage,
15230   int pgsz,
15231   int bExtend,                    /* True to extend file if necessary */
15232   void volatile **pp              /* OUT: Pointer to mapping */
15233 ){
15234   DO_OS_MALLOC_TEST(id);
15235   return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
15236 }
15237
15238 #if SQLITE_MAX_MMAP_SIZE>0
15239 /* The real implementation of xFetch and xUnfetch */
15240 SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
15241   DO_OS_MALLOC_TEST(id);
15242   return id->pMethods->xFetch(id, iOff, iAmt, pp);
15243 }
15244 SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
15245   return id->pMethods->xUnfetch(id, iOff, p);
15246 }
15247 #else
15248 /* No-op stubs to use when memory-mapped I/O is disabled */
15249 SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
15250   *pp = 0;
15251   return SQLITE_OK;
15252 }
15253 SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
15254   return SQLITE_OK;
15255 }
15256 #endif
15257
15258 /*
15259 ** The next group of routines are convenience wrappers around the
15260 ** VFS methods.
15261 */
15262 SQLITE_PRIVATE int sqlite3OsOpen(
15263   sqlite3_vfs *pVfs, 
15264   const char *zPath, 
15265   sqlite3_file *pFile, 
15266   int flags, 
15267   int *pFlagsOut
15268 ){
15269   int rc;
15270   DO_OS_MALLOC_TEST(0);
15271   /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
15272   ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
15273   ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
15274   ** reaching the VFS. */
15275   rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
15276   assert( rc==SQLITE_OK || pFile->pMethods==0 );
15277   return rc;
15278 }
15279 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
15280   DO_OS_MALLOC_TEST(0);
15281   assert( dirSync==0 || dirSync==1 );
15282   return pVfs->xDelete(pVfs, zPath, dirSync);
15283 }
15284 SQLITE_PRIVATE int sqlite3OsAccess(
15285   sqlite3_vfs *pVfs, 
15286   const char *zPath, 
15287   int flags, 
15288   int *pResOut
15289 ){
15290   DO_OS_MALLOC_TEST(0);
15291   return pVfs->xAccess(pVfs, zPath, flags, pResOut);
15292 }
15293 SQLITE_PRIVATE int sqlite3OsFullPathname(
15294   sqlite3_vfs *pVfs, 
15295   const char *zPath, 
15296   int nPathOut, 
15297   char *zPathOut
15298 ){
15299   DO_OS_MALLOC_TEST(0);
15300   zPathOut[0] = 0;
15301   return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
15302 }
15303 #ifndef SQLITE_OMIT_LOAD_EXTENSION
15304 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
15305   return pVfs->xDlOpen(pVfs, zPath);
15306 }
15307 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
15308   pVfs->xDlError(pVfs, nByte, zBufOut);
15309 }
15310 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
15311   return pVfs->xDlSym(pVfs, pHdle, zSym);
15312 }
15313 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
15314   pVfs->xDlClose(pVfs, pHandle);
15315 }
15316 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
15317 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
15318   return pVfs->xRandomness(pVfs, nByte, zBufOut);
15319 }
15320 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
15321   return pVfs->xSleep(pVfs, nMicro);
15322 }
15323 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
15324   int rc;
15325   /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
15326   ** method to get the current date and time if that method is available
15327   ** (if iVersion is 2 or greater and the function pointer is not NULL) and
15328   ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
15329   ** unavailable.
15330   */
15331   if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
15332     rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
15333   }else{
15334     double r;
15335     rc = pVfs->xCurrentTime(pVfs, &r);
15336     *pTimeOut = (sqlite3_int64)(r*86400000.0);
15337   }
15338   return rc;
15339 }
15340
15341 SQLITE_PRIVATE int sqlite3OsOpenMalloc(
15342   sqlite3_vfs *pVfs, 
15343   const char *zFile, 
15344   sqlite3_file **ppFile, 
15345   int flags,
15346   int *pOutFlags
15347 ){
15348   int rc = SQLITE_NOMEM;
15349   sqlite3_file *pFile;
15350   pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
15351   if( pFile ){
15352     rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
15353     if( rc!=SQLITE_OK ){
15354       sqlite3_free(pFile);
15355     }else{
15356       *ppFile = pFile;
15357     }
15358   }
15359   return rc;
15360 }
15361 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
15362   int rc = SQLITE_OK;
15363   assert( pFile );
15364   rc = sqlite3OsClose(pFile);
15365   sqlite3_free(pFile);
15366   return rc;
15367 }
15368
15369 /*
15370 ** This function is a wrapper around the OS specific implementation of
15371 ** sqlite3_os_init(). The purpose of the wrapper is to provide the
15372 ** ability to simulate a malloc failure, so that the handling of an
15373 ** error in sqlite3_os_init() by the upper layers can be tested.
15374 */
15375 SQLITE_PRIVATE int sqlite3OsInit(void){
15376   void *p = sqlite3_malloc(10);
15377   if( p==0 ) return SQLITE_NOMEM;
15378   sqlite3_free(p);
15379   return sqlite3_os_init();
15380 }
15381
15382 /*
15383 ** The list of all registered VFS implementations.
15384 */
15385 static sqlite3_vfs * SQLITE_WSD vfsList = 0;
15386 #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
15387
15388 /*
15389 ** Locate a VFS by name.  If no name is given, simply return the
15390 ** first VFS on the list.
15391 */
15392 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
15393   sqlite3_vfs *pVfs = 0;
15394 #if SQLITE_THREADSAFE
15395   sqlite3_mutex *mutex;
15396 #endif
15397 #ifndef SQLITE_OMIT_AUTOINIT
15398   int rc = sqlite3_initialize();
15399   if( rc ) return 0;
15400 #endif
15401 #if SQLITE_THREADSAFE
15402   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
15403 #endif
15404   sqlite3_mutex_enter(mutex);
15405   for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
15406     if( zVfs==0 ) break;
15407     if( strcmp(zVfs, pVfs->zName)==0 ) break;
15408   }
15409   sqlite3_mutex_leave(mutex);
15410   return pVfs;
15411 }
15412
15413 /*
15414 ** Unlink a VFS from the linked list
15415 */
15416 static void vfsUnlink(sqlite3_vfs *pVfs){
15417   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
15418   if( pVfs==0 ){
15419     /* No-op */
15420   }else if( vfsList==pVfs ){
15421     vfsList = pVfs->pNext;
15422   }else if( vfsList ){
15423     sqlite3_vfs *p = vfsList;
15424     while( p->pNext && p->pNext!=pVfs ){
15425       p = p->pNext;
15426     }
15427     if( p->pNext==pVfs ){
15428       p->pNext = pVfs->pNext;
15429     }
15430   }
15431 }
15432
15433 /*
15434 ** Register a VFS with the system.  It is harmless to register the same
15435 ** VFS multiple times.  The new VFS becomes the default if makeDflt is
15436 ** true.
15437 */
15438 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
15439   MUTEX_LOGIC(sqlite3_mutex *mutex;)
15440 #ifndef SQLITE_OMIT_AUTOINIT
15441   int rc = sqlite3_initialize();
15442   if( rc ) return rc;
15443 #endif
15444   MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
15445   sqlite3_mutex_enter(mutex);
15446   vfsUnlink(pVfs);
15447   if( makeDflt || vfsList==0 ){
15448     pVfs->pNext = vfsList;
15449     vfsList = pVfs;
15450   }else{
15451     pVfs->pNext = vfsList->pNext;
15452     vfsList->pNext = pVfs;
15453   }
15454   assert(vfsList);
15455   sqlite3_mutex_leave(mutex);
15456   return SQLITE_OK;
15457 }
15458
15459 /*
15460 ** Unregister a VFS so that it is no longer accessible.
15461 */
15462 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
15463 #if SQLITE_THREADSAFE
15464   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
15465 #endif
15466   sqlite3_mutex_enter(mutex);
15467   vfsUnlink(pVfs);
15468   sqlite3_mutex_leave(mutex);
15469   return SQLITE_OK;
15470 }
15471
15472 /************** End of os.c **************************************************/
15473 /************** Begin file fault.c *******************************************/
15474 /*
15475 ** 2008 Jan 22
15476 **
15477 ** The author disclaims copyright to this source code.  In place of
15478 ** a legal notice, here is a blessing:
15479 **
15480 **    May you do good and not evil.
15481 **    May you find forgiveness for yourself and forgive others.
15482 **    May you share freely, never taking more than you give.
15483 **
15484 *************************************************************************
15485 **
15486 ** This file contains code to support the concept of "benign" 
15487 ** malloc failures (when the xMalloc() or xRealloc() method of the
15488 ** sqlite3_mem_methods structure fails to allocate a block of memory
15489 ** and returns 0). 
15490 **
15491 ** Most malloc failures are non-benign. After they occur, SQLite
15492 ** abandons the current operation and returns an error code (usually
15493 ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
15494 ** fatal. For example, if a malloc fails while resizing a hash table, this 
15495 ** is completely recoverable simply by not carrying out the resize. The 
15496 ** hash table will continue to function normally.  So a malloc failure 
15497 ** during a hash table resize is a benign fault.
15498 */
15499
15500
15501 #ifndef SQLITE_OMIT_BUILTIN_TEST
15502
15503 /*
15504 ** Global variables.
15505 */
15506 typedef struct BenignMallocHooks BenignMallocHooks;
15507 static SQLITE_WSD struct BenignMallocHooks {
15508   void (*xBenignBegin)(void);
15509   void (*xBenignEnd)(void);
15510 } sqlite3Hooks = { 0, 0 };
15511
15512 /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
15513 ** structure.  If writable static data is unsupported on the target,
15514 ** we have to locate the state vector at run-time.  In the more common
15515 ** case where writable static data is supported, wsdHooks can refer directly
15516 ** to the "sqlite3Hooks" state vector declared above.
15517 */
15518 #ifdef SQLITE_OMIT_WSD
15519 # define wsdHooksInit \
15520   BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
15521 # define wsdHooks x[0]
15522 #else
15523 # define wsdHooksInit
15524 # define wsdHooks sqlite3Hooks
15525 #endif
15526
15527
15528 /*
15529 ** Register hooks to call when sqlite3BeginBenignMalloc() and
15530 ** sqlite3EndBenignMalloc() are called, respectively.
15531 */
15532 SQLITE_PRIVATE void sqlite3BenignMallocHooks(
15533   void (*xBenignBegin)(void),
15534   void (*xBenignEnd)(void)
15535 ){
15536   wsdHooksInit;
15537   wsdHooks.xBenignBegin = xBenignBegin;
15538   wsdHooks.xBenignEnd = xBenignEnd;
15539 }
15540
15541 /*
15542 ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
15543 ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
15544 ** indicates that subsequent malloc failures are non-benign.
15545 */
15546 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
15547   wsdHooksInit;
15548   if( wsdHooks.xBenignBegin ){
15549     wsdHooks.xBenignBegin();
15550   }
15551 }
15552 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
15553   wsdHooksInit;
15554   if( wsdHooks.xBenignEnd ){
15555     wsdHooks.xBenignEnd();
15556   }
15557 }
15558
15559 #endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
15560
15561 /************** End of fault.c ***********************************************/
15562 /************** Begin file mem0.c ********************************************/
15563 /*
15564 ** 2008 October 28
15565 **
15566 ** The author disclaims copyright to this source code.  In place of
15567 ** a legal notice, here is a blessing:
15568 **
15569 **    May you do good and not evil.
15570 **    May you find forgiveness for yourself and forgive others.
15571 **    May you share freely, never taking more than you give.
15572 **
15573 *************************************************************************
15574 **
15575 ** This file contains a no-op memory allocation drivers for use when
15576 ** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
15577 ** here always fail.  SQLite will not operate with these drivers.  These
15578 ** are merely placeholders.  Real drivers must be substituted using
15579 ** sqlite3_config() before SQLite will operate.
15580 */
15581
15582 /*
15583 ** This version of the memory allocator is the default.  It is
15584 ** used when no other memory allocator is specified using compile-time
15585 ** macros.
15586 */
15587 #ifdef SQLITE_ZERO_MALLOC
15588
15589 /*
15590 ** No-op versions of all memory allocation routines
15591 */
15592 static void *sqlite3MemMalloc(int nByte){ return 0; }
15593 static void sqlite3MemFree(void *pPrior){ return; }
15594 static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
15595 static int sqlite3MemSize(void *pPrior){ return 0; }
15596 static int sqlite3MemRoundup(int n){ return n; }
15597 static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
15598 static void sqlite3MemShutdown(void *NotUsed){ return; }
15599
15600 /*
15601 ** This routine is the only routine in this file with external linkage.
15602 **
15603 ** Populate the low-level memory allocation function pointers in
15604 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
15605 */
15606 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
15607   static const sqlite3_mem_methods defaultMethods = {
15608      sqlite3MemMalloc,
15609      sqlite3MemFree,
15610      sqlite3MemRealloc,
15611      sqlite3MemSize,
15612      sqlite3MemRoundup,
15613      sqlite3MemInit,
15614      sqlite3MemShutdown,
15615      0
15616   };
15617   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
15618 }
15619
15620 #endif /* SQLITE_ZERO_MALLOC */
15621
15622 /************** End of mem0.c ************************************************/
15623 /************** Begin file mem1.c ********************************************/
15624 /*
15625 ** 2007 August 14
15626 **
15627 ** The author disclaims copyright to this source code.  In place of
15628 ** a legal notice, here is a blessing:
15629 **
15630 **    May you do good and not evil.
15631 **    May you find forgiveness for yourself and forgive others.
15632 **    May you share freely, never taking more than you give.
15633 **
15634 *************************************************************************
15635 **
15636 ** This file contains low-level memory allocation drivers for when
15637 ** SQLite will use the standard C-library malloc/realloc/free interface
15638 ** to obtain the memory it needs.
15639 **
15640 ** This file contains implementations of the low-level memory allocation
15641 ** routines specified in the sqlite3_mem_methods object.  The content of
15642 ** this file is only used if SQLITE_SYSTEM_MALLOC is defined.  The
15643 ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
15644 ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined.  The
15645 ** default configuration is to use memory allocation routines in this
15646 ** file.
15647 **
15648 ** C-preprocessor macro summary:
15649 **
15650 **    HAVE_MALLOC_USABLE_SIZE     The configure script sets this symbol if
15651 **                                the malloc_usable_size() interface exists
15652 **                                on the target platform.  Or, this symbol
15653 **                                can be set manually, if desired.
15654 **                                If an equivalent interface exists by
15655 **                                a different name, using a separate -D
15656 **                                option to rename it.
15657 **
15658 **    SQLITE_WITHOUT_ZONEMALLOC   Some older macs lack support for the zone
15659 **                                memory allocator.  Set this symbol to enable
15660 **                                building on older macs.
15661 **
15662 **    SQLITE_WITHOUT_MSIZE        Set this symbol to disable the use of
15663 **                                _msize() on windows systems.  This might
15664 **                                be necessary when compiling for Delphi,
15665 **                                for example.
15666 */
15667
15668 /*
15669 ** This version of the memory allocator is the default.  It is
15670 ** used when no other memory allocator is specified using compile-time
15671 ** macros.
15672 */
15673 #ifdef SQLITE_SYSTEM_MALLOC
15674
15675 /*
15676 ** The MSVCRT has malloc_usable_size() but it is called _msize().
15677 ** The use of _msize() is automatic, but can be disabled by compiling
15678 ** with -DSQLITE_WITHOUT_MSIZE
15679 */
15680 #if defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
15681 # define SQLITE_MALLOCSIZE _msize
15682 #endif
15683
15684 #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
15685
15686 /*
15687 ** Use the zone allocator available on apple products unless the
15688 ** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
15689 */
15690 #include <sys/sysctl.h>
15691 #include <malloc/malloc.h>
15692 #include <libkern/OSAtomic.h>
15693 static malloc_zone_t* _sqliteZone_;
15694 #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
15695 #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
15696 #define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
15697 #define SQLITE_MALLOCSIZE(x) \
15698         (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
15699
15700 #else /* if not __APPLE__ */
15701
15702 /*
15703 ** Use standard C library malloc and free on non-Apple systems.  
15704 ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
15705 */
15706 #define SQLITE_MALLOC(x)    malloc(x)
15707 #define SQLITE_FREE(x)      free(x)
15708 #define SQLITE_REALLOC(x,y) realloc((x),(y))
15709
15710 #if (defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)) \
15711       || (defined(HAVE_MALLOC_H) && defined(HAVE_MALLOC_USABLE_SIZE))
15712 # include <malloc.h>    /* Needed for malloc_usable_size on linux */
15713 #endif
15714 #ifdef HAVE_MALLOC_USABLE_SIZE
15715 # ifndef SQLITE_MALLOCSIZE
15716 #  define SQLITE_MALLOCSIZE(x) malloc_usable_size(x)
15717 # endif
15718 #else
15719 # undef SQLITE_MALLOCSIZE
15720 #endif
15721
15722 #endif /* __APPLE__ or not __APPLE__ */
15723
15724 /*
15725 ** Like malloc(), but remember the size of the allocation
15726 ** so that we can find it later using sqlite3MemSize().
15727 **
15728 ** For this low-level routine, we are guaranteed that nByte>0 because
15729 ** cases of nByte<=0 will be intercepted and dealt with by higher level
15730 ** routines.
15731 */
15732 static void *sqlite3MemMalloc(int nByte){
15733 #ifdef SQLITE_MALLOCSIZE
15734   void *p = SQLITE_MALLOC( nByte );
15735   if( p==0 ){
15736     testcase( sqlite3GlobalConfig.xLog!=0 );
15737     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
15738   }
15739   return p;
15740 #else
15741   sqlite3_int64 *p;
15742   assert( nByte>0 );
15743   nByte = ROUND8(nByte);
15744   p = SQLITE_MALLOC( nByte+8 );
15745   if( p ){
15746     p[0] = nByte;
15747     p++;
15748   }else{
15749     testcase( sqlite3GlobalConfig.xLog!=0 );
15750     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
15751   }
15752   return (void *)p;
15753 #endif
15754 }
15755
15756 /*
15757 ** Like free() but works for allocations obtained from sqlite3MemMalloc()
15758 ** or sqlite3MemRealloc().
15759 **
15760 ** For this low-level routine, we already know that pPrior!=0 since
15761 ** cases where pPrior==0 will have been intecepted and dealt with
15762 ** by higher-level routines.
15763 */
15764 static void sqlite3MemFree(void *pPrior){
15765 #ifdef SQLITE_MALLOCSIZE
15766   SQLITE_FREE(pPrior);
15767 #else
15768   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
15769   assert( pPrior!=0 );
15770   p--;
15771   SQLITE_FREE(p);
15772 #endif
15773 }
15774
15775 /*
15776 ** Report the allocated size of a prior return from xMalloc()
15777 ** or xRealloc().
15778 */
15779 static int sqlite3MemSize(void *pPrior){
15780 #ifdef SQLITE_MALLOCSIZE
15781   return pPrior ? (int)SQLITE_MALLOCSIZE(pPrior) : 0;
15782 #else
15783   sqlite3_int64 *p;
15784   if( pPrior==0 ) return 0;
15785   p = (sqlite3_int64*)pPrior;
15786   p--;
15787   return (int)p[0];
15788 #endif
15789 }
15790
15791 /*
15792 ** Like realloc().  Resize an allocation previously obtained from
15793 ** sqlite3MemMalloc().
15794 **
15795 ** For this low-level interface, we know that pPrior!=0.  Cases where
15796 ** pPrior==0 while have been intercepted by higher-level routine and
15797 ** redirected to xMalloc.  Similarly, we know that nByte>0 becauses
15798 ** cases where nByte<=0 will have been intercepted by higher-level
15799 ** routines and redirected to xFree.
15800 */
15801 static void *sqlite3MemRealloc(void *pPrior, int nByte){
15802 #ifdef SQLITE_MALLOCSIZE
15803   void *p = SQLITE_REALLOC(pPrior, nByte);
15804   if( p==0 ){
15805     testcase( sqlite3GlobalConfig.xLog!=0 );
15806     sqlite3_log(SQLITE_NOMEM,
15807       "failed memory resize %u to %u bytes",
15808       SQLITE_MALLOCSIZE(pPrior), nByte);
15809   }
15810   return p;
15811 #else
15812   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
15813   assert( pPrior!=0 && nByte>0 );
15814   assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
15815   p--;
15816   p = SQLITE_REALLOC(p, nByte+8 );
15817   if( p ){
15818     p[0] = nByte;
15819     p++;
15820   }else{
15821     testcase( sqlite3GlobalConfig.xLog!=0 );
15822     sqlite3_log(SQLITE_NOMEM,
15823       "failed memory resize %u to %u bytes",
15824       sqlite3MemSize(pPrior), nByte);
15825   }
15826   return (void*)p;
15827 #endif
15828 }
15829
15830 /*
15831 ** Round up a request size to the next valid allocation size.
15832 */
15833 static int sqlite3MemRoundup(int n){
15834   return ROUND8(n);
15835 }
15836
15837 /*
15838 ** Initialize this module.
15839 */
15840 static int sqlite3MemInit(void *NotUsed){
15841 #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
15842   int cpuCount;
15843   size_t len;
15844   if( _sqliteZone_ ){
15845     return SQLITE_OK;
15846   }
15847   len = sizeof(cpuCount);
15848   /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
15849   sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
15850   if( cpuCount>1 ){
15851     /* defer MT decisions to system malloc */
15852     _sqliteZone_ = malloc_default_zone();
15853   }else{
15854     /* only 1 core, use our own zone to contention over global locks, 
15855     ** e.g. we have our own dedicated locks */
15856     bool success;
15857     malloc_zone_t* newzone = malloc_create_zone(4096, 0);
15858     malloc_set_zone_name(newzone, "Sqlite_Heap");
15859     do{
15860       success = OSAtomicCompareAndSwapPtrBarrier(NULL, newzone, 
15861                                  (void * volatile *)&_sqliteZone_);
15862     }while(!_sqliteZone_);
15863     if( !success ){
15864       /* somebody registered a zone first */
15865       malloc_destroy_zone(newzone);
15866     }
15867   }
15868 #endif
15869   UNUSED_PARAMETER(NotUsed);
15870   return SQLITE_OK;
15871 }
15872
15873 /*
15874 ** Deinitialize this module.
15875 */
15876 static void sqlite3MemShutdown(void *NotUsed){
15877   UNUSED_PARAMETER(NotUsed);
15878   return;
15879 }
15880
15881 /*
15882 ** This routine is the only routine in this file with external linkage.
15883 **
15884 ** Populate the low-level memory allocation function pointers in
15885 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
15886 */
15887 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
15888   static const sqlite3_mem_methods defaultMethods = {
15889      sqlite3MemMalloc,
15890      sqlite3MemFree,
15891      sqlite3MemRealloc,
15892      sqlite3MemSize,
15893      sqlite3MemRoundup,
15894      sqlite3MemInit,
15895      sqlite3MemShutdown,
15896      0
15897   };
15898   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
15899 }
15900
15901 #endif /* SQLITE_SYSTEM_MALLOC */
15902
15903 /************** End of mem1.c ************************************************/
15904 /************** Begin file mem2.c ********************************************/
15905 /*
15906 ** 2007 August 15
15907 **
15908 ** The author disclaims copyright to this source code.  In place of
15909 ** a legal notice, here is a blessing:
15910 **
15911 **    May you do good and not evil.
15912 **    May you find forgiveness for yourself and forgive others.
15913 **    May you share freely, never taking more than you give.
15914 **
15915 *************************************************************************
15916 **
15917 ** This file contains low-level memory allocation drivers for when
15918 ** SQLite will use the standard C-library malloc/realloc/free interface
15919 ** to obtain the memory it needs while adding lots of additional debugging
15920 ** information to each allocation in order to help detect and fix memory
15921 ** leaks and memory usage errors.
15922 **
15923 ** This file contains implementations of the low-level memory allocation
15924 ** routines specified in the sqlite3_mem_methods object.
15925 */
15926
15927 /*
15928 ** This version of the memory allocator is used only if the
15929 ** SQLITE_MEMDEBUG macro is defined
15930 */
15931 #ifdef SQLITE_MEMDEBUG
15932
15933 /*
15934 ** The backtrace functionality is only available with GLIBC
15935 */
15936 #ifdef __GLIBC__
15937   extern int backtrace(void**,int);
15938   extern void backtrace_symbols_fd(void*const*,int,int);
15939 #else
15940 # define backtrace(A,B) 1
15941 # define backtrace_symbols_fd(A,B,C)
15942 #endif
15943 /* #include <stdio.h> */
15944
15945 /*
15946 ** Each memory allocation looks like this:
15947 **
15948 **  ------------------------------------------------------------------------
15949 **  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
15950 **  ------------------------------------------------------------------------
15951 **
15952 ** The application code sees only a pointer to the allocation.  We have
15953 ** to back up from the allocation pointer to find the MemBlockHdr.  The
15954 ** MemBlockHdr tells us the size of the allocation and the number of
15955 ** backtrace pointers.  There is also a guard word at the end of the
15956 ** MemBlockHdr.
15957 */
15958 struct MemBlockHdr {
15959   i64 iSize;                          /* Size of this allocation */
15960   struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
15961   char nBacktrace;                    /* Number of backtraces on this alloc */
15962   char nBacktraceSlots;               /* Available backtrace slots */
15963   u8 nTitle;                          /* Bytes of title; includes '\0' */
15964   u8 eType;                           /* Allocation type code */
15965   int iForeGuard;                     /* Guard word for sanity */
15966 };
15967
15968 /*
15969 ** Guard words
15970 */
15971 #define FOREGUARD 0x80F5E153
15972 #define REARGUARD 0xE4676B53
15973
15974 /*
15975 ** Number of malloc size increments to track.
15976 */
15977 #define NCSIZE  1000
15978
15979 /*
15980 ** All of the static variables used by this module are collected
15981 ** into a single structure named "mem".  This is to keep the
15982 ** static variables organized and to reduce namespace pollution
15983 ** when this module is combined with other in the amalgamation.
15984 */
15985 static struct {
15986   
15987   /*
15988   ** Mutex to control access to the memory allocation subsystem.
15989   */
15990   sqlite3_mutex *mutex;
15991
15992   /*
15993   ** Head and tail of a linked list of all outstanding allocations
15994   */
15995   struct MemBlockHdr *pFirst;
15996   struct MemBlockHdr *pLast;
15997   
15998   /*
15999   ** The number of levels of backtrace to save in new allocations.
16000   */
16001   int nBacktrace;
16002   void (*xBacktrace)(int, int, void **);
16003
16004   /*
16005   ** Title text to insert in front of each block
16006   */
16007   int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
16008   char zTitle[100];  /* The title text */
16009
16010   /* 
16011   ** sqlite3MallocDisallow() increments the following counter.
16012   ** sqlite3MallocAllow() decrements it.
16013   */
16014   int disallow; /* Do not allow memory allocation */
16015
16016   /*
16017   ** Gather statistics on the sizes of memory allocations.
16018   ** nAlloc[i] is the number of allocation attempts of i*8
16019   ** bytes.  i==NCSIZE is the number of allocation attempts for
16020   ** sizes more than NCSIZE*8 bytes.
16021   */
16022   int nAlloc[NCSIZE];      /* Total number of allocations */
16023   int nCurrent[NCSIZE];    /* Current number of allocations */
16024   int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
16025
16026 } mem;
16027
16028
16029 /*
16030 ** Adjust memory usage statistics
16031 */
16032 static void adjustStats(int iSize, int increment){
16033   int i = ROUND8(iSize)/8;
16034   if( i>NCSIZE-1 ){
16035     i = NCSIZE - 1;
16036   }
16037   if( increment>0 ){
16038     mem.nAlloc[i]++;
16039     mem.nCurrent[i]++;
16040     if( mem.nCurrent[i]>mem.mxCurrent[i] ){
16041       mem.mxCurrent[i] = mem.nCurrent[i];
16042     }
16043   }else{
16044     mem.nCurrent[i]--;
16045     assert( mem.nCurrent[i]>=0 );
16046   }
16047 }
16048
16049 /*
16050 ** Given an allocation, find the MemBlockHdr for that allocation.
16051 **
16052 ** This routine checks the guards at either end of the allocation and
16053 ** if they are incorrect it asserts.
16054 */
16055 static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
16056   struct MemBlockHdr *p;
16057   int *pInt;
16058   u8 *pU8;
16059   int nReserve;
16060
16061   p = (struct MemBlockHdr*)pAllocation;
16062   p--;
16063   assert( p->iForeGuard==(int)FOREGUARD );
16064   nReserve = ROUND8(p->iSize);
16065   pInt = (int*)pAllocation;
16066   pU8 = (u8*)pAllocation;
16067   assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
16068   /* This checks any of the "extra" bytes allocated due
16069   ** to rounding up to an 8 byte boundary to ensure 
16070   ** they haven't been overwritten.
16071   */
16072   while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
16073   return p;
16074 }
16075
16076 /*
16077 ** Return the number of bytes currently allocated at address p.
16078 */
16079 static int sqlite3MemSize(void *p){
16080   struct MemBlockHdr *pHdr;
16081   if( !p ){
16082     return 0;
16083   }
16084   pHdr = sqlite3MemsysGetHeader(p);
16085   return pHdr->iSize;
16086 }
16087
16088 /*
16089 ** Initialize the memory allocation subsystem.
16090 */
16091 static int sqlite3MemInit(void *NotUsed){
16092   UNUSED_PARAMETER(NotUsed);
16093   assert( (sizeof(struct MemBlockHdr)&7) == 0 );
16094   if( !sqlite3GlobalConfig.bMemstat ){
16095     /* If memory status is enabled, then the malloc.c wrapper will already
16096     ** hold the STATIC_MEM mutex when the routines here are invoked. */
16097     mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
16098   }
16099   return SQLITE_OK;
16100 }
16101
16102 /*
16103 ** Deinitialize the memory allocation subsystem.
16104 */
16105 static void sqlite3MemShutdown(void *NotUsed){
16106   UNUSED_PARAMETER(NotUsed);
16107   mem.mutex = 0;
16108 }
16109
16110 /*
16111 ** Round up a request size to the next valid allocation size.
16112 */
16113 static int sqlite3MemRoundup(int n){
16114   return ROUND8(n);
16115 }
16116
16117 /*
16118 ** Fill a buffer with pseudo-random bytes.  This is used to preset
16119 ** the content of a new memory allocation to unpredictable values and
16120 ** to clear the content of a freed allocation to unpredictable values.
16121 */
16122 static void randomFill(char *pBuf, int nByte){
16123   unsigned int x, y, r;
16124   x = SQLITE_PTR_TO_INT(pBuf);
16125   y = nByte | 1;
16126   while( nByte >= 4 ){
16127     x = (x>>1) ^ (-(x&1) & 0xd0000001);
16128     y = y*1103515245 + 12345;
16129     r = x ^ y;
16130     *(int*)pBuf = r;
16131     pBuf += 4;
16132     nByte -= 4;
16133   }
16134   while( nByte-- > 0 ){
16135     x = (x>>1) ^ (-(x&1) & 0xd0000001);
16136     y = y*1103515245 + 12345;
16137     r = x ^ y;
16138     *(pBuf++) = r & 0xff;
16139   }
16140 }
16141
16142 /*
16143 ** Allocate nByte bytes of memory.
16144 */
16145 static void *sqlite3MemMalloc(int nByte){
16146   struct MemBlockHdr *pHdr;
16147   void **pBt;
16148   char *z;
16149   int *pInt;
16150   void *p = 0;
16151   int totalSize;
16152   int nReserve;
16153   sqlite3_mutex_enter(mem.mutex);
16154   assert( mem.disallow==0 );
16155   nReserve = ROUND8(nByte);
16156   totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
16157                mem.nBacktrace*sizeof(void*) + mem.nTitle;
16158   p = malloc(totalSize);
16159   if( p ){
16160     z = p;
16161     pBt = (void**)&z[mem.nTitle];
16162     pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
16163     pHdr->pNext = 0;
16164     pHdr->pPrev = mem.pLast;
16165     if( mem.pLast ){
16166       mem.pLast->pNext = pHdr;
16167     }else{
16168       mem.pFirst = pHdr;
16169     }
16170     mem.pLast = pHdr;
16171     pHdr->iForeGuard = FOREGUARD;
16172     pHdr->eType = MEMTYPE_HEAP;
16173     pHdr->nBacktraceSlots = mem.nBacktrace;
16174     pHdr->nTitle = mem.nTitle;
16175     if( mem.nBacktrace ){
16176       void *aAddr[40];
16177       pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
16178       memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
16179       assert(pBt[0]);
16180       if( mem.xBacktrace ){
16181         mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
16182       }
16183     }else{
16184       pHdr->nBacktrace = 0;
16185     }
16186     if( mem.nTitle ){
16187       memcpy(z, mem.zTitle, mem.nTitle);
16188     }
16189     pHdr->iSize = nByte;
16190     adjustStats(nByte, +1);
16191     pInt = (int*)&pHdr[1];
16192     pInt[nReserve/sizeof(int)] = REARGUARD;
16193     randomFill((char*)pInt, nByte);
16194     memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
16195     p = (void*)pInt;
16196   }
16197   sqlite3_mutex_leave(mem.mutex);
16198   return p; 
16199 }
16200
16201 /*
16202 ** Free memory.
16203 */
16204 static void sqlite3MemFree(void *pPrior){
16205   struct MemBlockHdr *pHdr;
16206   void **pBt;
16207   char *z;
16208   assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0 
16209        || mem.mutex!=0 );
16210   pHdr = sqlite3MemsysGetHeader(pPrior);
16211   pBt = (void**)pHdr;
16212   pBt -= pHdr->nBacktraceSlots;
16213   sqlite3_mutex_enter(mem.mutex);
16214   if( pHdr->pPrev ){
16215     assert( pHdr->pPrev->pNext==pHdr );
16216     pHdr->pPrev->pNext = pHdr->pNext;
16217   }else{
16218     assert( mem.pFirst==pHdr );
16219     mem.pFirst = pHdr->pNext;
16220   }
16221   if( pHdr->pNext ){
16222     assert( pHdr->pNext->pPrev==pHdr );
16223     pHdr->pNext->pPrev = pHdr->pPrev;
16224   }else{
16225     assert( mem.pLast==pHdr );
16226     mem.pLast = pHdr->pPrev;
16227   }
16228   z = (char*)pBt;
16229   z -= pHdr->nTitle;
16230   adjustStats(pHdr->iSize, -1);
16231   randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
16232                 pHdr->iSize + sizeof(int) + pHdr->nTitle);
16233   free(z);
16234   sqlite3_mutex_leave(mem.mutex);  
16235 }
16236
16237 /*
16238 ** Change the size of an existing memory allocation.
16239 **
16240 ** For this debugging implementation, we *always* make a copy of the
16241 ** allocation into a new place in memory.  In this way, if the 
16242 ** higher level code is using pointer to the old allocation, it is 
16243 ** much more likely to break and we are much more liking to find
16244 ** the error.
16245 */
16246 static void *sqlite3MemRealloc(void *pPrior, int nByte){
16247   struct MemBlockHdr *pOldHdr;
16248   void *pNew;
16249   assert( mem.disallow==0 );
16250   assert( (nByte & 7)==0 );     /* EV: R-46199-30249 */
16251   pOldHdr = sqlite3MemsysGetHeader(pPrior);
16252   pNew = sqlite3MemMalloc(nByte);
16253   if( pNew ){
16254     memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
16255     if( nByte>pOldHdr->iSize ){
16256       randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - pOldHdr->iSize);
16257     }
16258     sqlite3MemFree(pPrior);
16259   }
16260   return pNew;
16261 }
16262
16263 /*
16264 ** Populate the low-level memory allocation function pointers in
16265 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
16266 */
16267 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
16268   static const sqlite3_mem_methods defaultMethods = {
16269      sqlite3MemMalloc,
16270      sqlite3MemFree,
16271      sqlite3MemRealloc,
16272      sqlite3MemSize,
16273      sqlite3MemRoundup,
16274      sqlite3MemInit,
16275      sqlite3MemShutdown,
16276      0
16277   };
16278   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
16279 }
16280
16281 /*
16282 ** Set the "type" of an allocation.
16283 */
16284 SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
16285   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
16286     struct MemBlockHdr *pHdr;
16287     pHdr = sqlite3MemsysGetHeader(p);
16288     assert( pHdr->iForeGuard==FOREGUARD );
16289     pHdr->eType = eType;
16290   }
16291 }
16292
16293 /*
16294 ** Return TRUE if the mask of type in eType matches the type of the
16295 ** allocation p.  Also return true if p==NULL.
16296 **
16297 ** This routine is designed for use within an assert() statement, to
16298 ** verify the type of an allocation.  For example:
16299 **
16300 **     assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
16301 */
16302 SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
16303   int rc = 1;
16304   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
16305     struct MemBlockHdr *pHdr;
16306     pHdr = sqlite3MemsysGetHeader(p);
16307     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
16308     if( (pHdr->eType&eType)==0 ){
16309       rc = 0;
16310     }
16311   }
16312   return rc;
16313 }
16314
16315 /*
16316 ** Return TRUE if the mask of type in eType matches no bits of the type of the
16317 ** allocation p.  Also return true if p==NULL.
16318 **
16319 ** This routine is designed for use within an assert() statement, to
16320 ** verify the type of an allocation.  For example:
16321 **
16322 **     assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
16323 */
16324 SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
16325   int rc = 1;
16326   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
16327     struct MemBlockHdr *pHdr;
16328     pHdr = sqlite3MemsysGetHeader(p);
16329     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
16330     if( (pHdr->eType&eType)!=0 ){
16331       rc = 0;
16332     }
16333   }
16334   return rc;
16335 }
16336
16337 /*
16338 ** Set the number of backtrace levels kept for each allocation.
16339 ** A value of zero turns off backtracing.  The number is always rounded
16340 ** up to a multiple of 2.
16341 */
16342 SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
16343   if( depth<0 ){ depth = 0; }
16344   if( depth>20 ){ depth = 20; }
16345   depth = (depth+1)&0xfe;
16346   mem.nBacktrace = depth;
16347 }
16348
16349 SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
16350   mem.xBacktrace = xBacktrace;
16351 }
16352
16353 /*
16354 ** Set the title string for subsequent allocations.
16355 */
16356 SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
16357   unsigned int n = sqlite3Strlen30(zTitle) + 1;
16358   sqlite3_mutex_enter(mem.mutex);
16359   if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
16360   memcpy(mem.zTitle, zTitle, n);
16361   mem.zTitle[n] = 0;
16362   mem.nTitle = ROUND8(n);
16363   sqlite3_mutex_leave(mem.mutex);
16364 }
16365
16366 SQLITE_PRIVATE void sqlite3MemdebugSync(){
16367   struct MemBlockHdr *pHdr;
16368   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
16369     void **pBt = (void**)pHdr;
16370     pBt -= pHdr->nBacktraceSlots;
16371     mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
16372   }
16373 }
16374
16375 /*
16376 ** Open the file indicated and write a log of all unfreed memory 
16377 ** allocations into that log.
16378 */
16379 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
16380   FILE *out;
16381   struct MemBlockHdr *pHdr;
16382   void **pBt;
16383   int i;
16384   out = fopen(zFilename, "w");
16385   if( out==0 ){
16386     fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
16387                     zFilename);
16388     return;
16389   }
16390   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
16391     char *z = (char*)pHdr;
16392     z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
16393     fprintf(out, "**** %lld bytes at %p from %s ****\n", 
16394             pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
16395     if( pHdr->nBacktrace ){
16396       fflush(out);
16397       pBt = (void**)pHdr;
16398       pBt -= pHdr->nBacktraceSlots;
16399       backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
16400       fprintf(out, "\n");
16401     }
16402   }
16403   fprintf(out, "COUNTS:\n");
16404   for(i=0; i<NCSIZE-1; i++){
16405     if( mem.nAlloc[i] ){
16406       fprintf(out, "   %5d: %10d %10d %10d\n", 
16407             i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
16408     }
16409   }
16410   if( mem.nAlloc[NCSIZE-1] ){
16411     fprintf(out, "   %5d: %10d %10d %10d\n",
16412              NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
16413              mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
16414   }
16415   fclose(out);
16416 }
16417
16418 /*
16419 ** Return the number of times sqlite3MemMalloc() has been called.
16420 */
16421 SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
16422   int i;
16423   int nTotal = 0;
16424   for(i=0; i<NCSIZE; i++){
16425     nTotal += mem.nAlloc[i];
16426   }
16427   return nTotal;
16428 }
16429
16430
16431 #endif /* SQLITE_MEMDEBUG */
16432
16433 /************** End of mem2.c ************************************************/
16434 /************** Begin file mem3.c ********************************************/
16435 /*
16436 ** 2007 October 14
16437 **
16438 ** The author disclaims copyright to this source code.  In place of
16439 ** a legal notice, here is a blessing:
16440 **
16441 **    May you do good and not evil.
16442 **    May you find forgiveness for yourself and forgive others.
16443 **    May you share freely, never taking more than you give.
16444 **
16445 *************************************************************************
16446 ** This file contains the C functions that implement a memory
16447 ** allocation subsystem for use by SQLite. 
16448 **
16449 ** This version of the memory allocation subsystem omits all
16450 ** use of malloc(). The SQLite user supplies a block of memory
16451 ** before calling sqlite3_initialize() from which allocations
16452 ** are made and returned by the xMalloc() and xRealloc() 
16453 ** implementations. Once sqlite3_initialize() has been called,
16454 ** the amount of memory available to SQLite is fixed and cannot
16455 ** be changed.
16456 **
16457 ** This version of the memory allocation subsystem is included
16458 ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
16459 */
16460
16461 /*
16462 ** This version of the memory allocator is only built into the library
16463 ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
16464 ** mean that the library will use a memory-pool by default, just that
16465 ** it is available. The mempool allocator is activated by calling
16466 ** sqlite3_config().
16467 */
16468 #ifdef SQLITE_ENABLE_MEMSYS3
16469
16470 /*
16471 ** Maximum size (in Mem3Blocks) of a "small" chunk.
16472 */
16473 #define MX_SMALL 10
16474
16475
16476 /*
16477 ** Number of freelist hash slots
16478 */
16479 #define N_HASH  61
16480
16481 /*
16482 ** A memory allocation (also called a "chunk") consists of two or 
16483 ** more blocks where each block is 8 bytes.  The first 8 bytes are 
16484 ** a header that is not returned to the user.
16485 **
16486 ** A chunk is two or more blocks that is either checked out or
16487 ** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
16488 ** size of the allocation in blocks if the allocation is free.
16489 ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
16490 ** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
16491 ** is true if the previous chunk is checked out and false if the
16492 ** previous chunk is free.  The u.hdr.prevSize field is the size of
16493 ** the previous chunk in blocks if the previous chunk is on the
16494 ** freelist. If the previous chunk is checked out, then
16495 ** u.hdr.prevSize can be part of the data for that chunk and should
16496 ** not be read or written.
16497 **
16498 ** We often identify a chunk by its index in mem3.aPool[].  When
16499 ** this is done, the chunk index refers to the second block of
16500 ** the chunk.  In this way, the first chunk has an index of 1.
16501 ** A chunk index of 0 means "no such chunk" and is the equivalent
16502 ** of a NULL pointer.
16503 **
16504 ** The second block of free chunks is of the form u.list.  The
16505 ** two fields form a double-linked list of chunks of related sizes.
16506 ** Pointers to the head of the list are stored in mem3.aiSmall[] 
16507 ** for smaller chunks and mem3.aiHash[] for larger chunks.
16508 **
16509 ** The second block of a chunk is user data if the chunk is checked 
16510 ** out.  If a chunk is checked out, the user data may extend into
16511 ** the u.hdr.prevSize value of the following chunk.
16512 */
16513 typedef struct Mem3Block Mem3Block;
16514 struct Mem3Block {
16515   union {
16516     struct {
16517       u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
16518       u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
16519     } hdr;
16520     struct {
16521       u32 next;       /* Index in mem3.aPool[] of next free chunk */
16522       u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
16523     } list;
16524   } u;
16525 };
16526
16527 /*
16528 ** All of the static variables used by this module are collected
16529 ** into a single structure named "mem3".  This is to keep the
16530 ** static variables organized and to reduce namespace pollution
16531 ** when this module is combined with other in the amalgamation.
16532 */
16533 static SQLITE_WSD struct Mem3Global {
16534   /*
16535   ** Memory available for allocation. nPool is the size of the array
16536   ** (in Mem3Blocks) pointed to by aPool less 2.
16537   */
16538   u32 nPool;
16539   Mem3Block *aPool;
16540
16541   /*
16542   ** True if we are evaluating an out-of-memory callback.
16543   */
16544   int alarmBusy;
16545   
16546   /*
16547   ** Mutex to control access to the memory allocation subsystem.
16548   */
16549   sqlite3_mutex *mutex;
16550   
16551   /*
16552   ** The minimum amount of free space that we have seen.
16553   */
16554   u32 mnMaster;
16555
16556   /*
16557   ** iMaster is the index of the master chunk.  Most new allocations
16558   ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
16559   ** of the current master.  iMaster is 0 if there is not master chunk.
16560   ** The master chunk is not in either the aiHash[] or aiSmall[].
16561   */
16562   u32 iMaster;
16563   u32 szMaster;
16564
16565   /*
16566   ** Array of lists of free blocks according to the block size 
16567   ** for smaller chunks, or a hash on the block size for larger
16568   ** chunks.
16569   */
16570   u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
16571   u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
16572 } mem3 = { 97535575 };
16573
16574 #define mem3 GLOBAL(struct Mem3Global, mem3)
16575
16576 /*
16577 ** Unlink the chunk at mem3.aPool[i] from list it is currently
16578 ** on.  *pRoot is the list that i is a member of.
16579 */
16580 static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
16581   u32 next = mem3.aPool[i].u.list.next;
16582   u32 prev = mem3.aPool[i].u.list.prev;
16583   assert( sqlite3_mutex_held(mem3.mutex) );
16584   if( prev==0 ){
16585     *pRoot = next;
16586   }else{
16587     mem3.aPool[prev].u.list.next = next;
16588   }
16589   if( next ){
16590     mem3.aPool[next].u.list.prev = prev;
16591   }
16592   mem3.aPool[i].u.list.next = 0;
16593   mem3.aPool[i].u.list.prev = 0;
16594 }
16595
16596 /*
16597 ** Unlink the chunk at index i from 
16598 ** whatever list is currently a member of.
16599 */
16600 static void memsys3Unlink(u32 i){
16601   u32 size, hash;
16602   assert( sqlite3_mutex_held(mem3.mutex) );
16603   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
16604   assert( i>=1 );
16605   size = mem3.aPool[i-1].u.hdr.size4x/4;
16606   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
16607   assert( size>=2 );
16608   if( size <= MX_SMALL ){
16609     memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
16610   }else{
16611     hash = size % N_HASH;
16612     memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
16613   }
16614 }
16615
16616 /*
16617 ** Link the chunk at mem3.aPool[i] so that is on the list rooted
16618 ** at *pRoot.
16619 */
16620 static void memsys3LinkIntoList(u32 i, u32 *pRoot){
16621   assert( sqlite3_mutex_held(mem3.mutex) );
16622   mem3.aPool[i].u.list.next = *pRoot;
16623   mem3.aPool[i].u.list.prev = 0;
16624   if( *pRoot ){
16625     mem3.aPool[*pRoot].u.list.prev = i;
16626   }
16627   *pRoot = i;
16628 }
16629
16630 /*
16631 ** Link the chunk at index i into either the appropriate
16632 ** small chunk list, or into the large chunk hash table.
16633 */
16634 static void memsys3Link(u32 i){
16635   u32 size, hash;
16636   assert( sqlite3_mutex_held(mem3.mutex) );
16637   assert( i>=1 );
16638   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
16639   size = mem3.aPool[i-1].u.hdr.size4x/4;
16640   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
16641   assert( size>=2 );
16642   if( size <= MX_SMALL ){
16643     memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
16644   }else{
16645     hash = size % N_HASH;
16646     memsys3LinkIntoList(i, &mem3.aiHash[hash]);
16647   }
16648 }
16649
16650 /*
16651 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
16652 ** will already be held (obtained by code in malloc.c) if
16653 ** sqlite3GlobalConfig.bMemStat is true.
16654 */
16655 static void memsys3Enter(void){
16656   if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
16657     mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
16658   }
16659   sqlite3_mutex_enter(mem3.mutex);
16660 }
16661 static void memsys3Leave(void){
16662   sqlite3_mutex_leave(mem3.mutex);
16663 }
16664
16665 /*
16666 ** Called when we are unable to satisfy an allocation of nBytes.
16667 */
16668 static void memsys3OutOfMemory(int nByte){
16669   if( !mem3.alarmBusy ){
16670     mem3.alarmBusy = 1;
16671     assert( sqlite3_mutex_held(mem3.mutex) );
16672     sqlite3_mutex_leave(mem3.mutex);
16673     sqlite3_release_memory(nByte);
16674     sqlite3_mutex_enter(mem3.mutex);
16675     mem3.alarmBusy = 0;
16676   }
16677 }
16678
16679
16680 /*
16681 ** Chunk i is a free chunk that has been unlinked.  Adjust its 
16682 ** size parameters for check-out and return a pointer to the 
16683 ** user portion of the chunk.
16684 */
16685 static void *memsys3Checkout(u32 i, u32 nBlock){
16686   u32 x;
16687   assert( sqlite3_mutex_held(mem3.mutex) );
16688   assert( i>=1 );
16689   assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
16690   assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
16691   x = mem3.aPool[i-1].u.hdr.size4x;
16692   mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
16693   mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
16694   mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
16695   return &mem3.aPool[i];
16696 }
16697
16698 /*
16699 ** Carve a piece off of the end of the mem3.iMaster free chunk.
16700 ** Return a pointer to the new allocation.  Or, if the master chunk
16701 ** is not large enough, return 0.
16702 */
16703 static void *memsys3FromMaster(u32 nBlock){
16704   assert( sqlite3_mutex_held(mem3.mutex) );
16705   assert( mem3.szMaster>=nBlock );
16706   if( nBlock>=mem3.szMaster-1 ){
16707     /* Use the entire master */
16708     void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
16709     mem3.iMaster = 0;
16710     mem3.szMaster = 0;
16711     mem3.mnMaster = 0;
16712     return p;
16713   }else{
16714     /* Split the master block.  Return the tail. */
16715     u32 newi, x;
16716     newi = mem3.iMaster + mem3.szMaster - nBlock;
16717     assert( newi > mem3.iMaster+1 );
16718     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
16719     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
16720     mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
16721     mem3.szMaster -= nBlock;
16722     mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
16723     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
16724     mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
16725     if( mem3.szMaster < mem3.mnMaster ){
16726       mem3.mnMaster = mem3.szMaster;
16727     }
16728     return (void*)&mem3.aPool[newi];
16729   }
16730 }
16731
16732 /*
16733 ** *pRoot is the head of a list of free chunks of the same size
16734 ** or same size hash.  In other words, *pRoot is an entry in either
16735 ** mem3.aiSmall[] or mem3.aiHash[].  
16736 **
16737 ** This routine examines all entries on the given list and tries
16738 ** to coalesce each entries with adjacent free chunks.  
16739 **
16740 ** If it sees a chunk that is larger than mem3.iMaster, it replaces 
16741 ** the current mem3.iMaster with the new larger chunk.  In order for
16742 ** this mem3.iMaster replacement to work, the master chunk must be
16743 ** linked into the hash tables.  That is not the normal state of
16744 ** affairs, of course.  The calling routine must link the master
16745 ** chunk before invoking this routine, then must unlink the (possibly
16746 ** changed) master chunk once this routine has finished.
16747 */
16748 static void memsys3Merge(u32 *pRoot){
16749   u32 iNext, prev, size, i, x;
16750
16751   assert( sqlite3_mutex_held(mem3.mutex) );
16752   for(i=*pRoot; i>0; i=iNext){
16753     iNext = mem3.aPool[i].u.list.next;
16754     size = mem3.aPool[i-1].u.hdr.size4x;
16755     assert( (size&1)==0 );
16756     if( (size&2)==0 ){
16757       memsys3UnlinkFromList(i, pRoot);
16758       assert( i > mem3.aPool[i-1].u.hdr.prevSize );
16759       prev = i - mem3.aPool[i-1].u.hdr.prevSize;
16760       if( prev==iNext ){
16761         iNext = mem3.aPool[prev].u.list.next;
16762       }
16763       memsys3Unlink(prev);
16764       size = i + size/4 - prev;
16765       x = mem3.aPool[prev-1].u.hdr.size4x & 2;
16766       mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
16767       mem3.aPool[prev+size-1].u.hdr.prevSize = size;
16768       memsys3Link(prev);
16769       i = prev;
16770     }else{
16771       size /= 4;
16772     }
16773     if( size>mem3.szMaster ){
16774       mem3.iMaster = i;
16775       mem3.szMaster = size;
16776     }
16777   }
16778 }
16779
16780 /*
16781 ** Return a block of memory of at least nBytes in size.
16782 ** Return NULL if unable.
16783 **
16784 ** This function assumes that the necessary mutexes, if any, are
16785 ** already held by the caller. Hence "Unsafe".
16786 */
16787 static void *memsys3MallocUnsafe(int nByte){
16788   u32 i;
16789   u32 nBlock;
16790   u32 toFree;
16791
16792   assert( sqlite3_mutex_held(mem3.mutex) );
16793   assert( sizeof(Mem3Block)==8 );
16794   if( nByte<=12 ){
16795     nBlock = 2;
16796   }else{
16797     nBlock = (nByte + 11)/8;
16798   }
16799   assert( nBlock>=2 );
16800
16801   /* STEP 1:
16802   ** Look for an entry of the correct size in either the small
16803   ** chunk table or in the large chunk hash table.  This is
16804   ** successful most of the time (about 9 times out of 10).
16805   */
16806   if( nBlock <= MX_SMALL ){
16807     i = mem3.aiSmall[nBlock-2];
16808     if( i>0 ){
16809       memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
16810       return memsys3Checkout(i, nBlock);
16811     }
16812   }else{
16813     int hash = nBlock % N_HASH;
16814     for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
16815       if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
16816         memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
16817         return memsys3Checkout(i, nBlock);
16818       }
16819     }
16820   }
16821
16822   /* STEP 2:
16823   ** Try to satisfy the allocation by carving a piece off of the end
16824   ** of the master chunk.  This step usually works if step 1 fails.
16825   */
16826   if( mem3.szMaster>=nBlock ){
16827     return memsys3FromMaster(nBlock);
16828   }
16829
16830
16831   /* STEP 3:  
16832   ** Loop through the entire memory pool.  Coalesce adjacent free
16833   ** chunks.  Recompute the master chunk as the largest free chunk.
16834   ** Then try again to satisfy the allocation by carving a piece off
16835   ** of the end of the master chunk.  This step happens very
16836   ** rarely (we hope!)
16837   */
16838   for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
16839     memsys3OutOfMemory(toFree);
16840     if( mem3.iMaster ){
16841       memsys3Link(mem3.iMaster);
16842       mem3.iMaster = 0;
16843       mem3.szMaster = 0;
16844     }
16845     for(i=0; i<N_HASH; i++){
16846       memsys3Merge(&mem3.aiHash[i]);
16847     }
16848     for(i=0; i<MX_SMALL-1; i++){
16849       memsys3Merge(&mem3.aiSmall[i]);
16850     }
16851     if( mem3.szMaster ){
16852       memsys3Unlink(mem3.iMaster);
16853       if( mem3.szMaster>=nBlock ){
16854         return memsys3FromMaster(nBlock);
16855       }
16856     }
16857   }
16858
16859   /* If none of the above worked, then we fail. */
16860   return 0;
16861 }
16862
16863 /*
16864 ** Free an outstanding memory allocation.
16865 **
16866 ** This function assumes that the necessary mutexes, if any, are
16867 ** already held by the caller. Hence "Unsafe".
16868 */
16869 static void memsys3FreeUnsafe(void *pOld){
16870   Mem3Block *p = (Mem3Block*)pOld;
16871   int i;
16872   u32 size, x;
16873   assert( sqlite3_mutex_held(mem3.mutex) );
16874   assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
16875   i = p - mem3.aPool;
16876   assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
16877   size = mem3.aPool[i-1].u.hdr.size4x/4;
16878   assert( i+size<=mem3.nPool+1 );
16879   mem3.aPool[i-1].u.hdr.size4x &= ~1;
16880   mem3.aPool[i+size-1].u.hdr.prevSize = size;
16881   mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
16882   memsys3Link(i);
16883
16884   /* Try to expand the master using the newly freed chunk */
16885   if( mem3.iMaster ){
16886     while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
16887       size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
16888       mem3.iMaster -= size;
16889       mem3.szMaster += size;
16890       memsys3Unlink(mem3.iMaster);
16891       x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
16892       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
16893       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
16894     }
16895     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
16896     while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
16897       memsys3Unlink(mem3.iMaster+mem3.szMaster);
16898       mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
16899       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
16900       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
16901     }
16902   }
16903 }
16904
16905 /*
16906 ** Return the size of an outstanding allocation, in bytes.  The
16907 ** size returned omits the 8-byte header overhead.  This only
16908 ** works for chunks that are currently checked out.
16909 */
16910 static int memsys3Size(void *p){
16911   Mem3Block *pBlock;
16912   if( p==0 ) return 0;
16913   pBlock = (Mem3Block*)p;
16914   assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
16915   return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
16916 }
16917
16918 /*
16919 ** Round up a request size to the next valid allocation size.
16920 */
16921 static int memsys3Roundup(int n){
16922   if( n<=12 ){
16923     return 12;
16924   }else{
16925     return ((n+11)&~7) - 4;
16926   }
16927 }
16928
16929 /*
16930 ** Allocate nBytes of memory.
16931 */
16932 static void *memsys3Malloc(int nBytes){
16933   sqlite3_int64 *p;
16934   assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
16935   memsys3Enter();
16936   p = memsys3MallocUnsafe(nBytes);
16937   memsys3Leave();
16938   return (void*)p; 
16939 }
16940
16941 /*
16942 ** Free memory.
16943 */
16944 static void memsys3Free(void *pPrior){
16945   assert( pPrior );
16946   memsys3Enter();
16947   memsys3FreeUnsafe(pPrior);
16948   memsys3Leave();
16949 }
16950
16951 /*
16952 ** Change the size of an existing memory allocation
16953 */
16954 static void *memsys3Realloc(void *pPrior, int nBytes){
16955   int nOld;
16956   void *p;
16957   if( pPrior==0 ){
16958     return sqlite3_malloc(nBytes);
16959   }
16960   if( nBytes<=0 ){
16961     sqlite3_free(pPrior);
16962     return 0;
16963   }
16964   nOld = memsys3Size(pPrior);
16965   if( nBytes<=nOld && nBytes>=nOld-128 ){
16966     return pPrior;
16967   }
16968   memsys3Enter();
16969   p = memsys3MallocUnsafe(nBytes);
16970   if( p ){
16971     if( nOld<nBytes ){
16972       memcpy(p, pPrior, nOld);
16973     }else{
16974       memcpy(p, pPrior, nBytes);
16975     }
16976     memsys3FreeUnsafe(pPrior);
16977   }
16978   memsys3Leave();
16979   return p;
16980 }
16981
16982 /*
16983 ** Initialize this module.
16984 */
16985 static int memsys3Init(void *NotUsed){
16986   UNUSED_PARAMETER(NotUsed);
16987   if( !sqlite3GlobalConfig.pHeap ){
16988     return SQLITE_ERROR;
16989   }
16990
16991   /* Store a pointer to the memory block in global structure mem3. */
16992   assert( sizeof(Mem3Block)==8 );
16993   mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
16994   mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
16995
16996   /* Initialize the master block. */
16997   mem3.szMaster = mem3.nPool;
16998   mem3.mnMaster = mem3.szMaster;
16999   mem3.iMaster = 1;
17000   mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
17001   mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
17002   mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
17003
17004   return SQLITE_OK;
17005 }
17006
17007 /*
17008 ** Deinitialize this module.
17009 */
17010 static void memsys3Shutdown(void *NotUsed){
17011   UNUSED_PARAMETER(NotUsed);
17012   mem3.mutex = 0;
17013   return;
17014 }
17015
17016
17017
17018 /*
17019 ** Open the file indicated and write a log of all unfreed memory 
17020 ** allocations into that log.
17021 */
17022 SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
17023 #ifdef SQLITE_DEBUG
17024   FILE *out;
17025   u32 i, j;
17026   u32 size;
17027   if( zFilename==0 || zFilename[0]==0 ){
17028     out = stdout;
17029   }else{
17030     out = fopen(zFilename, "w");
17031     if( out==0 ){
17032       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
17033                       zFilename);
17034       return;
17035     }
17036   }
17037   memsys3Enter();
17038   fprintf(out, "CHUNKS:\n");
17039   for(i=1; i<=mem3.nPool; i+=size/4){
17040     size = mem3.aPool[i-1].u.hdr.size4x;
17041     if( size/4<=1 ){
17042       fprintf(out, "%p size error\n", &mem3.aPool[i]);
17043       assert( 0 );
17044       break;
17045     }
17046     if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
17047       fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
17048       assert( 0 );
17049       break;
17050     }
17051     if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
17052       fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
17053       assert( 0 );
17054       break;
17055     }
17056     if( size&1 ){
17057       fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
17058     }else{
17059       fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
17060                   i==mem3.iMaster ? " **master**" : "");
17061     }
17062   }
17063   for(i=0; i<MX_SMALL-1; i++){
17064     if( mem3.aiSmall[i]==0 ) continue;
17065     fprintf(out, "small(%2d):", i);
17066     for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
17067       fprintf(out, " %p(%d)", &mem3.aPool[j],
17068               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
17069     }
17070     fprintf(out, "\n"); 
17071   }
17072   for(i=0; i<N_HASH; i++){
17073     if( mem3.aiHash[i]==0 ) continue;
17074     fprintf(out, "hash(%2d):", i);
17075     for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
17076       fprintf(out, " %p(%d)", &mem3.aPool[j],
17077               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
17078     }
17079     fprintf(out, "\n"); 
17080   }
17081   fprintf(out, "master=%d\n", mem3.iMaster);
17082   fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
17083   fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
17084   sqlite3_mutex_leave(mem3.mutex);
17085   if( out==stdout ){
17086     fflush(stdout);
17087   }else{
17088     fclose(out);
17089   }
17090 #else
17091   UNUSED_PARAMETER(zFilename);
17092 #endif
17093 }
17094
17095 /*
17096 ** This routine is the only routine in this file with external 
17097 ** linkage.
17098 **
17099 ** Populate the low-level memory allocation function pointers in
17100 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
17101 ** arguments specify the block of memory to manage.
17102 **
17103 ** This routine is only called by sqlite3_config(), and therefore
17104 ** is not required to be threadsafe (it is not).
17105 */
17106 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
17107   static const sqlite3_mem_methods mempoolMethods = {
17108      memsys3Malloc,
17109      memsys3Free,
17110      memsys3Realloc,
17111      memsys3Size,
17112      memsys3Roundup,
17113      memsys3Init,
17114      memsys3Shutdown,
17115      0
17116   };
17117   return &mempoolMethods;
17118 }
17119
17120 #endif /* SQLITE_ENABLE_MEMSYS3 */
17121
17122 /************** End of mem3.c ************************************************/
17123 /************** Begin file mem5.c ********************************************/
17124 /*
17125 ** 2007 October 14
17126 **
17127 ** The author disclaims copyright to this source code.  In place of
17128 ** a legal notice, here is a blessing:
17129 **
17130 **    May you do good and not evil.
17131 **    May you find forgiveness for yourself and forgive others.
17132 **    May you share freely, never taking more than you give.
17133 **
17134 *************************************************************************
17135 ** This file contains the C functions that implement a memory
17136 ** allocation subsystem for use by SQLite. 
17137 **
17138 ** This version of the memory allocation subsystem omits all
17139 ** use of malloc(). The application gives SQLite a block of memory
17140 ** before calling sqlite3_initialize() from which allocations
17141 ** are made and returned by the xMalloc() and xRealloc() 
17142 ** implementations. Once sqlite3_initialize() has been called,
17143 ** the amount of memory available to SQLite is fixed and cannot
17144 ** be changed.
17145 **
17146 ** This version of the memory allocation subsystem is included
17147 ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
17148 **
17149 ** This memory allocator uses the following algorithm:
17150 **
17151 **   1.  All memory allocations sizes are rounded up to a power of 2.
17152 **
17153 **   2.  If two adjacent free blocks are the halves of a larger block,
17154 **       then the two blocks are coalesed into the single larger block.
17155 **
17156 **   3.  New memory is allocated from the first available free block.
17157 **
17158 ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
17159 ** Concerning Dynamic Storage Allocation". Journal of the Association for
17160 ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
17161 ** 
17162 ** Let n be the size of the largest allocation divided by the minimum
17163 ** allocation size (after rounding all sizes up to a power of 2.)  Let M
17164 ** be the maximum amount of memory ever outstanding at one time.  Let
17165 ** N be the total amount of memory available for allocation.  Robson
17166 ** proved that this memory allocator will never breakdown due to 
17167 ** fragmentation as long as the following constraint holds:
17168 **
17169 **      N >=  M*(1 + log2(n)/2) - n + 1
17170 **
17171 ** The sqlite3_status() logic tracks the maximum values of n and M so
17172 ** that an application can, at any time, verify this constraint.
17173 */
17174
17175 /*
17176 ** This version of the memory allocator is used only when 
17177 ** SQLITE_ENABLE_MEMSYS5 is defined.
17178 */
17179 #ifdef SQLITE_ENABLE_MEMSYS5
17180
17181 /*
17182 ** A minimum allocation is an instance of the following structure.
17183 ** Larger allocations are an array of these structures where the
17184 ** size of the array is a power of 2.
17185 **
17186 ** The size of this object must be a power of two.  That fact is
17187 ** verified in memsys5Init().
17188 */
17189 typedef struct Mem5Link Mem5Link;
17190 struct Mem5Link {
17191   int next;       /* Index of next free chunk */
17192   int prev;       /* Index of previous free chunk */
17193 };
17194
17195 /*
17196 ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
17197 ** mem5.szAtom is always at least 8 and 32-bit integers are used,
17198 ** it is not actually possible to reach this limit.
17199 */
17200 #define LOGMAX 30
17201
17202 /*
17203 ** Masks used for mem5.aCtrl[] elements.
17204 */
17205 #define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
17206 #define CTRL_FREE     0x20    /* True if not checked out */
17207
17208 /*
17209 ** All of the static variables used by this module are collected
17210 ** into a single structure named "mem5".  This is to keep the
17211 ** static variables organized and to reduce namespace pollution
17212 ** when this module is combined with other in the amalgamation.
17213 */
17214 static SQLITE_WSD struct Mem5Global {
17215   /*
17216   ** Memory available for allocation
17217   */
17218   int szAtom;      /* Smallest possible allocation in bytes */
17219   int nBlock;      /* Number of szAtom sized blocks in zPool */
17220   u8 *zPool;       /* Memory available to be allocated */
17221   
17222   /*
17223   ** Mutex to control access to the memory allocation subsystem.
17224   */
17225   sqlite3_mutex *mutex;
17226
17227   /*
17228   ** Performance statistics
17229   */
17230   u64 nAlloc;         /* Total number of calls to malloc */
17231   u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
17232   u64 totalExcess;    /* Total internal fragmentation */
17233   u32 currentOut;     /* Current checkout, including internal fragmentation */
17234   u32 currentCount;   /* Current number of distinct checkouts */
17235   u32 maxOut;         /* Maximum instantaneous currentOut */
17236   u32 maxCount;       /* Maximum instantaneous currentCount */
17237   u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
17238   
17239   /*
17240   ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
17241   ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
17242   ** and so forth.
17243   */
17244   int aiFreelist[LOGMAX+1];
17245
17246   /*
17247   ** Space for tracking which blocks are checked out and the size
17248   ** of each block.  One byte per block.
17249   */
17250   u8 *aCtrl;
17251
17252 } mem5;
17253
17254 /*
17255 ** Access the static variable through a macro for SQLITE_OMIT_WSD
17256 */
17257 #define mem5 GLOBAL(struct Mem5Global, mem5)
17258
17259 /*
17260 ** Assuming mem5.zPool is divided up into an array of Mem5Link
17261 ** structures, return a pointer to the idx-th such lik.
17262 */
17263 #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
17264
17265 /*
17266 ** Unlink the chunk at mem5.aPool[i] from list it is currently
17267 ** on.  It should be found on mem5.aiFreelist[iLogsize].
17268 */
17269 static void memsys5Unlink(int i, int iLogsize){
17270   int next, prev;
17271   assert( i>=0 && i<mem5.nBlock );
17272   assert( iLogsize>=0 && iLogsize<=LOGMAX );
17273   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
17274
17275   next = MEM5LINK(i)->next;
17276   prev = MEM5LINK(i)->prev;
17277   if( prev<0 ){
17278     mem5.aiFreelist[iLogsize] = next;
17279   }else{
17280     MEM5LINK(prev)->next = next;
17281   }
17282   if( next>=0 ){
17283     MEM5LINK(next)->prev = prev;
17284   }
17285 }
17286
17287 /*
17288 ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
17289 ** free list.
17290 */
17291 static void memsys5Link(int i, int iLogsize){
17292   int x;
17293   assert( sqlite3_mutex_held(mem5.mutex) );
17294   assert( i>=0 && i<mem5.nBlock );
17295   assert( iLogsize>=0 && iLogsize<=LOGMAX );
17296   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
17297
17298   x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
17299   MEM5LINK(i)->prev = -1;
17300   if( x>=0 ){
17301     assert( x<mem5.nBlock );
17302     MEM5LINK(x)->prev = i;
17303   }
17304   mem5.aiFreelist[iLogsize] = i;
17305 }
17306
17307 /*
17308 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
17309 ** will already be held (obtained by code in malloc.c) if
17310 ** sqlite3GlobalConfig.bMemStat is true.
17311 */
17312 static void memsys5Enter(void){
17313   sqlite3_mutex_enter(mem5.mutex);
17314 }
17315 static void memsys5Leave(void){
17316   sqlite3_mutex_leave(mem5.mutex);
17317 }
17318
17319 /*
17320 ** Return the size of an outstanding allocation, in bytes.  The
17321 ** size returned omits the 8-byte header overhead.  This only
17322 ** works for chunks that are currently checked out.
17323 */
17324 static int memsys5Size(void *p){
17325   int iSize = 0;
17326   if( p ){
17327     int i = ((u8 *)p-mem5.zPool)/mem5.szAtom;
17328     assert( i>=0 && i<mem5.nBlock );
17329     iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
17330   }
17331   return iSize;
17332 }
17333
17334 /*
17335 ** Find the first entry on the freelist iLogsize.  Unlink that
17336 ** entry and return its index. 
17337 */
17338 static int memsys5UnlinkFirst(int iLogsize){
17339   int i;
17340   int iFirst;
17341
17342   assert( iLogsize>=0 && iLogsize<=LOGMAX );
17343   i = iFirst = mem5.aiFreelist[iLogsize];
17344   assert( iFirst>=0 );
17345   while( i>0 ){
17346     if( i<iFirst ) iFirst = i;
17347     i = MEM5LINK(i)->next;
17348   }
17349   memsys5Unlink(iFirst, iLogsize);
17350   return iFirst;
17351 }
17352
17353 /*
17354 ** Return a block of memory of at least nBytes in size.
17355 ** Return NULL if unable.  Return NULL if nBytes==0.
17356 **
17357 ** The caller guarantees that nByte positive.
17358 **
17359 ** The caller has obtained a mutex prior to invoking this
17360 ** routine so there is never any chance that two or more
17361 ** threads can be in this routine at the same time.
17362 */
17363 static void *memsys5MallocUnsafe(int nByte){
17364   int i;           /* Index of a mem5.aPool[] slot */
17365   int iBin;        /* Index into mem5.aiFreelist[] */
17366   int iFullSz;     /* Size of allocation rounded up to power of 2 */
17367   int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
17368
17369   /* nByte must be a positive */
17370   assert( nByte>0 );
17371
17372   /* Keep track of the maximum allocation request.  Even unfulfilled
17373   ** requests are counted */
17374   if( (u32)nByte>mem5.maxRequest ){
17375     mem5.maxRequest = nByte;
17376   }
17377
17378   /* Abort if the requested allocation size is larger than the largest
17379   ** power of two that we can represent using 32-bit signed integers.
17380   */
17381   if( nByte > 0x40000000 ){
17382     return 0;
17383   }
17384
17385   /* Round nByte up to the next valid power of two */
17386   for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
17387
17388   /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
17389   ** block.  If not, then split a block of the next larger power of
17390   ** two in order to create a new free block of size iLogsize.
17391   */
17392   for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
17393   if( iBin>LOGMAX ){
17394     testcase( sqlite3GlobalConfig.xLog!=0 );
17395     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
17396     return 0;
17397   }
17398   i = memsys5UnlinkFirst(iBin);
17399   while( iBin>iLogsize ){
17400     int newSize;
17401
17402     iBin--;
17403     newSize = 1 << iBin;
17404     mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
17405     memsys5Link(i+newSize, iBin);
17406   }
17407   mem5.aCtrl[i] = iLogsize;
17408
17409   /* Update allocator performance statistics. */
17410   mem5.nAlloc++;
17411   mem5.totalAlloc += iFullSz;
17412   mem5.totalExcess += iFullSz - nByte;
17413   mem5.currentCount++;
17414   mem5.currentOut += iFullSz;
17415   if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
17416   if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
17417
17418   /* Return a pointer to the allocated memory. */
17419   return (void*)&mem5.zPool[i*mem5.szAtom];
17420 }
17421
17422 /*
17423 ** Free an outstanding memory allocation.
17424 */
17425 static void memsys5FreeUnsafe(void *pOld){
17426   u32 size, iLogsize;
17427   int iBlock;
17428
17429   /* Set iBlock to the index of the block pointed to by pOld in 
17430   ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
17431   */
17432   iBlock = ((u8 *)pOld-mem5.zPool)/mem5.szAtom;
17433
17434   /* Check that the pointer pOld points to a valid, non-free block. */
17435   assert( iBlock>=0 && iBlock<mem5.nBlock );
17436   assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
17437   assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
17438
17439   iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
17440   size = 1<<iLogsize;
17441   assert( iBlock+size-1<(u32)mem5.nBlock );
17442
17443   mem5.aCtrl[iBlock] |= CTRL_FREE;
17444   mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
17445   assert( mem5.currentCount>0 );
17446   assert( mem5.currentOut>=(size*mem5.szAtom) );
17447   mem5.currentCount--;
17448   mem5.currentOut -= size*mem5.szAtom;
17449   assert( mem5.currentOut>0 || mem5.currentCount==0 );
17450   assert( mem5.currentCount>0 || mem5.currentOut==0 );
17451
17452   mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
17453   while( ALWAYS(iLogsize<LOGMAX) ){
17454     int iBuddy;
17455     if( (iBlock>>iLogsize) & 1 ){
17456       iBuddy = iBlock - size;
17457     }else{
17458       iBuddy = iBlock + size;
17459     }
17460     assert( iBuddy>=0 );
17461     if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
17462     if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
17463     memsys5Unlink(iBuddy, iLogsize);
17464     iLogsize++;
17465     if( iBuddy<iBlock ){
17466       mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
17467       mem5.aCtrl[iBlock] = 0;
17468       iBlock = iBuddy;
17469     }else{
17470       mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
17471       mem5.aCtrl[iBuddy] = 0;
17472     }
17473     size *= 2;
17474   }
17475   memsys5Link(iBlock, iLogsize);
17476 }
17477
17478 /*
17479 ** Allocate nBytes of memory
17480 */
17481 static void *memsys5Malloc(int nBytes){
17482   sqlite3_int64 *p = 0;
17483   if( nBytes>0 ){
17484     memsys5Enter();
17485     p = memsys5MallocUnsafe(nBytes);
17486     memsys5Leave();
17487   }
17488   return (void*)p; 
17489 }
17490
17491 /*
17492 ** Free memory.
17493 **
17494 ** The outer layer memory allocator prevents this routine from
17495 ** being called with pPrior==0.
17496 */
17497 static void memsys5Free(void *pPrior){
17498   assert( pPrior!=0 );
17499   memsys5Enter();
17500   memsys5FreeUnsafe(pPrior);
17501   memsys5Leave();  
17502 }
17503
17504 /*
17505 ** Change the size of an existing memory allocation.
17506 **
17507 ** The outer layer memory allocator prevents this routine from
17508 ** being called with pPrior==0.  
17509 **
17510 ** nBytes is always a value obtained from a prior call to
17511 ** memsys5Round().  Hence nBytes is always a non-negative power
17512 ** of two.  If nBytes==0 that means that an oversize allocation
17513 ** (an allocation larger than 0x40000000) was requested and this
17514 ** routine should return 0 without freeing pPrior.
17515 */
17516 static void *memsys5Realloc(void *pPrior, int nBytes){
17517   int nOld;
17518   void *p;
17519   assert( pPrior!=0 );
17520   assert( (nBytes&(nBytes-1))==0 );  /* EV: R-46199-30249 */
17521   assert( nBytes>=0 );
17522   if( nBytes==0 ){
17523     return 0;
17524   }
17525   nOld = memsys5Size(pPrior);
17526   if( nBytes<=nOld ){
17527     return pPrior;
17528   }
17529   memsys5Enter();
17530   p = memsys5MallocUnsafe(nBytes);
17531   if( p ){
17532     memcpy(p, pPrior, nOld);
17533     memsys5FreeUnsafe(pPrior);
17534   }
17535   memsys5Leave();
17536   return p;
17537 }
17538
17539 /*
17540 ** Round up a request size to the next valid allocation size.  If
17541 ** the allocation is too large to be handled by this allocation system,
17542 ** return 0.
17543 **
17544 ** All allocations must be a power of two and must be expressed by a
17545 ** 32-bit signed integer.  Hence the largest allocation is 0x40000000
17546 ** or 1073741824 bytes.
17547 */
17548 static int memsys5Roundup(int n){
17549   int iFullSz;
17550   if( n > 0x40000000 ) return 0;
17551   for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
17552   return iFullSz;
17553 }
17554
17555 /*
17556 ** Return the ceiling of the logarithm base 2 of iValue.
17557 **
17558 ** Examples:   memsys5Log(1) -> 0
17559 **             memsys5Log(2) -> 1
17560 **             memsys5Log(4) -> 2
17561 **             memsys5Log(5) -> 3
17562 **             memsys5Log(8) -> 3
17563 **             memsys5Log(9) -> 4
17564 */
17565 static int memsys5Log(int iValue){
17566   int iLog;
17567   for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
17568   return iLog;
17569 }
17570
17571 /*
17572 ** Initialize the memory allocator.
17573 **
17574 ** This routine is not threadsafe.  The caller must be holding a mutex
17575 ** to prevent multiple threads from entering at the same time.
17576 */
17577 static int memsys5Init(void *NotUsed){
17578   int ii;            /* Loop counter */
17579   int nByte;         /* Number of bytes of memory available to this allocator */
17580   u8 *zByte;         /* Memory usable by this allocator */
17581   int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
17582   int iOffset;       /* An offset into mem5.aCtrl[] */
17583
17584   UNUSED_PARAMETER(NotUsed);
17585
17586   /* For the purposes of this routine, disable the mutex */
17587   mem5.mutex = 0;
17588
17589   /* The size of a Mem5Link object must be a power of two.  Verify that
17590   ** this is case.
17591   */
17592   assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
17593
17594   nByte = sqlite3GlobalConfig.nHeap;
17595   zByte = (u8*)sqlite3GlobalConfig.pHeap;
17596   assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */
17597
17598   /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
17599   nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
17600   mem5.szAtom = (1<<nMinLog);
17601   while( (int)sizeof(Mem5Link)>mem5.szAtom ){
17602     mem5.szAtom = mem5.szAtom << 1;
17603   }
17604
17605   mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
17606   mem5.zPool = zByte;
17607   mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
17608
17609   for(ii=0; ii<=LOGMAX; ii++){
17610     mem5.aiFreelist[ii] = -1;
17611   }
17612
17613   iOffset = 0;
17614   for(ii=LOGMAX; ii>=0; ii--){
17615     int nAlloc = (1<<ii);
17616     if( (iOffset+nAlloc)<=mem5.nBlock ){
17617       mem5.aCtrl[iOffset] = ii | CTRL_FREE;
17618       memsys5Link(iOffset, ii);
17619       iOffset += nAlloc;
17620     }
17621     assert((iOffset+nAlloc)>mem5.nBlock);
17622   }
17623
17624   /* If a mutex is required for normal operation, allocate one */
17625   if( sqlite3GlobalConfig.bMemstat==0 ){
17626     mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
17627   }
17628
17629   return SQLITE_OK;
17630 }
17631
17632 /*
17633 ** Deinitialize this module.
17634 */
17635 static void memsys5Shutdown(void *NotUsed){
17636   UNUSED_PARAMETER(NotUsed);
17637   mem5.mutex = 0;
17638   return;
17639 }
17640
17641 #ifdef SQLITE_TEST
17642 /*
17643 ** Open the file indicated and write a log of all unfreed memory 
17644 ** allocations into that log.
17645 */
17646 SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
17647   FILE *out;
17648   int i, j, n;
17649   int nMinLog;
17650
17651   if( zFilename==0 || zFilename[0]==0 ){
17652     out = stdout;
17653   }else{
17654     out = fopen(zFilename, "w");
17655     if( out==0 ){
17656       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
17657                       zFilename);
17658       return;
17659     }
17660   }
17661   memsys5Enter();
17662   nMinLog = memsys5Log(mem5.szAtom);
17663   for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
17664     for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
17665     fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
17666   }
17667   fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
17668   fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
17669   fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
17670   fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
17671   fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
17672   fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
17673   fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
17674   fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
17675   memsys5Leave();
17676   if( out==stdout ){
17677     fflush(stdout);
17678   }else{
17679     fclose(out);
17680   }
17681 }
17682 #endif
17683
17684 /*
17685 ** This routine is the only routine in this file with external 
17686 ** linkage. It returns a pointer to a static sqlite3_mem_methods
17687 ** struct populated with the memsys5 methods.
17688 */
17689 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
17690   static const sqlite3_mem_methods memsys5Methods = {
17691      memsys5Malloc,
17692      memsys5Free,
17693      memsys5Realloc,
17694      memsys5Size,
17695      memsys5Roundup,
17696      memsys5Init,
17697      memsys5Shutdown,
17698      0
17699   };
17700   return &memsys5Methods;
17701 }
17702
17703 #endif /* SQLITE_ENABLE_MEMSYS5 */
17704
17705 /************** End of mem5.c ************************************************/
17706 /************** Begin file mutex.c *******************************************/
17707 /*
17708 ** 2007 August 14
17709 **
17710 ** The author disclaims copyright to this source code.  In place of
17711 ** a legal notice, here is a blessing:
17712 **
17713 **    May you do good and not evil.
17714 **    May you find forgiveness for yourself and forgive others.
17715 **    May you share freely, never taking more than you give.
17716 **
17717 *************************************************************************
17718 ** This file contains the C functions that implement mutexes.
17719 **
17720 ** This file contains code that is common across all mutex implementations.
17721 */
17722
17723 #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
17724 /*
17725 ** For debugging purposes, record when the mutex subsystem is initialized
17726 ** and uninitialized so that we can assert() if there is an attempt to
17727 ** allocate a mutex while the system is uninitialized.
17728 */
17729 static SQLITE_WSD int mutexIsInit = 0;
17730 #endif /* SQLITE_DEBUG */
17731
17732
17733 #ifndef SQLITE_MUTEX_OMIT
17734 /*
17735 ** Initialize the mutex system.
17736 */
17737 SQLITE_PRIVATE int sqlite3MutexInit(void){ 
17738   int rc = SQLITE_OK;
17739   if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
17740     /* If the xMutexAlloc method has not been set, then the user did not
17741     ** install a mutex implementation via sqlite3_config() prior to 
17742     ** sqlite3_initialize() being called. This block copies pointers to
17743     ** the default implementation into the sqlite3GlobalConfig structure.
17744     */
17745     sqlite3_mutex_methods const *pFrom;
17746     sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
17747
17748     if( sqlite3GlobalConfig.bCoreMutex ){
17749       pFrom = sqlite3DefaultMutex();
17750     }else{
17751       pFrom = sqlite3NoopMutex();
17752     }
17753     memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
17754     memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
17755            sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
17756     pTo->xMutexAlloc = pFrom->xMutexAlloc;
17757   }
17758   rc = sqlite3GlobalConfig.mutex.xMutexInit();
17759
17760 #ifdef SQLITE_DEBUG
17761   GLOBAL(int, mutexIsInit) = 1;
17762 #endif
17763
17764   return rc;
17765 }
17766
17767 /*
17768 ** Shutdown the mutex system. This call frees resources allocated by
17769 ** sqlite3MutexInit().
17770 */
17771 SQLITE_PRIVATE int sqlite3MutexEnd(void){
17772   int rc = SQLITE_OK;
17773   if( sqlite3GlobalConfig.mutex.xMutexEnd ){
17774     rc = sqlite3GlobalConfig.mutex.xMutexEnd();
17775   }
17776
17777 #ifdef SQLITE_DEBUG
17778   GLOBAL(int, mutexIsInit) = 0;
17779 #endif
17780
17781   return rc;
17782 }
17783
17784 /*
17785 ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
17786 */
17787 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
17788 #ifndef SQLITE_OMIT_AUTOINIT
17789   if( sqlite3_initialize() ) return 0;
17790 #endif
17791   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
17792 }
17793
17794 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
17795   if( !sqlite3GlobalConfig.bCoreMutex ){
17796     return 0;
17797   }
17798   assert( GLOBAL(int, mutexIsInit) );
17799   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
17800 }
17801
17802 /*
17803 ** Free a dynamic mutex.
17804 */
17805 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
17806   if( p ){
17807     sqlite3GlobalConfig.mutex.xMutexFree(p);
17808   }
17809 }
17810
17811 /*
17812 ** Obtain the mutex p. If some other thread already has the mutex, block
17813 ** until it can be obtained.
17814 */
17815 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
17816   if( p ){
17817     sqlite3GlobalConfig.mutex.xMutexEnter(p);
17818   }
17819 }
17820
17821 /*
17822 ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
17823 ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
17824 */
17825 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
17826   int rc = SQLITE_OK;
17827   if( p ){
17828     return sqlite3GlobalConfig.mutex.xMutexTry(p);
17829   }
17830   return rc;
17831 }
17832
17833 /*
17834 ** The sqlite3_mutex_leave() routine exits a mutex that was previously
17835 ** entered by the same thread.  The behavior is undefined if the mutex 
17836 ** is not currently entered. If a NULL pointer is passed as an argument
17837 ** this function is a no-op.
17838 */
17839 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
17840   if( p ){
17841     sqlite3GlobalConfig.mutex.xMutexLeave(p);
17842   }
17843 }
17844
17845 #ifndef NDEBUG
17846 /*
17847 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17848 ** intended for use inside assert() statements.
17849 */
17850 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
17851   return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
17852 }
17853 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
17854   return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
17855 }
17856 #endif
17857
17858 #endif /* !defined(SQLITE_MUTEX_OMIT) */
17859
17860 /************** End of mutex.c ***********************************************/
17861 /************** Begin file mutex_noop.c **************************************/
17862 /*
17863 ** 2008 October 07
17864 **
17865 ** The author disclaims copyright to this source code.  In place of
17866 ** a legal notice, here is a blessing:
17867 **
17868 **    May you do good and not evil.
17869 **    May you find forgiveness for yourself and forgive others.
17870 **    May you share freely, never taking more than you give.
17871 **
17872 *************************************************************************
17873 ** This file contains the C functions that implement mutexes.
17874 **
17875 ** This implementation in this file does not provide any mutual
17876 ** exclusion and is thus suitable for use only in applications
17877 ** that use SQLite in a single thread.  The routines defined
17878 ** here are place-holders.  Applications can substitute working
17879 ** mutex routines at start-time using the
17880 **
17881 **     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
17882 **
17883 ** interface.
17884 **
17885 ** If compiled with SQLITE_DEBUG, then additional logic is inserted
17886 ** that does error checking on mutexes to make sure they are being
17887 ** called correctly.
17888 */
17889
17890 #ifndef SQLITE_MUTEX_OMIT
17891
17892 #ifndef SQLITE_DEBUG
17893 /*
17894 ** Stub routines for all mutex methods.
17895 **
17896 ** This routines provide no mutual exclusion or error checking.
17897 */
17898 static int noopMutexInit(void){ return SQLITE_OK; }
17899 static int noopMutexEnd(void){ return SQLITE_OK; }
17900 static sqlite3_mutex *noopMutexAlloc(int id){ 
17901   UNUSED_PARAMETER(id);
17902   return (sqlite3_mutex*)8; 
17903 }
17904 static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
17905 static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
17906 static int noopMutexTry(sqlite3_mutex *p){
17907   UNUSED_PARAMETER(p);
17908   return SQLITE_OK;
17909 }
17910 static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
17911
17912 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
17913   static const sqlite3_mutex_methods sMutex = {
17914     noopMutexInit,
17915     noopMutexEnd,
17916     noopMutexAlloc,
17917     noopMutexFree,
17918     noopMutexEnter,
17919     noopMutexTry,
17920     noopMutexLeave,
17921
17922     0,
17923     0,
17924   };
17925
17926   return &sMutex;
17927 }
17928 #endif /* !SQLITE_DEBUG */
17929
17930 #ifdef SQLITE_DEBUG
17931 /*
17932 ** In this implementation, error checking is provided for testing
17933 ** and debugging purposes.  The mutexes still do not provide any
17934 ** mutual exclusion.
17935 */
17936
17937 /*
17938 ** The mutex object
17939 */
17940 typedef struct sqlite3_debug_mutex {
17941   int id;     /* The mutex type */
17942   int cnt;    /* Number of entries without a matching leave */
17943 } sqlite3_debug_mutex;
17944
17945 /*
17946 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
17947 ** intended for use inside assert() statements.
17948 */
17949 static int debugMutexHeld(sqlite3_mutex *pX){
17950   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17951   return p==0 || p->cnt>0;
17952 }
17953 static int debugMutexNotheld(sqlite3_mutex *pX){
17954   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17955   return p==0 || p->cnt==0;
17956 }
17957
17958 /*
17959 ** Initialize and deinitialize the mutex subsystem.
17960 */
17961 static int debugMutexInit(void){ return SQLITE_OK; }
17962 static int debugMutexEnd(void){ return SQLITE_OK; }
17963
17964 /*
17965 ** The sqlite3_mutex_alloc() routine allocates a new
17966 ** mutex and returns a pointer to it.  If it returns NULL
17967 ** that means that a mutex could not be allocated. 
17968 */
17969 static sqlite3_mutex *debugMutexAlloc(int id){
17970   static sqlite3_debug_mutex aStatic[6];
17971   sqlite3_debug_mutex *pNew = 0;
17972   switch( id ){
17973     case SQLITE_MUTEX_FAST:
17974     case SQLITE_MUTEX_RECURSIVE: {
17975       pNew = sqlite3Malloc(sizeof(*pNew));
17976       if( pNew ){
17977         pNew->id = id;
17978         pNew->cnt = 0;
17979       }
17980       break;
17981     }
17982     default: {
17983       assert( id-2 >= 0 );
17984       assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
17985       pNew = &aStatic[id-2];
17986       pNew->id = id;
17987       break;
17988     }
17989   }
17990   return (sqlite3_mutex*)pNew;
17991 }
17992
17993 /*
17994 ** This routine deallocates a previously allocated mutex.
17995 */
17996 static void debugMutexFree(sqlite3_mutex *pX){
17997   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
17998   assert( p->cnt==0 );
17999   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
18000   sqlite3_free(p);
18001 }
18002
18003 /*
18004 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
18005 ** to enter a mutex.  If another thread is already within the mutex,
18006 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
18007 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
18008 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
18009 ** be entered multiple times by the same thread.  In such cases the,
18010 ** mutex must be exited an equal number of times before another thread
18011 ** can enter.  If the same thread tries to enter any other kind of mutex
18012 ** more than once, the behavior is undefined.
18013 */
18014 static void debugMutexEnter(sqlite3_mutex *pX){
18015   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
18016   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
18017   p->cnt++;
18018 }
18019 static int debugMutexTry(sqlite3_mutex *pX){
18020   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
18021   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
18022   p->cnt++;
18023   return SQLITE_OK;
18024 }
18025
18026 /*
18027 ** The sqlite3_mutex_leave() routine exits a mutex that was
18028 ** previously entered by the same thread.  The behavior
18029 ** is undefined if the mutex is not currently entered or
18030 ** is not currently allocated.  SQLite will never do either.
18031 */
18032 static void debugMutexLeave(sqlite3_mutex *pX){
18033   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
18034   assert( debugMutexHeld(pX) );
18035   p->cnt--;
18036   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
18037 }
18038
18039 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
18040   static const sqlite3_mutex_methods sMutex = {
18041     debugMutexInit,
18042     debugMutexEnd,
18043     debugMutexAlloc,
18044     debugMutexFree,
18045     debugMutexEnter,
18046     debugMutexTry,
18047     debugMutexLeave,
18048
18049     debugMutexHeld,
18050     debugMutexNotheld
18051   };
18052
18053   return &sMutex;
18054 }
18055 #endif /* SQLITE_DEBUG */
18056
18057 /*
18058 ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
18059 ** is used regardless of the run-time threadsafety setting.
18060 */
18061 #ifdef SQLITE_MUTEX_NOOP
18062 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
18063   return sqlite3NoopMutex();
18064 }
18065 #endif /* defined(SQLITE_MUTEX_NOOP) */
18066 #endif /* !defined(SQLITE_MUTEX_OMIT) */
18067
18068 /************** End of mutex_noop.c ******************************************/
18069 /************** Begin file mutex_unix.c **************************************/
18070 /*
18071 ** 2007 August 28
18072 **
18073 ** The author disclaims copyright to this source code.  In place of
18074 ** a legal notice, here is a blessing:
18075 **
18076 **    May you do good and not evil.
18077 **    May you find forgiveness for yourself and forgive others.
18078 **    May you share freely, never taking more than you give.
18079 **
18080 *************************************************************************
18081 ** This file contains the C functions that implement mutexes for pthreads
18082 */
18083
18084 /*
18085 ** The code in this file is only used if we are compiling threadsafe
18086 ** under unix with pthreads.
18087 **
18088 ** Note that this implementation requires a version of pthreads that
18089 ** supports recursive mutexes.
18090 */
18091 #ifdef SQLITE_MUTEX_PTHREADS
18092
18093 #include <pthread.h>
18094
18095 /*
18096 ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
18097 ** are necessary under two condidtions:  (1) Debug builds and (2) using
18098 ** home-grown mutexes.  Encapsulate these conditions into a single #define.
18099 */
18100 #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
18101 # define SQLITE_MUTEX_NREF 1
18102 #else
18103 # define SQLITE_MUTEX_NREF 0
18104 #endif
18105
18106 /*
18107 ** Each recursive mutex is an instance of the following structure.
18108 */
18109 struct sqlite3_mutex {
18110   pthread_mutex_t mutex;     /* Mutex controlling the lock */
18111 #if SQLITE_MUTEX_NREF
18112   int id;                    /* Mutex type */
18113   volatile int nRef;         /* Number of entrances */
18114   volatile pthread_t owner;  /* Thread that is within this mutex */
18115   int trace;                 /* True to trace changes */
18116 #endif
18117 };
18118 #if SQLITE_MUTEX_NREF
18119 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
18120 #else
18121 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
18122 #endif
18123
18124 /*
18125 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
18126 ** intended for use only inside assert() statements.  On some platforms,
18127 ** there might be race conditions that can cause these routines to
18128 ** deliver incorrect results.  In particular, if pthread_equal() is
18129 ** not an atomic operation, then these routines might delivery
18130 ** incorrect results.  On most platforms, pthread_equal() is a 
18131 ** comparison of two integers and is therefore atomic.  But we are
18132 ** told that HPUX is not such a platform.  If so, then these routines
18133 ** will not always work correctly on HPUX.
18134 **
18135 ** On those platforms where pthread_equal() is not atomic, SQLite
18136 ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
18137 ** make sure no assert() statements are evaluated and hence these
18138 ** routines are never called.
18139 */
18140 #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
18141 static int pthreadMutexHeld(sqlite3_mutex *p){
18142   return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
18143 }
18144 static int pthreadMutexNotheld(sqlite3_mutex *p){
18145   return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
18146 }
18147 #endif
18148
18149 /*
18150 ** Initialize and deinitialize the mutex subsystem.
18151 */
18152 static int pthreadMutexInit(void){ return SQLITE_OK; }
18153 static int pthreadMutexEnd(void){ return SQLITE_OK; }
18154
18155 /*
18156 ** The sqlite3_mutex_alloc() routine allocates a new
18157 ** mutex and returns a pointer to it.  If it returns NULL
18158 ** that means that a mutex could not be allocated.  SQLite
18159 ** will unwind its stack and return an error.  The argument
18160 ** to sqlite3_mutex_alloc() is one of these integer constants:
18161 **
18162 ** <ul>
18163 ** <li>  SQLITE_MUTEX_FAST
18164 ** <li>  SQLITE_MUTEX_RECURSIVE
18165 ** <li>  SQLITE_MUTEX_STATIC_MASTER
18166 ** <li>  SQLITE_MUTEX_STATIC_MEM
18167 ** <li>  SQLITE_MUTEX_STATIC_MEM2
18168 ** <li>  SQLITE_MUTEX_STATIC_PRNG
18169 ** <li>  SQLITE_MUTEX_STATIC_LRU
18170 ** <li>  SQLITE_MUTEX_STATIC_PMEM
18171 ** </ul>
18172 **
18173 ** The first two constants cause sqlite3_mutex_alloc() to create
18174 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
18175 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
18176 ** The mutex implementation does not need to make a distinction
18177 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
18178 ** not want to.  But SQLite will only request a recursive mutex in
18179 ** cases where it really needs one.  If a faster non-recursive mutex
18180 ** implementation is available on the host platform, the mutex subsystem
18181 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
18182 **
18183 ** The other allowed parameters to sqlite3_mutex_alloc() each return
18184 ** a pointer to a static preexisting mutex.  Six static mutexes are
18185 ** used by the current version of SQLite.  Future versions of SQLite
18186 ** may add additional static mutexes.  Static mutexes are for internal
18187 ** use by SQLite only.  Applications that use SQLite mutexes should
18188 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
18189 ** SQLITE_MUTEX_RECURSIVE.
18190 **
18191 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
18192 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
18193 ** returns a different mutex on every call.  But for the static 
18194 ** mutex types, the same mutex is returned on every call that has
18195 ** the same type number.
18196 */
18197 static sqlite3_mutex *pthreadMutexAlloc(int iType){
18198   static sqlite3_mutex staticMutexes[] = {
18199     SQLITE3_MUTEX_INITIALIZER,
18200     SQLITE3_MUTEX_INITIALIZER,
18201     SQLITE3_MUTEX_INITIALIZER,
18202     SQLITE3_MUTEX_INITIALIZER,
18203     SQLITE3_MUTEX_INITIALIZER,
18204     SQLITE3_MUTEX_INITIALIZER
18205   };
18206   sqlite3_mutex *p;
18207   switch( iType ){
18208     case SQLITE_MUTEX_RECURSIVE: {
18209       p = sqlite3MallocZero( sizeof(*p) );
18210       if( p ){
18211 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
18212         /* If recursive mutexes are not available, we will have to
18213         ** build our own.  See below. */
18214         pthread_mutex_init(&p->mutex, 0);
18215 #else
18216         /* Use a recursive mutex if it is available */
18217         pthread_mutexattr_t recursiveAttr;
18218         pthread_mutexattr_init(&recursiveAttr);
18219         pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
18220         pthread_mutex_init(&p->mutex, &recursiveAttr);
18221         pthread_mutexattr_destroy(&recursiveAttr);
18222 #endif
18223 #if SQLITE_MUTEX_NREF
18224         p->id = iType;
18225 #endif
18226       }
18227       break;
18228     }
18229     case SQLITE_MUTEX_FAST: {
18230       p = sqlite3MallocZero( sizeof(*p) );
18231       if( p ){
18232 #if SQLITE_MUTEX_NREF
18233         p->id = iType;
18234 #endif
18235         pthread_mutex_init(&p->mutex, 0);
18236       }
18237       break;
18238     }
18239     default: {
18240       assert( iType-2 >= 0 );
18241       assert( iType-2 < ArraySize(staticMutexes) );
18242       p = &staticMutexes[iType-2];
18243 #if SQLITE_MUTEX_NREF
18244       p->id = iType;
18245 #endif
18246       break;
18247     }
18248   }
18249   return p;
18250 }
18251
18252
18253 /*
18254 ** This routine deallocates a previously
18255 ** allocated mutex.  SQLite is careful to deallocate every
18256 ** mutex that it allocates.
18257 */
18258 static void pthreadMutexFree(sqlite3_mutex *p){
18259   assert( p->nRef==0 );
18260   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
18261   pthread_mutex_destroy(&p->mutex);
18262   sqlite3_free(p);
18263 }
18264
18265 /*
18266 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
18267 ** to enter a mutex.  If another thread is already within the mutex,
18268 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
18269 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
18270 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
18271 ** be entered multiple times by the same thread.  In such cases the,
18272 ** mutex must be exited an equal number of times before another thread
18273 ** can enter.  If the same thread tries to enter any other kind of mutex
18274 ** more than once, the behavior is undefined.
18275 */
18276 static void pthreadMutexEnter(sqlite3_mutex *p){
18277   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
18278
18279 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
18280   /* If recursive mutexes are not available, then we have to grow
18281   ** our own.  This implementation assumes that pthread_equal()
18282   ** is atomic - that it cannot be deceived into thinking self
18283   ** and p->owner are equal if p->owner changes between two values
18284   ** that are not equal to self while the comparison is taking place.
18285   ** This implementation also assumes a coherent cache - that 
18286   ** separate processes cannot read different values from the same
18287   ** address at the same time.  If either of these two conditions
18288   ** are not met, then the mutexes will fail and problems will result.
18289   */
18290   {
18291     pthread_t self = pthread_self();
18292     if( p->nRef>0 && pthread_equal(p->owner, self) ){
18293       p->nRef++;
18294     }else{
18295       pthread_mutex_lock(&p->mutex);
18296       assert( p->nRef==0 );
18297       p->owner = self;
18298       p->nRef = 1;
18299     }
18300   }
18301 #else
18302   /* Use the built-in recursive mutexes if they are available.
18303   */
18304   pthread_mutex_lock(&p->mutex);
18305 #if SQLITE_MUTEX_NREF
18306   assert( p->nRef>0 || p->owner==0 );
18307   p->owner = pthread_self();
18308   p->nRef++;
18309 #endif
18310 #endif
18311
18312 #ifdef SQLITE_DEBUG
18313   if( p->trace ){
18314     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18315   }
18316 #endif
18317 }
18318 static int pthreadMutexTry(sqlite3_mutex *p){
18319   int rc;
18320   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
18321
18322 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
18323   /* If recursive mutexes are not available, then we have to grow
18324   ** our own.  This implementation assumes that pthread_equal()
18325   ** is atomic - that it cannot be deceived into thinking self
18326   ** and p->owner are equal if p->owner changes between two values
18327   ** that are not equal to self while the comparison is taking place.
18328   ** This implementation also assumes a coherent cache - that 
18329   ** separate processes cannot read different values from the same
18330   ** address at the same time.  If either of these two conditions
18331   ** are not met, then the mutexes will fail and problems will result.
18332   */
18333   {
18334     pthread_t self = pthread_self();
18335     if( p->nRef>0 && pthread_equal(p->owner, self) ){
18336       p->nRef++;
18337       rc = SQLITE_OK;
18338     }else if( pthread_mutex_trylock(&p->mutex)==0 ){
18339       assert( p->nRef==0 );
18340       p->owner = self;
18341       p->nRef = 1;
18342       rc = SQLITE_OK;
18343     }else{
18344       rc = SQLITE_BUSY;
18345     }
18346   }
18347 #else
18348   /* Use the built-in recursive mutexes if they are available.
18349   */
18350   if( pthread_mutex_trylock(&p->mutex)==0 ){
18351 #if SQLITE_MUTEX_NREF
18352     p->owner = pthread_self();
18353     p->nRef++;
18354 #endif
18355     rc = SQLITE_OK;
18356   }else{
18357     rc = SQLITE_BUSY;
18358   }
18359 #endif
18360
18361 #ifdef SQLITE_DEBUG
18362   if( rc==SQLITE_OK && p->trace ){
18363     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18364   }
18365 #endif
18366   return rc;
18367 }
18368
18369 /*
18370 ** The sqlite3_mutex_leave() routine exits a mutex that was
18371 ** previously entered by the same thread.  The behavior
18372 ** is undefined if the mutex is not currently entered or
18373 ** is not currently allocated.  SQLite will never do either.
18374 */
18375 static void pthreadMutexLeave(sqlite3_mutex *p){
18376   assert( pthreadMutexHeld(p) );
18377 #if SQLITE_MUTEX_NREF
18378   p->nRef--;
18379   if( p->nRef==0 ) p->owner = 0;
18380 #endif
18381   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
18382
18383 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
18384   if( p->nRef==0 ){
18385     pthread_mutex_unlock(&p->mutex);
18386   }
18387 #else
18388   pthread_mutex_unlock(&p->mutex);
18389 #endif
18390
18391 #ifdef SQLITE_DEBUG
18392   if( p->trace ){
18393     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18394   }
18395 #endif
18396 }
18397
18398 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
18399   static const sqlite3_mutex_methods sMutex = {
18400     pthreadMutexInit,
18401     pthreadMutexEnd,
18402     pthreadMutexAlloc,
18403     pthreadMutexFree,
18404     pthreadMutexEnter,
18405     pthreadMutexTry,
18406     pthreadMutexLeave,
18407 #ifdef SQLITE_DEBUG
18408     pthreadMutexHeld,
18409     pthreadMutexNotheld
18410 #else
18411     0,
18412     0
18413 #endif
18414   };
18415
18416   return &sMutex;
18417 }
18418
18419 #endif /* SQLITE_MUTEX_PTHREADS */
18420
18421 /************** End of mutex_unix.c ******************************************/
18422 /************** Begin file mutex_w32.c ***************************************/
18423 /*
18424 ** 2007 August 14
18425 **
18426 ** The author disclaims copyright to this source code.  In place of
18427 ** a legal notice, here is a blessing:
18428 **
18429 **    May you do good and not evil.
18430 **    May you find forgiveness for yourself and forgive others.
18431 **    May you share freely, never taking more than you give.
18432 **
18433 *************************************************************************
18434 ** This file contains the C functions that implement mutexes for win32
18435 */
18436
18437 /*
18438 ** The code in this file is only used if we are compiling multithreaded
18439 ** on a win32 system.
18440 */
18441 #ifdef SQLITE_MUTEX_W32
18442
18443 /*
18444 ** Each recursive mutex is an instance of the following structure.
18445 */
18446 struct sqlite3_mutex {
18447   CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
18448   int id;                    /* Mutex type */
18449 #ifdef SQLITE_DEBUG
18450   volatile int nRef;         /* Number of enterances */
18451   volatile DWORD owner;      /* Thread holding this mutex */
18452   int trace;                 /* True to trace changes */
18453 #endif
18454 };
18455 #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
18456 #ifdef SQLITE_DEBUG
18457 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0, 0 }
18458 #else
18459 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
18460 #endif
18461
18462 /*
18463 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
18464 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
18465 **
18466 ** Here is an interesting observation:  Win95, Win98, and WinME lack
18467 ** the LockFileEx() API.  But we can still statically link against that
18468 ** API as long as we don't call it win running Win95/98/ME.  A call to
18469 ** this routine is used to determine if the host is Win95/98/ME or
18470 ** WinNT/2K/XP so that we will know whether or not we can safely call
18471 ** the LockFileEx() API.
18472 **
18473 ** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
18474 ** which is only available if your application was compiled with 
18475 ** _WIN32_WINNT defined to a value >= 0x0400.  Currently, the only
18476 ** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef 
18477 ** this out as well.
18478 */
18479 #if 0
18480 #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
18481 # define mutexIsNT()  (1)
18482 #else
18483   static int mutexIsNT(void){
18484     static int osType = 0;
18485     if( osType==0 ){
18486       OSVERSIONINFO sInfo;
18487       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
18488       GetVersionEx(&sInfo);
18489       osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
18490     }
18491     return osType==2;
18492   }
18493 #endif /* SQLITE_OS_WINCE */
18494 #endif
18495
18496 #ifdef SQLITE_DEBUG
18497 /*
18498 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
18499 ** intended for use only inside assert() statements.
18500 */
18501 static int winMutexHeld(sqlite3_mutex *p){
18502   return p->nRef!=0 && p->owner==GetCurrentThreadId();
18503 }
18504 static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
18505   return p->nRef==0 || p->owner!=tid;
18506 }
18507 static int winMutexNotheld(sqlite3_mutex *p){
18508   DWORD tid = GetCurrentThreadId(); 
18509   return winMutexNotheld2(p, tid);
18510 }
18511 #endif
18512
18513
18514 /*
18515 ** Initialize and deinitialize the mutex subsystem.
18516 */
18517 static sqlite3_mutex winMutex_staticMutexes[6] = {
18518   SQLITE3_MUTEX_INITIALIZER,
18519   SQLITE3_MUTEX_INITIALIZER,
18520   SQLITE3_MUTEX_INITIALIZER,
18521   SQLITE3_MUTEX_INITIALIZER,
18522   SQLITE3_MUTEX_INITIALIZER,
18523   SQLITE3_MUTEX_INITIALIZER
18524 };
18525 static int winMutex_isInit = 0;
18526 /* As winMutexInit() and winMutexEnd() are called as part
18527 ** of the sqlite3_initialize and sqlite3_shutdown()
18528 ** processing, the "interlocked" magic is probably not
18529 ** strictly necessary.
18530 */
18531 static long winMutex_lock = 0;
18532
18533 SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
18534
18535 static int winMutexInit(void){ 
18536   /* The first to increment to 1 does actual initialization */
18537   if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
18538     int i;
18539     for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
18540 #if SQLITE_OS_WINRT
18541       InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
18542 #else
18543       InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
18544 #endif
18545     }
18546     winMutex_isInit = 1;
18547   }else{
18548     /* Someone else is in the process of initing the static mutexes */
18549     while( !winMutex_isInit ){
18550       sqlite3_win32_sleep(1);
18551     }
18552   }
18553   return SQLITE_OK; 
18554 }
18555
18556 static int winMutexEnd(void){ 
18557   /* The first to decrement to 0 does actual shutdown 
18558   ** (which should be the last to shutdown.) */
18559   if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
18560     if( winMutex_isInit==1 ){
18561       int i;
18562       for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
18563         DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
18564       }
18565       winMutex_isInit = 0;
18566     }
18567   }
18568   return SQLITE_OK; 
18569 }
18570
18571 /*
18572 ** The sqlite3_mutex_alloc() routine allocates a new
18573 ** mutex and returns a pointer to it.  If it returns NULL
18574 ** that means that a mutex could not be allocated.  SQLite
18575 ** will unwind its stack and return an error.  The argument
18576 ** to sqlite3_mutex_alloc() is one of these integer constants:
18577 **
18578 ** <ul>
18579 ** <li>  SQLITE_MUTEX_FAST
18580 ** <li>  SQLITE_MUTEX_RECURSIVE
18581 ** <li>  SQLITE_MUTEX_STATIC_MASTER
18582 ** <li>  SQLITE_MUTEX_STATIC_MEM
18583 ** <li>  SQLITE_MUTEX_STATIC_MEM2
18584 ** <li>  SQLITE_MUTEX_STATIC_PRNG
18585 ** <li>  SQLITE_MUTEX_STATIC_LRU
18586 ** <li>  SQLITE_MUTEX_STATIC_PMEM
18587 ** </ul>
18588 **
18589 ** The first two constants cause sqlite3_mutex_alloc() to create
18590 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
18591 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
18592 ** The mutex implementation does not need to make a distinction
18593 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
18594 ** not want to.  But SQLite will only request a recursive mutex in
18595 ** cases where it really needs one.  If a faster non-recursive mutex
18596 ** implementation is available on the host platform, the mutex subsystem
18597 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
18598 **
18599 ** The other allowed parameters to sqlite3_mutex_alloc() each return
18600 ** a pointer to a static preexisting mutex.  Six static mutexes are
18601 ** used by the current version of SQLite.  Future versions of SQLite
18602 ** may add additional static mutexes.  Static mutexes are for internal
18603 ** use by SQLite only.  Applications that use SQLite mutexes should
18604 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
18605 ** SQLITE_MUTEX_RECURSIVE.
18606 **
18607 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
18608 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
18609 ** returns a different mutex on every call.  But for the static 
18610 ** mutex types, the same mutex is returned on every call that has
18611 ** the same type number.
18612 */
18613 static sqlite3_mutex *winMutexAlloc(int iType){
18614   sqlite3_mutex *p;
18615
18616   switch( iType ){
18617     case SQLITE_MUTEX_FAST:
18618     case SQLITE_MUTEX_RECURSIVE: {
18619       p = sqlite3MallocZero( sizeof(*p) );
18620       if( p ){  
18621 #ifdef SQLITE_DEBUG
18622         p->id = iType;
18623 #endif
18624 #if SQLITE_OS_WINRT
18625         InitializeCriticalSectionEx(&p->mutex, 0, 0);
18626 #else
18627         InitializeCriticalSection(&p->mutex);
18628 #endif
18629       }
18630       break;
18631     }
18632     default: {
18633       assert( winMutex_isInit==1 );
18634       assert( iType-2 >= 0 );
18635       assert( iType-2 < ArraySize(winMutex_staticMutexes) );
18636       p = &winMutex_staticMutexes[iType-2];
18637 #ifdef SQLITE_DEBUG
18638       p->id = iType;
18639 #endif
18640       break;
18641     }
18642   }
18643   return p;
18644 }
18645
18646
18647 /*
18648 ** This routine deallocates a previously
18649 ** allocated mutex.  SQLite is careful to deallocate every
18650 ** mutex that it allocates.
18651 */
18652 static void winMutexFree(sqlite3_mutex *p){
18653   assert( p );
18654   assert( p->nRef==0 && p->owner==0 );
18655   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
18656   DeleteCriticalSection(&p->mutex);
18657   sqlite3_free(p);
18658 }
18659
18660 /*
18661 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
18662 ** to enter a mutex.  If another thread is already within the mutex,
18663 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
18664 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
18665 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
18666 ** be entered multiple times by the same thread.  In such cases the,
18667 ** mutex must be exited an equal number of times before another thread
18668 ** can enter.  If the same thread tries to enter any other kind of mutex
18669 ** more than once, the behavior is undefined.
18670 */
18671 static void winMutexEnter(sqlite3_mutex *p){
18672 #ifdef SQLITE_DEBUG
18673   DWORD tid = GetCurrentThreadId(); 
18674   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
18675 #endif
18676   EnterCriticalSection(&p->mutex);
18677 #ifdef SQLITE_DEBUG
18678   assert( p->nRef>0 || p->owner==0 );
18679   p->owner = tid; 
18680   p->nRef++;
18681   if( p->trace ){
18682     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18683   }
18684 #endif
18685 }
18686 static int winMutexTry(sqlite3_mutex *p){
18687 #ifndef NDEBUG
18688   DWORD tid = GetCurrentThreadId(); 
18689 #endif
18690   int rc = SQLITE_BUSY;
18691   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
18692   /*
18693   ** The sqlite3_mutex_try() routine is very rarely used, and when it
18694   ** is used it is merely an optimization.  So it is OK for it to always
18695   ** fail.  
18696   **
18697   ** The TryEnterCriticalSection() interface is only available on WinNT.
18698   ** And some windows compilers complain if you try to use it without
18699   ** first doing some #defines that prevent SQLite from building on Win98.
18700   ** For that reason, we will omit this optimization for now.  See
18701   ** ticket #2685.
18702   */
18703 #if 0
18704   if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
18705     p->owner = tid;
18706     p->nRef++;
18707     rc = SQLITE_OK;
18708   }
18709 #else
18710   UNUSED_PARAMETER(p);
18711 #endif
18712 #ifdef SQLITE_DEBUG
18713   if( rc==SQLITE_OK && p->trace ){
18714     printf("try mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18715   }
18716 #endif
18717   return rc;
18718 }
18719
18720 /*
18721 ** The sqlite3_mutex_leave() routine exits a mutex that was
18722 ** previously entered by the same thread.  The behavior
18723 ** is undefined if the mutex is not currently entered or
18724 ** is not currently allocated.  SQLite will never do either.
18725 */
18726 static void winMutexLeave(sqlite3_mutex *p){
18727 #ifndef NDEBUG
18728   DWORD tid = GetCurrentThreadId();
18729   assert( p->nRef>0 );
18730   assert( p->owner==tid );
18731   p->nRef--;
18732   if( p->nRef==0 ) p->owner = 0;
18733   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
18734 #endif
18735   LeaveCriticalSection(&p->mutex);
18736 #ifdef SQLITE_DEBUG
18737   if( p->trace ){
18738     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
18739   }
18740 #endif
18741 }
18742
18743 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
18744   static const sqlite3_mutex_methods sMutex = {
18745     winMutexInit,
18746     winMutexEnd,
18747     winMutexAlloc,
18748     winMutexFree,
18749     winMutexEnter,
18750     winMutexTry,
18751     winMutexLeave,
18752 #ifdef SQLITE_DEBUG
18753     winMutexHeld,
18754     winMutexNotheld
18755 #else
18756     0,
18757     0
18758 #endif
18759   };
18760
18761   return &sMutex;
18762 }
18763 #endif /* SQLITE_MUTEX_W32 */
18764
18765 /************** End of mutex_w32.c *******************************************/
18766 /************** Begin file malloc.c ******************************************/
18767 /*
18768 ** 2001 September 15
18769 **
18770 ** The author disclaims copyright to this source code.  In place of
18771 ** a legal notice, here is a blessing:
18772 **
18773 **    May you do good and not evil.
18774 **    May you find forgiveness for yourself and forgive others.
18775 **    May you share freely, never taking more than you give.
18776 **
18777 *************************************************************************
18778 **
18779 ** Memory allocation functions used throughout sqlite.
18780 */
18781 /* #include <stdarg.h> */
18782
18783 /*
18784 ** Attempt to release up to n bytes of non-essential memory currently
18785 ** held by SQLite. An example of non-essential memory is memory used to
18786 ** cache database pages that are not currently in use.
18787 */
18788 SQLITE_API int sqlite3_release_memory(int n){
18789 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
18790   return sqlite3PcacheReleaseMemory(n);
18791 #else
18792   /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
18793   ** is a no-op returning zero if SQLite is not compiled with
18794   ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
18795   UNUSED_PARAMETER(n);
18796   return 0;
18797 #endif
18798 }
18799
18800 /*
18801 ** An instance of the following object records the location of
18802 ** each unused scratch buffer.
18803 */
18804 typedef struct ScratchFreeslot {
18805   struct ScratchFreeslot *pNext;   /* Next unused scratch buffer */
18806 } ScratchFreeslot;
18807
18808 /*
18809 ** State information local to the memory allocation subsystem.
18810 */
18811 static SQLITE_WSD struct Mem0Global {
18812   sqlite3_mutex *mutex;         /* Mutex to serialize access */
18813
18814   /*
18815   ** The alarm callback and its arguments.  The mem0.mutex lock will
18816   ** be held while the callback is running.  Recursive calls into
18817   ** the memory subsystem are allowed, but no new callbacks will be
18818   ** issued.
18819   */
18820   sqlite3_int64 alarmThreshold;
18821   void (*alarmCallback)(void*, sqlite3_int64,int);
18822   void *alarmArg;
18823
18824   /*
18825   ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
18826   ** (so that a range test can be used to determine if an allocation
18827   ** being freed came from pScratch) and a pointer to the list of
18828   ** unused scratch allocations.
18829   */
18830   void *pScratchEnd;
18831   ScratchFreeslot *pScratchFree;
18832   u32 nScratchFree;
18833
18834   /*
18835   ** True if heap is nearly "full" where "full" is defined by the
18836   ** sqlite3_soft_heap_limit() setting.
18837   */
18838   int nearlyFull;
18839 } mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
18840
18841 #define mem0 GLOBAL(struct Mem0Global, mem0)
18842
18843 /*
18844 ** This routine runs when the memory allocator sees that the
18845 ** total memory allocation is about to exceed the soft heap
18846 ** limit.
18847 */
18848 static void softHeapLimitEnforcer(
18849   void *NotUsed, 
18850   sqlite3_int64 NotUsed2,
18851   int allocSize
18852 ){
18853   UNUSED_PARAMETER2(NotUsed, NotUsed2);
18854   sqlite3_release_memory(allocSize);
18855 }
18856
18857 /*
18858 ** Change the alarm callback
18859 */
18860 static int sqlite3MemoryAlarm(
18861   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
18862   void *pArg,
18863   sqlite3_int64 iThreshold
18864 ){
18865   int nUsed;
18866   sqlite3_mutex_enter(mem0.mutex);
18867   mem0.alarmCallback = xCallback;
18868   mem0.alarmArg = pArg;
18869   mem0.alarmThreshold = iThreshold;
18870   nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
18871   mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);
18872   sqlite3_mutex_leave(mem0.mutex);
18873   return SQLITE_OK;
18874 }
18875
18876 #ifndef SQLITE_OMIT_DEPRECATED
18877 /*
18878 ** Deprecated external interface.  Internal/core SQLite code
18879 ** should call sqlite3MemoryAlarm.
18880 */
18881 SQLITE_API int sqlite3_memory_alarm(
18882   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
18883   void *pArg,
18884   sqlite3_int64 iThreshold
18885 ){
18886   return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
18887 }
18888 #endif
18889
18890 /*
18891 ** Set the soft heap-size limit for the library. Passing a zero or 
18892 ** negative value indicates no limit.
18893 */
18894 SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
18895   sqlite3_int64 priorLimit;
18896   sqlite3_int64 excess;
18897 #ifndef SQLITE_OMIT_AUTOINIT
18898   int rc = sqlite3_initialize();
18899   if( rc ) return -1;
18900 #endif
18901   sqlite3_mutex_enter(mem0.mutex);
18902   priorLimit = mem0.alarmThreshold;
18903   sqlite3_mutex_leave(mem0.mutex);
18904   if( n<0 ) return priorLimit;
18905   if( n>0 ){
18906     sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n);
18907   }else{
18908     sqlite3MemoryAlarm(0, 0, 0);
18909   }
18910   excess = sqlite3_memory_used() - n;
18911   if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
18912   return priorLimit;
18913 }
18914 SQLITE_API void sqlite3_soft_heap_limit(int n){
18915   if( n<0 ) n = 0;
18916   sqlite3_soft_heap_limit64(n);
18917 }
18918
18919 /*
18920 ** Initialize the memory allocation subsystem.
18921 */
18922 SQLITE_PRIVATE int sqlite3MallocInit(void){
18923   if( sqlite3GlobalConfig.m.xMalloc==0 ){
18924     sqlite3MemSetDefault();
18925   }
18926   memset(&mem0, 0, sizeof(mem0));
18927   if( sqlite3GlobalConfig.bCoreMutex ){
18928     mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
18929   }
18930   if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
18931       && sqlite3GlobalConfig.nScratch>0 ){
18932     int i, n, sz;
18933     ScratchFreeslot *pSlot;
18934     sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
18935     sqlite3GlobalConfig.szScratch = sz;
18936     pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
18937     n = sqlite3GlobalConfig.nScratch;
18938     mem0.pScratchFree = pSlot;
18939     mem0.nScratchFree = n;
18940     for(i=0; i<n-1; i++){
18941       pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
18942       pSlot = pSlot->pNext;
18943     }
18944     pSlot->pNext = 0;
18945     mem0.pScratchEnd = (void*)&pSlot[1];
18946   }else{
18947     mem0.pScratchEnd = 0;
18948     sqlite3GlobalConfig.pScratch = 0;
18949     sqlite3GlobalConfig.szScratch = 0;
18950     sqlite3GlobalConfig.nScratch = 0;
18951   }
18952   if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
18953       || sqlite3GlobalConfig.nPage<1 ){
18954     sqlite3GlobalConfig.pPage = 0;
18955     sqlite3GlobalConfig.szPage = 0;
18956     sqlite3GlobalConfig.nPage = 0;
18957   }
18958   return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
18959 }
18960
18961 /*
18962 ** Return true if the heap is currently under memory pressure - in other
18963 ** words if the amount of heap used is close to the limit set by
18964 ** sqlite3_soft_heap_limit().
18965 */
18966 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
18967   return mem0.nearlyFull;
18968 }
18969
18970 /*
18971 ** Deinitialize the memory allocation subsystem.
18972 */
18973 SQLITE_PRIVATE void sqlite3MallocEnd(void){
18974   if( sqlite3GlobalConfig.m.xShutdown ){
18975     sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
18976   }
18977   memset(&mem0, 0, sizeof(mem0));
18978 }
18979
18980 /*
18981 ** Return the amount of memory currently checked out.
18982 */
18983 SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
18984   int n, mx;
18985   sqlite3_int64 res;
18986   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
18987   res = (sqlite3_int64)n;  /* Work around bug in Borland C. Ticket #3216 */
18988   return res;
18989 }
18990
18991 /*
18992 ** Return the maximum amount of memory that has ever been
18993 ** checked out since either the beginning of this process
18994 ** or since the most recent reset.
18995 */
18996 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
18997   int n, mx;
18998   sqlite3_int64 res;
18999   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
19000   res = (sqlite3_int64)mx;  /* Work around bug in Borland C. Ticket #3216 */
19001   return res;
19002 }
19003
19004 /*
19005 ** Trigger the alarm 
19006 */
19007 static void sqlite3MallocAlarm(int nByte){
19008   void (*xCallback)(void*,sqlite3_int64,int);
19009   sqlite3_int64 nowUsed;
19010   void *pArg;
19011   if( mem0.alarmCallback==0 ) return;
19012   xCallback = mem0.alarmCallback;
19013   nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
19014   pArg = mem0.alarmArg;
19015   mem0.alarmCallback = 0;
19016   sqlite3_mutex_leave(mem0.mutex);
19017   xCallback(pArg, nowUsed, nByte);
19018   sqlite3_mutex_enter(mem0.mutex);
19019   mem0.alarmCallback = xCallback;
19020   mem0.alarmArg = pArg;
19021 }
19022
19023 /*
19024 ** Do a memory allocation with statistics and alarms.  Assume the
19025 ** lock is already held.
19026 */
19027 static int mallocWithAlarm(int n, void **pp){
19028   int nFull;
19029   void *p;
19030   assert( sqlite3_mutex_held(mem0.mutex) );
19031   nFull = sqlite3GlobalConfig.m.xRoundup(n);
19032   sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
19033   if( mem0.alarmCallback!=0 ){
19034     int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
19035     if( nUsed >= mem0.alarmThreshold - nFull ){
19036       mem0.nearlyFull = 1;
19037       sqlite3MallocAlarm(nFull);
19038     }else{
19039       mem0.nearlyFull = 0;
19040     }
19041   }
19042   p = sqlite3GlobalConfig.m.xMalloc(nFull);
19043 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
19044   if( p==0 && mem0.alarmCallback ){
19045     sqlite3MallocAlarm(nFull);
19046     p = sqlite3GlobalConfig.m.xMalloc(nFull);
19047   }
19048 #endif
19049   if( p ){
19050     nFull = sqlite3MallocSize(p);
19051     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
19052     sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, 1);
19053   }
19054   *pp = p;
19055   return nFull;
19056 }
19057
19058 /*
19059 ** Allocate memory.  This routine is like sqlite3_malloc() except that it
19060 ** assumes the memory subsystem has already been initialized.
19061 */
19062 SQLITE_PRIVATE void *sqlite3Malloc(int n){
19063   void *p;
19064   if( n<=0               /* IMP: R-65312-04917 */ 
19065    || n>=0x7fffff00
19066   ){
19067     /* A memory allocation of a number of bytes which is near the maximum
19068     ** signed integer value might cause an integer overflow inside of the
19069     ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
19070     ** 255 bytes of overhead.  SQLite itself will never use anything near
19071     ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
19072     p = 0;
19073   }else if( sqlite3GlobalConfig.bMemstat ){
19074     sqlite3_mutex_enter(mem0.mutex);
19075     mallocWithAlarm(n, &p);
19076     sqlite3_mutex_leave(mem0.mutex);
19077   }else{
19078     p = sqlite3GlobalConfig.m.xMalloc(n);
19079   }
19080   assert( EIGHT_BYTE_ALIGNMENT(p) );  /* IMP: R-04675-44850 */
19081   return p;
19082 }
19083
19084 /*
19085 ** This version of the memory allocation is for use by the application.
19086 ** First make sure the memory subsystem is initialized, then do the
19087 ** allocation.
19088 */
19089 SQLITE_API void *sqlite3_malloc(int n){
19090 #ifndef SQLITE_OMIT_AUTOINIT
19091   if( sqlite3_initialize() ) return 0;
19092 #endif
19093   return sqlite3Malloc(n);
19094 }
19095
19096 /*
19097 ** Each thread may only have a single outstanding allocation from
19098 ** xScratchMalloc().  We verify this constraint in the single-threaded
19099 ** case by setting scratchAllocOut to 1 when an allocation
19100 ** is outstanding clearing it when the allocation is freed.
19101 */
19102 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
19103 static int scratchAllocOut = 0;
19104 #endif
19105
19106
19107 /*
19108 ** Allocate memory that is to be used and released right away.
19109 ** This routine is similar to alloca() in that it is not intended
19110 ** for situations where the memory might be held long-term.  This
19111 ** routine is intended to get memory to old large transient data
19112 ** structures that would not normally fit on the stack of an
19113 ** embedded processor.
19114 */
19115 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
19116   void *p;
19117   assert( n>0 );
19118
19119   sqlite3_mutex_enter(mem0.mutex);
19120   if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
19121     p = mem0.pScratchFree;
19122     mem0.pScratchFree = mem0.pScratchFree->pNext;
19123     mem0.nScratchFree--;
19124     sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
19125     sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
19126     sqlite3_mutex_leave(mem0.mutex);
19127   }else{
19128     if( sqlite3GlobalConfig.bMemstat ){
19129       sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
19130       n = mallocWithAlarm(n, &p);
19131       if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
19132       sqlite3_mutex_leave(mem0.mutex);
19133     }else{
19134       sqlite3_mutex_leave(mem0.mutex);
19135       p = sqlite3GlobalConfig.m.xMalloc(n);
19136     }
19137     sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
19138   }
19139   assert( sqlite3_mutex_notheld(mem0.mutex) );
19140
19141
19142 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
19143   /* Verify that no more than two scratch allocations per thread
19144   ** are outstanding at one time.  (This is only checked in the
19145   ** single-threaded case since checking in the multi-threaded case
19146   ** would be much more complicated.) */
19147   assert( scratchAllocOut<=1 );
19148   if( p ) scratchAllocOut++;
19149 #endif
19150
19151   return p;
19152 }
19153 SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
19154   if( p ){
19155
19156 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
19157     /* Verify that no more than two scratch allocation per thread
19158     ** is outstanding at one time.  (This is only checked in the
19159     ** single-threaded case since checking in the multi-threaded case
19160     ** would be much more complicated.) */
19161     assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
19162     scratchAllocOut--;
19163 #endif
19164
19165     if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
19166       /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
19167       ScratchFreeslot *pSlot;
19168       pSlot = (ScratchFreeslot*)p;
19169       sqlite3_mutex_enter(mem0.mutex);
19170       pSlot->pNext = mem0.pScratchFree;
19171       mem0.pScratchFree = pSlot;
19172       mem0.nScratchFree++;
19173       assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
19174       sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
19175       sqlite3_mutex_leave(mem0.mutex);
19176     }else{
19177       /* Release memory back to the heap */
19178       assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
19179       assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
19180       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
19181       if( sqlite3GlobalConfig.bMemstat ){
19182         int iSize = sqlite3MallocSize(p);
19183         sqlite3_mutex_enter(mem0.mutex);
19184         sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
19185         sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
19186         sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
19187         sqlite3GlobalConfig.m.xFree(p);
19188         sqlite3_mutex_leave(mem0.mutex);
19189       }else{
19190         sqlite3GlobalConfig.m.xFree(p);
19191       }
19192     }
19193   }
19194 }
19195
19196 /*
19197 ** TRUE if p is a lookaside memory allocation from db
19198 */
19199 #ifndef SQLITE_OMIT_LOOKASIDE
19200 static int isLookaside(sqlite3 *db, void *p){
19201   return p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
19202 }
19203 #else
19204 #define isLookaside(A,B) 0
19205 #endif
19206
19207 /*
19208 ** Return the size of a memory allocation previously obtained from
19209 ** sqlite3Malloc() or sqlite3_malloc().
19210 */
19211 SQLITE_PRIVATE int sqlite3MallocSize(void *p){
19212   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
19213   assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
19214   return sqlite3GlobalConfig.m.xSize(p);
19215 }
19216 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
19217   assert( db==0 || sqlite3_mutex_held(db->mutex) );
19218   if( db && isLookaside(db, p) ){
19219     return db->lookaside.sz;
19220   }else{
19221     assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
19222     assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
19223     assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
19224     return sqlite3GlobalConfig.m.xSize(p);
19225   }
19226 }
19227
19228 /*
19229 ** Free memory previously obtained from sqlite3Malloc().
19230 */
19231 SQLITE_API void sqlite3_free(void *p){
19232   if( p==0 ) return;  /* IMP: R-49053-54554 */
19233   assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
19234   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
19235   if( sqlite3GlobalConfig.bMemstat ){
19236     sqlite3_mutex_enter(mem0.mutex);
19237     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
19238     sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
19239     sqlite3GlobalConfig.m.xFree(p);
19240     sqlite3_mutex_leave(mem0.mutex);
19241   }else{
19242     sqlite3GlobalConfig.m.xFree(p);
19243   }
19244 }
19245
19246 /*
19247 ** Free memory that might be associated with a particular database
19248 ** connection.
19249 */
19250 SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
19251   assert( db==0 || sqlite3_mutex_held(db->mutex) );
19252   if( db ){
19253     if( db->pnBytesFreed ){
19254       *db->pnBytesFreed += sqlite3DbMallocSize(db, p);
19255       return;
19256     }
19257     if( isLookaside(db, p) ){
19258       LookasideSlot *pBuf = (LookasideSlot*)p;
19259 #if SQLITE_DEBUG
19260       /* Trash all content in the buffer being freed */
19261       memset(p, 0xaa, db->lookaside.sz);
19262 #endif
19263       pBuf->pNext = db->lookaside.pFree;
19264       db->lookaside.pFree = pBuf;
19265       db->lookaside.nOut--;
19266       return;
19267     }
19268   }
19269   assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
19270   assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
19271   assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
19272   sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
19273   sqlite3_free(p);
19274 }
19275
19276 /*
19277 ** Change the size of an existing memory allocation
19278 */
19279 SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
19280   int nOld, nNew, nDiff;
19281   void *pNew;
19282   if( pOld==0 ){
19283     return sqlite3Malloc(nBytes); /* IMP: R-28354-25769 */
19284   }
19285   if( nBytes<=0 ){
19286     sqlite3_free(pOld); /* IMP: R-31593-10574 */
19287     return 0;
19288   }
19289   if( nBytes>=0x7fffff00 ){
19290     /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
19291     return 0;
19292   }
19293   nOld = sqlite3MallocSize(pOld);
19294   /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
19295   ** argument to xRealloc is always a value returned by a prior call to
19296   ** xRoundup. */
19297   nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
19298   if( nOld==nNew ){
19299     pNew = pOld;
19300   }else if( sqlite3GlobalConfig.bMemstat ){
19301     sqlite3_mutex_enter(mem0.mutex);
19302     sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
19303     nDiff = nNew - nOld;
19304     if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >= 
19305           mem0.alarmThreshold-nDiff ){
19306       sqlite3MallocAlarm(nDiff);
19307     }
19308     assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
19309     assert( sqlite3MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
19310     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
19311     if( pNew==0 && mem0.alarmCallback ){
19312       sqlite3MallocAlarm(nBytes);
19313       pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
19314     }
19315     if( pNew ){
19316       nNew = sqlite3MallocSize(pNew);
19317       sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
19318     }
19319     sqlite3_mutex_leave(mem0.mutex);
19320   }else{
19321     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
19322   }
19323   assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-04675-44850 */
19324   return pNew;
19325 }
19326
19327 /*
19328 ** The public interface to sqlite3Realloc.  Make sure that the memory
19329 ** subsystem is initialized prior to invoking sqliteRealloc.
19330 */
19331 SQLITE_API void *sqlite3_realloc(void *pOld, int n){
19332 #ifndef SQLITE_OMIT_AUTOINIT
19333   if( sqlite3_initialize() ) return 0;
19334 #endif
19335   return sqlite3Realloc(pOld, n);
19336 }
19337
19338
19339 /*
19340 ** Allocate and zero memory.
19341 */ 
19342 SQLITE_PRIVATE void *sqlite3MallocZero(int n){
19343   void *p = sqlite3Malloc(n);
19344   if( p ){
19345     memset(p, 0, n);
19346   }
19347   return p;
19348 }
19349
19350 /*
19351 ** Allocate and zero memory.  If the allocation fails, make
19352 ** the mallocFailed flag in the connection pointer.
19353 */
19354 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
19355   void *p = sqlite3DbMallocRaw(db, n);
19356   if( p ){
19357     memset(p, 0, n);
19358   }
19359   return p;
19360 }
19361
19362 /*
19363 ** Allocate and zero memory.  If the allocation fails, make
19364 ** the mallocFailed flag in the connection pointer.
19365 **
19366 ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
19367 ** failure on the same database connection) then always return 0.
19368 ** Hence for a particular database connection, once malloc starts
19369 ** failing, it fails consistently until mallocFailed is reset.
19370 ** This is an important assumption.  There are many places in the
19371 ** code that do things like this:
19372 **
19373 **         int *a = (int*)sqlite3DbMallocRaw(db, 100);
19374 **         int *b = (int*)sqlite3DbMallocRaw(db, 200);
19375 **         if( b ) a[10] = 9;
19376 **
19377 ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
19378 ** that all prior mallocs (ex: "a") worked too.
19379 */
19380 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
19381   void *p;
19382   assert( db==0 || sqlite3_mutex_held(db->mutex) );
19383   assert( db==0 || db->pnBytesFreed==0 );
19384 #ifndef SQLITE_OMIT_LOOKASIDE
19385   if( db ){
19386     LookasideSlot *pBuf;
19387     if( db->mallocFailed ){
19388       return 0;
19389     }
19390     if( db->lookaside.bEnabled ){
19391       if( n>db->lookaside.sz ){
19392         db->lookaside.anStat[1]++;
19393       }else if( (pBuf = db->lookaside.pFree)==0 ){
19394         db->lookaside.anStat[2]++;
19395       }else{
19396         db->lookaside.pFree = pBuf->pNext;
19397         db->lookaside.nOut++;
19398         db->lookaside.anStat[0]++;
19399         if( db->lookaside.nOut>db->lookaside.mxOut ){
19400           db->lookaside.mxOut = db->lookaside.nOut;
19401         }
19402         return (void*)pBuf;
19403       }
19404     }
19405   }
19406 #else
19407   if( db && db->mallocFailed ){
19408     return 0;
19409   }
19410 #endif
19411   p = sqlite3Malloc(n);
19412   if( !p && db ){
19413     db->mallocFailed = 1;
19414   }
19415   sqlite3MemdebugSetType(p, MEMTYPE_DB |
19416          ((db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
19417   return p;
19418 }
19419
19420 /*
19421 ** Resize the block of memory pointed to by p to n bytes. If the
19422 ** resize fails, set the mallocFailed flag in the connection object.
19423 */
19424 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
19425   void *pNew = 0;
19426   assert( db!=0 );
19427   assert( sqlite3_mutex_held(db->mutex) );
19428   if( db->mallocFailed==0 ){
19429     if( p==0 ){
19430       return sqlite3DbMallocRaw(db, n);
19431     }
19432     if( isLookaside(db, p) ){
19433       if( n<=db->lookaside.sz ){
19434         return p;
19435       }
19436       pNew = sqlite3DbMallocRaw(db, n);
19437       if( pNew ){
19438         memcpy(pNew, p, db->lookaside.sz);
19439         sqlite3DbFree(db, p);
19440       }
19441     }else{
19442       assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
19443       assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
19444       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
19445       pNew = sqlite3_realloc(p, n);
19446       if( !pNew ){
19447         sqlite3MemdebugSetType(p, MEMTYPE_DB|MEMTYPE_HEAP);
19448         db->mallocFailed = 1;
19449       }
19450       sqlite3MemdebugSetType(pNew, MEMTYPE_DB | 
19451             (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
19452     }
19453   }
19454   return pNew;
19455 }
19456
19457 /*
19458 ** Attempt to reallocate p.  If the reallocation fails, then free p
19459 ** and set the mallocFailed flag in the database connection.
19460 */
19461 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
19462   void *pNew;
19463   pNew = sqlite3DbRealloc(db, p, n);
19464   if( !pNew ){
19465     sqlite3DbFree(db, p);
19466   }
19467   return pNew;
19468 }
19469
19470 /*
19471 ** Make a copy of a string in memory obtained from sqliteMalloc(). These 
19472 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
19473 ** is because when memory debugging is turned on, these two functions are 
19474 ** called via macros that record the current file and line number in the
19475 ** ThreadData structure.
19476 */
19477 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
19478   char *zNew;
19479   size_t n;
19480   if( z==0 ){
19481     return 0;
19482   }
19483   n = sqlite3Strlen30(z) + 1;
19484   assert( (n&0x7fffffff)==n );
19485   zNew = sqlite3DbMallocRaw(db, (int)n);
19486   if( zNew ){
19487     memcpy(zNew, z, n);
19488   }
19489   return zNew;
19490 }
19491 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
19492   char *zNew;
19493   if( z==0 ){
19494     return 0;
19495   }
19496   assert( (n&0x7fffffff)==n );
19497   zNew = sqlite3DbMallocRaw(db, n+1);
19498   if( zNew ){
19499     memcpy(zNew, z, n);
19500     zNew[n] = 0;
19501   }
19502   return zNew;
19503 }
19504
19505 /*
19506 ** Create a string from the zFromat argument and the va_list that follows.
19507 ** Store the string in memory obtained from sqliteMalloc() and make *pz
19508 ** point to that string.
19509 */
19510 SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
19511   va_list ap;
19512   char *z;
19513
19514   va_start(ap, zFormat);
19515   z = sqlite3VMPrintf(db, zFormat, ap);
19516   va_end(ap);
19517   sqlite3DbFree(db, *pz);
19518   *pz = z;
19519 }
19520
19521
19522 /*
19523 ** This function must be called before exiting any API function (i.e. 
19524 ** returning control to the user) that has called sqlite3_malloc or
19525 ** sqlite3_realloc.
19526 **
19527 ** The returned value is normally a copy of the second argument to this
19528 ** function. However, if a malloc() failure has occurred since the previous
19529 ** invocation SQLITE_NOMEM is returned instead. 
19530 **
19531 ** If the first argument, db, is not NULL and a malloc() error has occurred,
19532 ** then the connection error-code (the value returned by sqlite3_errcode())
19533 ** is set to SQLITE_NOMEM.
19534 */
19535 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
19536   /* If the db handle is not NULL, then we must hold the connection handle
19537   ** mutex here. Otherwise the read (and possible write) of db->mallocFailed 
19538   ** is unsafe, as is the call to sqlite3Error().
19539   */
19540   assert( !db || sqlite3_mutex_held(db->mutex) );
19541   if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
19542     sqlite3Error(db, SQLITE_NOMEM, 0);
19543     db->mallocFailed = 0;
19544     rc = SQLITE_NOMEM;
19545   }
19546   return rc & (db ? db->errMask : 0xff);
19547 }
19548
19549 /************** End of malloc.c **********************************************/
19550 /************** Begin file printf.c ******************************************/
19551 /*
19552 ** The "printf" code that follows dates from the 1980's.  It is in
19553 ** the public domain.  The original comments are included here for
19554 ** completeness.  They are very out-of-date but might be useful as
19555 ** an historical reference.  Most of the "enhancements" have been backed
19556 ** out so that the functionality is now the same as standard printf().
19557 **
19558 **************************************************************************
19559 **
19560 ** This file contains code for a set of "printf"-like routines.  These
19561 ** routines format strings much like the printf() from the standard C
19562 ** library, though the implementation here has enhancements to support
19563 ** SQLlite.
19564 */
19565
19566 /*
19567 ** Conversion types fall into various categories as defined by the
19568 ** following enumeration.
19569 */
19570 #define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
19571 #define etFLOAT       2 /* Floating point.  %f */
19572 #define etEXP         3 /* Exponentional notation. %e and %E */
19573 #define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
19574 #define etSIZE        5 /* Return number of characters processed so far. %n */
19575 #define etSTRING      6 /* Strings. %s */
19576 #define etDYNSTRING   7 /* Dynamically allocated strings. %z */
19577 #define etPERCENT     8 /* Percent symbol. %% */
19578 #define etCHARX       9 /* Characters. %c */
19579 /* The rest are extensions, not normally found in printf() */
19580 #define etSQLESCAPE  10 /* Strings with '\'' doubled.  %q */
19581 #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
19582                           NULL pointers replaced by SQL NULL.  %Q */
19583 #define etTOKEN      12 /* a pointer to a Token structure */
19584 #define etSRCLIST    13 /* a pointer to a SrcList */
19585 #define etPOINTER    14 /* The %p conversion */
19586 #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
19587 #define etORDINAL    16 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
19588
19589 #define etINVALID     0 /* Any unrecognized conversion type */
19590
19591
19592 /*
19593 ** An "etByte" is an 8-bit unsigned value.
19594 */
19595 typedef unsigned char etByte;
19596
19597 /*
19598 ** Each builtin conversion character (ex: the 'd' in "%d") is described
19599 ** by an instance of the following structure
19600 */
19601 typedef struct et_info {   /* Information about each format field */
19602   char fmttype;            /* The format field code letter */
19603   etByte base;             /* The base for radix conversion */
19604   etByte flags;            /* One or more of FLAG_ constants below */
19605   etByte type;             /* Conversion paradigm */
19606   etByte charset;          /* Offset into aDigits[] of the digits string */
19607   etByte prefix;           /* Offset into aPrefix[] of the prefix string */
19608 } et_info;
19609
19610 /*
19611 ** Allowed values for et_info.flags
19612 */
19613 #define FLAG_SIGNED  1     /* True if the value to convert is signed */
19614 #define FLAG_INTERN  2     /* True if for internal use only */
19615 #define FLAG_STRING  4     /* Allow infinity precision */
19616
19617
19618 /*
19619 ** The following table is searched linearly, so it is good to put the
19620 ** most frequently used conversion types first.
19621 */
19622 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
19623 static const char aPrefix[] = "-x0\000X0";
19624 static const et_info fmtinfo[] = {
19625   {  'd', 10, 1, etRADIX,      0,  0 },
19626   {  's',  0, 4, etSTRING,     0,  0 },
19627   {  'g',  0, 1, etGENERIC,    30, 0 },
19628   {  'z',  0, 4, etDYNSTRING,  0,  0 },
19629   {  'q',  0, 4, etSQLESCAPE,  0,  0 },
19630   {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
19631   {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
19632   {  'c',  0, 0, etCHARX,      0,  0 },
19633   {  'o',  8, 0, etRADIX,      0,  2 },
19634   {  'u', 10, 0, etRADIX,      0,  0 },
19635   {  'x', 16, 0, etRADIX,      16, 1 },
19636   {  'X', 16, 0, etRADIX,      0,  4 },
19637 #ifndef SQLITE_OMIT_FLOATING_POINT
19638   {  'f',  0, 1, etFLOAT,      0,  0 },
19639   {  'e',  0, 1, etEXP,        30, 0 },
19640   {  'E',  0, 1, etEXP,        14, 0 },
19641   {  'G',  0, 1, etGENERIC,    14, 0 },
19642 #endif
19643   {  'i', 10, 1, etRADIX,      0,  0 },
19644   {  'n',  0, 0, etSIZE,       0,  0 },
19645   {  '%',  0, 0, etPERCENT,    0,  0 },
19646   {  'p', 16, 0, etPOINTER,    0,  1 },
19647
19648 /* All the rest have the FLAG_INTERN bit set and are thus for internal
19649 ** use only */
19650   {  'T',  0, 2, etTOKEN,      0,  0 },
19651   {  'S',  0, 2, etSRCLIST,    0,  0 },
19652   {  'r', 10, 3, etORDINAL,    0,  0 },
19653 };
19654
19655 /*
19656 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
19657 ** conversions will work.
19658 */
19659 #ifndef SQLITE_OMIT_FLOATING_POINT
19660 /*
19661 ** "*val" is a double such that 0.1 <= *val < 10.0
19662 ** Return the ascii code for the leading digit of *val, then
19663 ** multiply "*val" by 10.0 to renormalize.
19664 **
19665 ** Example:
19666 **     input:     *val = 3.14159
19667 **     output:    *val = 1.4159    function return = '3'
19668 **
19669 ** The counter *cnt is incremented each time.  After counter exceeds
19670 ** 16 (the number of significant digits in a 64-bit float) '0' is
19671 ** always returned.
19672 */
19673 static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
19674   int digit;
19675   LONGDOUBLE_TYPE d;
19676   if( (*cnt)<=0 ) return '0';
19677   (*cnt)--;
19678   digit = (int)*val;
19679   d = digit;
19680   digit += '0';
19681   *val = (*val - d)*10.0;
19682   return (char)digit;
19683 }
19684 #endif /* SQLITE_OMIT_FLOATING_POINT */
19685
19686 /*
19687 ** Append N space characters to the given string buffer.
19688 */
19689 SQLITE_PRIVATE void sqlite3AppendSpace(StrAccum *pAccum, int N){
19690   static const char zSpaces[] = "                             ";
19691   while( N>=(int)sizeof(zSpaces)-1 ){
19692     sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
19693     N -= sizeof(zSpaces)-1;
19694   }
19695   if( N>0 ){
19696     sqlite3StrAccumAppend(pAccum, zSpaces, N);
19697   }
19698 }
19699
19700 /*
19701 ** On machines with a small stack size, you can redefine the
19702 ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
19703 */
19704 #ifndef SQLITE_PRINT_BUF_SIZE
19705 # define SQLITE_PRINT_BUF_SIZE 70
19706 #endif
19707 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
19708
19709 /*
19710 ** Render a string given by "fmt" into the StrAccum object.
19711 */
19712 SQLITE_PRIVATE void sqlite3VXPrintf(
19713   StrAccum *pAccum,                  /* Accumulate results here */
19714   int useExtended,                   /* Allow extended %-conversions */
19715   const char *fmt,                   /* Format string */
19716   va_list ap                         /* arguments */
19717 ){
19718   int c;                     /* Next character in the format string */
19719   char *bufpt;               /* Pointer to the conversion buffer */
19720   int precision;             /* Precision of the current field */
19721   int length;                /* Length of the field */
19722   int idx;                   /* A general purpose loop counter */
19723   int width;                 /* Width of the current field */
19724   etByte flag_leftjustify;   /* True if "-" flag is present */
19725   etByte flag_plussign;      /* True if "+" flag is present */
19726   etByte flag_blanksign;     /* True if " " flag is present */
19727   etByte flag_alternateform; /* True if "#" flag is present */
19728   etByte flag_altform2;      /* True if "!" flag is present */
19729   etByte flag_zeropad;       /* True if field width constant starts with zero */
19730   etByte flag_long;          /* True if "l" flag is present */
19731   etByte flag_longlong;      /* True if the "ll" flag is present */
19732   etByte done;               /* Loop termination flag */
19733   etByte xtype = 0;          /* Conversion paradigm */
19734   char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
19735   sqlite_uint64 longvalue;   /* Value for integer types */
19736   LONGDOUBLE_TYPE realvalue; /* Value for real types */
19737   const et_info *infop;      /* Pointer to the appropriate info structure */
19738   char *zOut;                /* Rendering buffer */
19739   int nOut;                  /* Size of the rendering buffer */
19740   char *zExtra;              /* Malloced memory used by some conversion */
19741 #ifndef SQLITE_OMIT_FLOATING_POINT
19742   int  exp, e2;              /* exponent of real numbers */
19743   int nsd;                   /* Number of significant digits returned */
19744   double rounder;            /* Used for rounding floating point values */
19745   etByte flag_dp;            /* True if decimal point should be shown */
19746   etByte flag_rtz;           /* True if trailing zeros should be removed */
19747 #endif
19748   char buf[etBUFSIZE];       /* Conversion buffer */
19749
19750   bufpt = 0;
19751   for(; (c=(*fmt))!=0; ++fmt){
19752     if( c!='%' ){
19753       int amt;
19754       bufpt = (char *)fmt;
19755       amt = 1;
19756       while( (c=(*++fmt))!='%' && c!=0 ) amt++;
19757       sqlite3StrAccumAppend(pAccum, bufpt, amt);
19758       if( c==0 ) break;
19759     }
19760     if( (c=(*++fmt))==0 ){
19761       sqlite3StrAccumAppend(pAccum, "%", 1);
19762       break;
19763     }
19764     /* Find out what flags are present */
19765     flag_leftjustify = flag_plussign = flag_blanksign = 
19766      flag_alternateform = flag_altform2 = flag_zeropad = 0;
19767     done = 0;
19768     do{
19769       switch( c ){
19770         case '-':   flag_leftjustify = 1;     break;
19771         case '+':   flag_plussign = 1;        break;
19772         case ' ':   flag_blanksign = 1;       break;
19773         case '#':   flag_alternateform = 1;   break;
19774         case '!':   flag_altform2 = 1;        break;
19775         case '0':   flag_zeropad = 1;         break;
19776         default:    done = 1;                 break;
19777       }
19778     }while( !done && (c=(*++fmt))!=0 );
19779     /* Get the field width */
19780     width = 0;
19781     if( c=='*' ){
19782       width = va_arg(ap,int);
19783       if( width<0 ){
19784         flag_leftjustify = 1;
19785         width = -width;
19786       }
19787       c = *++fmt;
19788     }else{
19789       while( c>='0' && c<='9' ){
19790         width = width*10 + c - '0';
19791         c = *++fmt;
19792       }
19793     }
19794     /* Get the precision */
19795     if( c=='.' ){
19796       precision = 0;
19797       c = *++fmt;
19798       if( c=='*' ){
19799         precision = va_arg(ap,int);
19800         if( precision<0 ) precision = -precision;
19801         c = *++fmt;
19802       }else{
19803         while( c>='0' && c<='9' ){
19804           precision = precision*10 + c - '0';
19805           c = *++fmt;
19806         }
19807       }
19808     }else{
19809       precision = -1;
19810     }
19811     /* Get the conversion type modifier */
19812     if( c=='l' ){
19813       flag_long = 1;
19814       c = *++fmt;
19815       if( c=='l' ){
19816         flag_longlong = 1;
19817         c = *++fmt;
19818       }else{
19819         flag_longlong = 0;
19820       }
19821     }else{
19822       flag_long = flag_longlong = 0;
19823     }
19824     /* Fetch the info entry for the field */
19825     infop = &fmtinfo[0];
19826     xtype = etINVALID;
19827     for(idx=0; idx<ArraySize(fmtinfo); idx++){
19828       if( c==fmtinfo[idx].fmttype ){
19829         infop = &fmtinfo[idx];
19830         if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
19831           xtype = infop->type;
19832         }else{
19833           return;
19834         }
19835         break;
19836       }
19837     }
19838     zExtra = 0;
19839
19840     /*
19841     ** At this point, variables are initialized as follows:
19842     **
19843     **   flag_alternateform          TRUE if a '#' is present.
19844     **   flag_altform2               TRUE if a '!' is present.
19845     **   flag_plussign               TRUE if a '+' is present.
19846     **   flag_leftjustify            TRUE if a '-' is present or if the
19847     **                               field width was negative.
19848     **   flag_zeropad                TRUE if the width began with 0.
19849     **   flag_long                   TRUE if the letter 'l' (ell) prefixed
19850     **                               the conversion character.
19851     **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
19852     **                               the conversion character.
19853     **   flag_blanksign              TRUE if a ' ' is present.
19854     **   width                       The specified field width.  This is
19855     **                               always non-negative.  Zero is the default.
19856     **   precision                   The specified precision.  The default
19857     **                               is -1.
19858     **   xtype                       The class of the conversion.
19859     **   infop                       Pointer to the appropriate info struct.
19860     */
19861     switch( xtype ){
19862       case etPOINTER:
19863         flag_longlong = sizeof(char*)==sizeof(i64);
19864         flag_long = sizeof(char*)==sizeof(long int);
19865         /* Fall through into the next case */
19866       case etORDINAL:
19867       case etRADIX:
19868         if( infop->flags & FLAG_SIGNED ){
19869           i64 v;
19870           if( flag_longlong ){
19871             v = va_arg(ap,i64);
19872           }else if( flag_long ){
19873             v = va_arg(ap,long int);
19874           }else{
19875             v = va_arg(ap,int);
19876           }
19877           if( v<0 ){
19878             if( v==SMALLEST_INT64 ){
19879               longvalue = ((u64)1)<<63;
19880             }else{
19881               longvalue = -v;
19882             }
19883             prefix = '-';
19884           }else{
19885             longvalue = v;
19886             if( flag_plussign )        prefix = '+';
19887             else if( flag_blanksign )  prefix = ' ';
19888             else                       prefix = 0;
19889           }
19890         }else{
19891           if( flag_longlong ){
19892             longvalue = va_arg(ap,u64);
19893           }else if( flag_long ){
19894             longvalue = va_arg(ap,unsigned long int);
19895           }else{
19896             longvalue = va_arg(ap,unsigned int);
19897           }
19898           prefix = 0;
19899         }
19900         if( longvalue==0 ) flag_alternateform = 0;
19901         if( flag_zeropad && precision<width-(prefix!=0) ){
19902           precision = width-(prefix!=0);
19903         }
19904         if( precision<etBUFSIZE-10 ){
19905           nOut = etBUFSIZE;
19906           zOut = buf;
19907         }else{
19908           nOut = precision + 10;
19909           zOut = zExtra = sqlite3Malloc( nOut );
19910           if( zOut==0 ){
19911             pAccum->mallocFailed = 1;
19912             return;
19913           }
19914         }
19915         bufpt = &zOut[nOut-1];
19916         if( xtype==etORDINAL ){
19917           static const char zOrd[] = "thstndrd";
19918           int x = (int)(longvalue % 10);
19919           if( x>=4 || (longvalue/10)%10==1 ){
19920             x = 0;
19921           }
19922           *(--bufpt) = zOrd[x*2+1];
19923           *(--bufpt) = zOrd[x*2];
19924         }
19925         {
19926           register const char *cset;      /* Use registers for speed */
19927           register int base;
19928           cset = &aDigits[infop->charset];
19929           base = infop->base;
19930           do{                                           /* Convert to ascii */
19931             *(--bufpt) = cset[longvalue%base];
19932             longvalue = longvalue/base;
19933           }while( longvalue>0 );
19934         }
19935         length = (int)(&zOut[nOut-1]-bufpt);
19936         for(idx=precision-length; idx>0; idx--){
19937           *(--bufpt) = '0';                             /* Zero pad */
19938         }
19939         if( prefix ) *(--bufpt) = prefix;               /* Add sign */
19940         if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
19941           const char *pre;
19942           char x;
19943           pre = &aPrefix[infop->prefix];
19944           for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
19945         }
19946         length = (int)(&zOut[nOut-1]-bufpt);
19947         break;
19948       case etFLOAT:
19949       case etEXP:
19950       case etGENERIC:
19951         realvalue = va_arg(ap,double);
19952 #ifdef SQLITE_OMIT_FLOATING_POINT
19953         length = 0;
19954 #else
19955         if( precision<0 ) precision = 6;         /* Set default precision */
19956         if( realvalue<0.0 ){
19957           realvalue = -realvalue;
19958           prefix = '-';
19959         }else{
19960           if( flag_plussign )          prefix = '+';
19961           else if( flag_blanksign )    prefix = ' ';
19962           else                         prefix = 0;
19963         }
19964         if( xtype==etGENERIC && precision>0 ) precision--;
19965 #if 0
19966         /* Rounding works like BSD when the constant 0.4999 is used.  Wierd! */
19967         for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
19968 #else
19969         /* It makes more sense to use 0.5 */
19970         for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
19971 #endif
19972         if( xtype==etFLOAT ) realvalue += rounder;
19973         /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
19974         exp = 0;
19975         if( sqlite3IsNaN((double)realvalue) ){
19976           bufpt = "NaN";
19977           length = 3;
19978           break;
19979         }
19980         if( realvalue>0.0 ){
19981           LONGDOUBLE_TYPE scale = 1.0;
19982           while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
19983           while( realvalue>=1e64*scale && exp<=350 ){ scale *= 1e64; exp+=64; }
19984           while( realvalue>=1e8*scale && exp<=350 ){ scale *= 1e8; exp+=8; }
19985           while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
19986           realvalue /= scale;
19987           while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
19988           while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
19989           if( exp>350 ){
19990             if( prefix=='-' ){
19991               bufpt = "-Inf";
19992             }else if( prefix=='+' ){
19993               bufpt = "+Inf";
19994             }else{
19995               bufpt = "Inf";
19996             }
19997             length = sqlite3Strlen30(bufpt);
19998             break;
19999           }
20000         }
20001         bufpt = buf;
20002         /*
20003         ** If the field type is etGENERIC, then convert to either etEXP
20004         ** or etFLOAT, as appropriate.
20005         */
20006         if( xtype!=etFLOAT ){
20007           realvalue += rounder;
20008           if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
20009         }
20010         if( xtype==etGENERIC ){
20011           flag_rtz = !flag_alternateform;
20012           if( exp<-4 || exp>precision ){
20013             xtype = etEXP;
20014           }else{
20015             precision = precision - exp;
20016             xtype = etFLOAT;
20017           }
20018         }else{
20019           flag_rtz = flag_altform2;
20020         }
20021         if( xtype==etEXP ){
20022           e2 = 0;
20023         }else{
20024           e2 = exp;
20025         }
20026         if( e2+precision+width > etBUFSIZE - 15 ){
20027           bufpt = zExtra = sqlite3Malloc( e2+precision+width+15 );
20028           if( bufpt==0 ){
20029             pAccum->mallocFailed = 1;
20030             return;
20031           }
20032         }
20033         zOut = bufpt;
20034         nsd = 16 + flag_altform2*10;
20035         flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
20036         /* The sign in front of the number */
20037         if( prefix ){
20038           *(bufpt++) = prefix;
20039         }
20040         /* Digits prior to the decimal point */
20041         if( e2<0 ){
20042           *(bufpt++) = '0';
20043         }else{
20044           for(; e2>=0; e2--){
20045             *(bufpt++) = et_getdigit(&realvalue,&nsd);
20046           }
20047         }
20048         /* The decimal point */
20049         if( flag_dp ){
20050           *(bufpt++) = '.';
20051         }
20052         /* "0" digits after the decimal point but before the first
20053         ** significant digit of the number */
20054         for(e2++; e2<0; precision--, e2++){
20055           assert( precision>0 );
20056           *(bufpt++) = '0';
20057         }
20058         /* Significant digits after the decimal point */
20059         while( (precision--)>0 ){
20060           *(bufpt++) = et_getdigit(&realvalue,&nsd);
20061         }
20062         /* Remove trailing zeros and the "." if no digits follow the "." */
20063         if( flag_rtz && flag_dp ){
20064           while( bufpt[-1]=='0' ) *(--bufpt) = 0;
20065           assert( bufpt>zOut );
20066           if( bufpt[-1]=='.' ){
20067             if( flag_altform2 ){
20068               *(bufpt++) = '0';
20069             }else{
20070               *(--bufpt) = 0;
20071             }
20072           }
20073         }
20074         /* Add the "eNNN" suffix */
20075         if( xtype==etEXP ){
20076           *(bufpt++) = aDigits[infop->charset];
20077           if( exp<0 ){
20078             *(bufpt++) = '-'; exp = -exp;
20079           }else{
20080             *(bufpt++) = '+';
20081           }
20082           if( exp>=100 ){
20083             *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
20084             exp %= 100;
20085           }
20086           *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
20087           *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
20088         }
20089         *bufpt = 0;
20090
20091         /* The converted number is in buf[] and zero terminated. Output it.
20092         ** Note that the number is in the usual order, not reversed as with
20093         ** integer conversions. */
20094         length = (int)(bufpt-zOut);
20095         bufpt = zOut;
20096
20097         /* Special case:  Add leading zeros if the flag_zeropad flag is
20098         ** set and we are not left justified */
20099         if( flag_zeropad && !flag_leftjustify && length < width){
20100           int i;
20101           int nPad = width - length;
20102           for(i=width; i>=nPad; i--){
20103             bufpt[i] = bufpt[i-nPad];
20104           }
20105           i = prefix!=0;
20106           while( nPad-- ) bufpt[i++] = '0';
20107           length = width;
20108         }
20109 #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
20110         break;
20111       case etSIZE:
20112         *(va_arg(ap,int*)) = pAccum->nChar;
20113         length = width = 0;
20114         break;
20115       case etPERCENT:
20116         buf[0] = '%';
20117         bufpt = buf;
20118         length = 1;
20119         break;
20120       case etCHARX:
20121         c = va_arg(ap,int);
20122         buf[0] = (char)c;
20123         if( precision>=0 ){
20124           for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
20125           length = precision;
20126         }else{
20127           length =1;
20128         }
20129         bufpt = buf;
20130         break;
20131       case etSTRING:
20132       case etDYNSTRING:
20133         bufpt = va_arg(ap,char*);
20134         if( bufpt==0 ){
20135           bufpt = "";
20136         }else if( xtype==etDYNSTRING ){
20137           zExtra = bufpt;
20138         }
20139         if( precision>=0 ){
20140           for(length=0; length<precision && bufpt[length]; length++){}
20141         }else{
20142           length = sqlite3Strlen30(bufpt);
20143         }
20144         break;
20145       case etSQLESCAPE:
20146       case etSQLESCAPE2:
20147       case etSQLESCAPE3: {
20148         int i, j, k, n, isnull;
20149         int needQuote;
20150         char ch;
20151         char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
20152         char *escarg = va_arg(ap,char*);
20153         isnull = escarg==0;
20154         if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
20155         k = precision;
20156         for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
20157           if( ch==q )  n++;
20158         }
20159         needQuote = !isnull && xtype==etSQLESCAPE2;
20160         n += i + 1 + needQuote*2;
20161         if( n>etBUFSIZE ){
20162           bufpt = zExtra = sqlite3Malloc( n );
20163           if( bufpt==0 ){
20164             pAccum->mallocFailed = 1;
20165             return;
20166           }
20167         }else{
20168           bufpt = buf;
20169         }
20170         j = 0;
20171         if( needQuote ) bufpt[j++] = q;
20172         k = i;
20173         for(i=0; i<k; i++){
20174           bufpt[j++] = ch = escarg[i];
20175           if( ch==q ) bufpt[j++] = ch;
20176         }
20177         if( needQuote ) bufpt[j++] = q;
20178         bufpt[j] = 0;
20179         length = j;
20180         /* The precision in %q and %Q means how many input characters to
20181         ** consume, not the length of the output...
20182         ** if( precision>=0 && precision<length ) length = precision; */
20183         break;
20184       }
20185       case etTOKEN: {
20186         Token *pToken = va_arg(ap, Token*);
20187         if( pToken ){
20188           sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
20189         }
20190         length = width = 0;
20191         break;
20192       }
20193       case etSRCLIST: {
20194         SrcList *pSrc = va_arg(ap, SrcList*);
20195         int k = va_arg(ap, int);
20196         struct SrcList_item *pItem = &pSrc->a[k];
20197         assert( k>=0 && k<pSrc->nSrc );
20198         if( pItem->zDatabase ){
20199           sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
20200           sqlite3StrAccumAppend(pAccum, ".", 1);
20201         }
20202         sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
20203         length = width = 0;
20204         break;
20205       }
20206       default: {
20207         assert( xtype==etINVALID );
20208         return;
20209       }
20210     }/* End switch over the format type */
20211     /*
20212     ** The text of the conversion is pointed to by "bufpt" and is
20213     ** "length" characters long.  The field width is "width".  Do
20214     ** the output.
20215     */
20216     if( !flag_leftjustify ){
20217       register int nspace;
20218       nspace = width-length;
20219       if( nspace>0 ){
20220         sqlite3AppendSpace(pAccum, nspace);
20221       }
20222     }
20223     if( length>0 ){
20224       sqlite3StrAccumAppend(pAccum, bufpt, length);
20225     }
20226     if( flag_leftjustify ){
20227       register int nspace;
20228       nspace = width-length;
20229       if( nspace>0 ){
20230         sqlite3AppendSpace(pAccum, nspace);
20231       }
20232     }
20233     sqlite3_free(zExtra);
20234   }/* End for loop over the format string */
20235 } /* End of function */
20236
20237 /*
20238 ** Append N bytes of text from z to the StrAccum object.
20239 */
20240 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
20241   assert( z!=0 || N==0 );
20242   if( p->tooBig | p->mallocFailed ){
20243     testcase(p->tooBig);
20244     testcase(p->mallocFailed);
20245     return;
20246   }
20247   assert( p->zText!=0 || p->nChar==0 );
20248   if( N<0 ){
20249     N = sqlite3Strlen30(z);
20250   }
20251   if( N==0 || NEVER(z==0) ){
20252     return;
20253   }
20254   if( p->nChar+N >= p->nAlloc ){
20255     char *zNew;
20256     if( !p->useMalloc ){
20257       p->tooBig = 1;
20258       N = p->nAlloc - p->nChar - 1;
20259       if( N<=0 ){
20260         return;
20261       }
20262     }else{
20263       char *zOld = (p->zText==p->zBase ? 0 : p->zText);
20264       i64 szNew = p->nChar;
20265       szNew += N + 1;
20266       if( szNew > p->mxAlloc ){
20267         sqlite3StrAccumReset(p);
20268         p->tooBig = 1;
20269         return;
20270       }else{
20271         p->nAlloc = (int)szNew;
20272       }
20273       if( p->useMalloc==1 ){
20274         zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
20275       }else{
20276         zNew = sqlite3_realloc(zOld, p->nAlloc);
20277       }
20278       if( zNew ){
20279         if( zOld==0 && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
20280         p->zText = zNew;
20281       }else{
20282         p->mallocFailed = 1;
20283         sqlite3StrAccumReset(p);
20284         return;
20285       }
20286     }
20287   }
20288   assert( p->zText );
20289   memcpy(&p->zText[p->nChar], z, N);
20290   p->nChar += N;
20291 }
20292
20293 /*
20294 ** Finish off a string by making sure it is zero-terminated.
20295 ** Return a pointer to the resulting string.  Return a NULL
20296 ** pointer if any kind of error was encountered.
20297 */
20298 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
20299   if( p->zText ){
20300     p->zText[p->nChar] = 0;
20301     if( p->useMalloc && p->zText==p->zBase ){
20302       if( p->useMalloc==1 ){
20303         p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
20304       }else{
20305         p->zText = sqlite3_malloc(p->nChar+1);
20306       }
20307       if( p->zText ){
20308         memcpy(p->zText, p->zBase, p->nChar+1);
20309       }else{
20310         p->mallocFailed = 1;
20311       }
20312     }
20313   }
20314   return p->zText;
20315 }
20316
20317 /*
20318 ** Reset an StrAccum string.  Reclaim all malloced memory.
20319 */
20320 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
20321   if( p->zText!=p->zBase ){
20322     if( p->useMalloc==1 ){
20323       sqlite3DbFree(p->db, p->zText);
20324     }else{
20325       sqlite3_free(p->zText);
20326     }
20327   }
20328   p->zText = 0;
20329 }
20330
20331 /*
20332 ** Initialize a string accumulator
20333 */
20334 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
20335   p->zText = p->zBase = zBase;
20336   p->db = 0;
20337   p->nChar = 0;
20338   p->nAlloc = n;
20339   p->mxAlloc = mx;
20340   p->useMalloc = 1;
20341   p->tooBig = 0;
20342   p->mallocFailed = 0;
20343 }
20344
20345 /*
20346 ** Print into memory obtained from sqliteMalloc().  Use the internal
20347 ** %-conversion extensions.
20348 */
20349 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
20350   char *z;
20351   char zBase[SQLITE_PRINT_BUF_SIZE];
20352   StrAccum acc;
20353   assert( db!=0 );
20354   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
20355                       db->aLimit[SQLITE_LIMIT_LENGTH]);
20356   acc.db = db;
20357   sqlite3VXPrintf(&acc, 1, zFormat, ap);
20358   z = sqlite3StrAccumFinish(&acc);
20359   if( acc.mallocFailed ){
20360     db->mallocFailed = 1;
20361   }
20362   return z;
20363 }
20364
20365 /*
20366 ** Print into memory obtained from sqliteMalloc().  Use the internal
20367 ** %-conversion extensions.
20368 */
20369 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
20370   va_list ap;
20371   char *z;
20372   va_start(ap, zFormat);
20373   z = sqlite3VMPrintf(db, zFormat, ap);
20374   va_end(ap);
20375   return z;
20376 }
20377
20378 /*
20379 ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
20380 ** the string and before returnning.  This routine is intended to be used
20381 ** to modify an existing string.  For example:
20382 **
20383 **       x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
20384 **
20385 */
20386 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
20387   va_list ap;
20388   char *z;
20389   va_start(ap, zFormat);
20390   z = sqlite3VMPrintf(db, zFormat, ap);
20391   va_end(ap);
20392   sqlite3DbFree(db, zStr);
20393   return z;
20394 }
20395
20396 /*
20397 ** Print into memory obtained from sqlite3_malloc().  Omit the internal
20398 ** %-conversion extensions.
20399 */
20400 SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
20401   char *z;
20402   char zBase[SQLITE_PRINT_BUF_SIZE];
20403   StrAccum acc;
20404 #ifndef SQLITE_OMIT_AUTOINIT
20405   if( sqlite3_initialize() ) return 0;
20406 #endif
20407   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
20408   acc.useMalloc = 2;
20409   sqlite3VXPrintf(&acc, 0, zFormat, ap);
20410   z = sqlite3StrAccumFinish(&acc);
20411   return z;
20412 }
20413
20414 /*
20415 ** Print into memory obtained from sqlite3_malloc()().  Omit the internal
20416 ** %-conversion extensions.
20417 */
20418 SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
20419   va_list ap;
20420   char *z;
20421 #ifndef SQLITE_OMIT_AUTOINIT
20422   if( sqlite3_initialize() ) return 0;
20423 #endif
20424   va_start(ap, zFormat);
20425   z = sqlite3_vmprintf(zFormat, ap);
20426   va_end(ap);
20427   return z;
20428 }
20429
20430 /*
20431 ** sqlite3_snprintf() works like snprintf() except that it ignores the
20432 ** current locale settings.  This is important for SQLite because we
20433 ** are not able to use a "," as the decimal point in place of "." as
20434 ** specified by some locales.
20435 **
20436 ** Oops:  The first two arguments of sqlite3_snprintf() are backwards
20437 ** from the snprintf() standard.  Unfortunately, it is too late to change
20438 ** this without breaking compatibility, so we just have to live with the
20439 ** mistake.
20440 **
20441 ** sqlite3_vsnprintf() is the varargs version.
20442 */
20443 SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
20444   StrAccum acc;
20445   if( n<=0 ) return zBuf;
20446   sqlite3StrAccumInit(&acc, zBuf, n, 0);
20447   acc.useMalloc = 0;
20448   sqlite3VXPrintf(&acc, 0, zFormat, ap);
20449   return sqlite3StrAccumFinish(&acc);
20450 }
20451 SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
20452   char *z;
20453   va_list ap;
20454   va_start(ap,zFormat);
20455   z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
20456   va_end(ap);
20457   return z;
20458 }
20459
20460 /*
20461 ** This is the routine that actually formats the sqlite3_log() message.
20462 ** We house it in a separate routine from sqlite3_log() to avoid using
20463 ** stack space on small-stack systems when logging is disabled.
20464 **
20465 ** sqlite3_log() must render into a static buffer.  It cannot dynamically
20466 ** allocate memory because it might be called while the memory allocator
20467 ** mutex is held.
20468 */
20469 static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
20470   StrAccum acc;                          /* String accumulator */
20471   char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */
20472
20473   sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
20474   acc.useMalloc = 0;
20475   sqlite3VXPrintf(&acc, 0, zFormat, ap);
20476   sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
20477                            sqlite3StrAccumFinish(&acc));
20478 }
20479
20480 /*
20481 ** Format and write a message to the log if logging is enabled.
20482 */
20483 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
20484   va_list ap;                             /* Vararg list */
20485   if( sqlite3GlobalConfig.xLog ){
20486     va_start(ap, zFormat);
20487     renderLogMsg(iErrCode, zFormat, ap);
20488     va_end(ap);
20489   }
20490 }
20491
20492 #if defined(SQLITE_DEBUG)
20493 /*
20494 ** A version of printf() that understands %lld.  Used for debugging.
20495 ** The printf() built into some versions of windows does not understand %lld
20496 ** and segfaults if you give it a long long int.
20497 */
20498 SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
20499   va_list ap;
20500   StrAccum acc;
20501   char zBuf[500];
20502   sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
20503   acc.useMalloc = 0;
20504   va_start(ap,zFormat);
20505   sqlite3VXPrintf(&acc, 0, zFormat, ap);
20506   va_end(ap);
20507   sqlite3StrAccumFinish(&acc);
20508   fprintf(stdout,"%s", zBuf);
20509   fflush(stdout);
20510 }
20511 #endif
20512
20513 #ifndef SQLITE_OMIT_TRACE
20514 /*
20515 ** variable-argument wrapper around sqlite3VXPrintf().
20516 */
20517 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
20518   va_list ap;
20519   va_start(ap,zFormat);
20520   sqlite3VXPrintf(p, 1, zFormat, ap);
20521   va_end(ap);
20522 }
20523 #endif
20524
20525 /************** End of printf.c **********************************************/
20526 /************** Begin file random.c ******************************************/
20527 /*
20528 ** 2001 September 15
20529 **
20530 ** The author disclaims copyright to this source code.  In place of
20531 ** a legal notice, here is a blessing:
20532 **
20533 **    May you do good and not evil.
20534 **    May you find forgiveness for yourself and forgive others.
20535 **    May you share freely, never taking more than you give.
20536 **
20537 *************************************************************************
20538 ** This file contains code to implement a pseudo-random number
20539 ** generator (PRNG) for SQLite.
20540 **
20541 ** Random numbers are used by some of the database backends in order
20542 ** to generate random integer keys for tables or random filenames.
20543 */
20544
20545
20546 /* All threads share a single random number generator.
20547 ** This structure is the current state of the generator.
20548 */
20549 static SQLITE_WSD struct sqlite3PrngType {
20550   unsigned char isInit;          /* True if initialized */
20551   unsigned char i, j;            /* State variables */
20552   unsigned char s[256];          /* State variables */
20553 } sqlite3Prng;
20554
20555 /*
20556 ** Get a single 8-bit random value from the RC4 PRNG.  The Mutex
20557 ** must be held while executing this routine.
20558 **
20559 ** Why not just use a library random generator like lrand48() for this?
20560 ** Because the OP_NewRowid opcode in the VDBE depends on having a very
20561 ** good source of random numbers.  The lrand48() library function may
20562 ** well be good enough.  But maybe not.  Or maybe lrand48() has some
20563 ** subtle problems on some systems that could cause problems.  It is hard
20564 ** to know.  To minimize the risk of problems due to bad lrand48()
20565 ** implementations, SQLite uses this random number generator based
20566 ** on RC4, which we know works very well.
20567 **
20568 ** (Later):  Actually, OP_NewRowid does not depend on a good source of
20569 ** randomness any more.  But we will leave this code in all the same.
20570 */
20571 static u8 randomByte(void){
20572   unsigned char t;
20573
20574
20575   /* The "wsdPrng" macro will resolve to the pseudo-random number generator
20576   ** state vector.  If writable static data is unsupported on the target,
20577   ** we have to locate the state vector at run-time.  In the more common
20578   ** case where writable static data is supported, wsdPrng can refer directly
20579   ** to the "sqlite3Prng" state vector declared above.
20580   */
20581 #ifdef SQLITE_OMIT_WSD
20582   struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
20583 # define wsdPrng p[0]
20584 #else
20585 # define wsdPrng sqlite3Prng
20586 #endif
20587
20588
20589   /* Initialize the state of the random number generator once,
20590   ** the first time this routine is called.  The seed value does
20591   ** not need to contain a lot of randomness since we are not
20592   ** trying to do secure encryption or anything like that...
20593   **
20594   ** Nothing in this file or anywhere else in SQLite does any kind of
20595   ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
20596   ** number generator) not as an encryption device.
20597   */
20598   if( !wsdPrng.isInit ){
20599     int i;
20600     char k[256];
20601     wsdPrng.j = 0;
20602     wsdPrng.i = 0;
20603     sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
20604     for(i=0; i<256; i++){
20605       wsdPrng.s[i] = (u8)i;
20606     }
20607     for(i=0; i<256; i++){
20608       wsdPrng.j += wsdPrng.s[i] + k[i];
20609       t = wsdPrng.s[wsdPrng.j];
20610       wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
20611       wsdPrng.s[i] = t;
20612     }
20613     wsdPrng.isInit = 1;
20614   }
20615
20616   /* Generate and return single random byte
20617   */
20618   wsdPrng.i++;
20619   t = wsdPrng.s[wsdPrng.i];
20620   wsdPrng.j += t;
20621   wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
20622   wsdPrng.s[wsdPrng.j] = t;
20623   t += wsdPrng.s[wsdPrng.i];
20624   return wsdPrng.s[t];
20625 }
20626
20627 /*
20628 ** Return N random bytes.
20629 */
20630 SQLITE_API void sqlite3_randomness(int N, void *pBuf){
20631   unsigned char *zBuf = pBuf;
20632 #if SQLITE_THREADSAFE
20633   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
20634 #endif
20635   sqlite3_mutex_enter(mutex);
20636   while( N-- ){
20637     *(zBuf++) = randomByte();
20638   }
20639   sqlite3_mutex_leave(mutex);
20640 }
20641
20642 #ifndef SQLITE_OMIT_BUILTIN_TEST
20643 /*
20644 ** For testing purposes, we sometimes want to preserve the state of
20645 ** PRNG and restore the PRNG to its saved state at a later time, or
20646 ** to reset the PRNG to its initial state.  These routines accomplish
20647 ** those tasks.
20648 **
20649 ** The sqlite3_test_control() interface calls these routines to
20650 ** control the PRNG.
20651 */
20652 static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
20653 SQLITE_PRIVATE void sqlite3PrngSaveState(void){
20654   memcpy(
20655     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
20656     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
20657     sizeof(sqlite3Prng)
20658   );
20659 }
20660 SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
20661   memcpy(
20662     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
20663     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
20664     sizeof(sqlite3Prng)
20665   );
20666 }
20667 SQLITE_PRIVATE void sqlite3PrngResetState(void){
20668   GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
20669 }
20670 #endif /* SQLITE_OMIT_BUILTIN_TEST */
20671
20672 /************** End of random.c **********************************************/
20673 /************** Begin file utf.c *********************************************/
20674 /*
20675 ** 2004 April 13
20676 **
20677 ** The author disclaims copyright to this source code.  In place of
20678 ** a legal notice, here is a blessing:
20679 **
20680 **    May you do good and not evil.
20681 **    May you find forgiveness for yourself and forgive others.
20682 **    May you share freely, never taking more than you give.
20683 **
20684 *************************************************************************
20685 ** This file contains routines used to translate between UTF-8, 
20686 ** UTF-16, UTF-16BE, and UTF-16LE.
20687 **
20688 ** Notes on UTF-8:
20689 **
20690 **   Byte-0    Byte-1    Byte-2    Byte-3    Value
20691 **  0xxxxxxx                                 00000000 00000000 0xxxxxxx
20692 **  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
20693 **  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
20694 **  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
20695 **
20696 **
20697 ** Notes on UTF-16:  (with wwww+1==uuuuu)
20698 **
20699 **      Word-0               Word-1          Value
20700 **  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
20701 **  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
20702 **
20703 **
20704 ** BOM or Byte Order Mark:
20705 **     0xff 0xfe   little-endian utf-16 follows
20706 **     0xfe 0xff   big-endian utf-16 follows
20707 **
20708 */
20709 /* #include <assert.h> */
20710
20711 #ifndef SQLITE_AMALGAMATION
20712 /*
20713 ** The following constant value is used by the SQLITE_BIGENDIAN and
20714 ** SQLITE_LITTLEENDIAN macros.
20715 */
20716 SQLITE_PRIVATE const int sqlite3one = 1;
20717 #endif /* SQLITE_AMALGAMATION */
20718
20719 /*
20720 ** This lookup table is used to help decode the first byte of
20721 ** a multi-byte UTF8 character.
20722 */
20723 static const unsigned char sqlite3Utf8Trans1[] = {
20724   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
20725   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
20726   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
20727   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
20728   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
20729   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
20730   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
20731   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
20732 };
20733
20734
20735 #define WRITE_UTF8(zOut, c) {                          \
20736   if( c<0x00080 ){                                     \
20737     *zOut++ = (u8)(c&0xFF);                            \
20738   }                                                    \
20739   else if( c<0x00800 ){                                \
20740     *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
20741     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
20742   }                                                    \
20743   else if( c<0x10000 ){                                \
20744     *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
20745     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
20746     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
20747   }else{                                               \
20748     *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
20749     *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
20750     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
20751     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
20752   }                                                    \
20753 }
20754
20755 #define WRITE_UTF16LE(zOut, c) {                                    \
20756   if( c<=0xFFFF ){                                                  \
20757     *zOut++ = (u8)(c&0x00FF);                                       \
20758     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
20759   }else{                                                            \
20760     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
20761     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
20762     *zOut++ = (u8)(c&0x00FF);                                       \
20763     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
20764   }                                                                 \
20765 }
20766
20767 #define WRITE_UTF16BE(zOut, c) {                                    \
20768   if( c<=0xFFFF ){                                                  \
20769     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
20770     *zOut++ = (u8)(c&0x00FF);                                       \
20771   }else{                                                            \
20772     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
20773     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
20774     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
20775     *zOut++ = (u8)(c&0x00FF);                                       \
20776   }                                                                 \
20777 }
20778
20779 #define READ_UTF16LE(zIn, TERM, c){                                   \
20780   c = (*zIn++);                                                       \
20781   c += ((*zIn++)<<8);                                                 \
20782   if( c>=0xD800 && c<0xE000 && TERM ){                                \
20783     int c2 = (*zIn++);                                                \
20784     c2 += ((*zIn++)<<8);                                              \
20785     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
20786   }                                                                   \
20787 }
20788
20789 #define READ_UTF16BE(zIn, TERM, c){                                   \
20790   c = ((*zIn++)<<8);                                                  \
20791   c += (*zIn++);                                                      \
20792   if( c>=0xD800 && c<0xE000 && TERM ){                                \
20793     int c2 = ((*zIn++)<<8);                                           \
20794     c2 += (*zIn++);                                                   \
20795     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
20796   }                                                                   \
20797 }
20798
20799 /*
20800 ** Translate a single UTF-8 character.  Return the unicode value.
20801 **
20802 ** During translation, assume that the byte that zTerm points
20803 ** is a 0x00.
20804 **
20805 ** Write a pointer to the next unread byte back into *pzNext.
20806 **
20807 ** Notes On Invalid UTF-8:
20808 **
20809 **  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
20810 **     be encoded as a multi-byte character.  Any multi-byte character that
20811 **     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
20812 **
20813 **  *  This routine never allows a UTF16 surrogate value to be encoded.
20814 **     If a multi-byte character attempts to encode a value between
20815 **     0xd800 and 0xe000 then it is rendered as 0xfffd.
20816 **
20817 **  *  Bytes in the range of 0x80 through 0xbf which occur as the first
20818 **     byte of a character are interpreted as single-byte characters
20819 **     and rendered as themselves even though they are technically
20820 **     invalid characters.
20821 **
20822 **  *  This routine accepts an infinite number of different UTF8 encodings
20823 **     for unicode values 0x80 and greater.  It do not change over-length
20824 **     encodings to 0xfffd as some systems recommend.
20825 */
20826 #define READ_UTF8(zIn, zTerm, c)                           \
20827   c = *(zIn++);                                            \
20828   if( c>=0xc0 ){                                           \
20829     c = sqlite3Utf8Trans1[c-0xc0];                         \
20830     while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
20831       c = (c<<6) + (0x3f & *(zIn++));                      \
20832     }                                                      \
20833     if( c<0x80                                             \
20834         || (c&0xFFFFF800)==0xD800                          \
20835         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
20836   }
20837 SQLITE_PRIVATE u32 sqlite3Utf8Read(
20838   const unsigned char **pz    /* Pointer to string from which to read char */
20839 ){
20840   unsigned int c;
20841
20842   /* Same as READ_UTF8() above but without the zTerm parameter.
20843   ** For this routine, we assume the UTF8 string is always zero-terminated.
20844   */
20845   c = *((*pz)++);
20846   if( c>=0xc0 ){
20847     c = sqlite3Utf8Trans1[c-0xc0];
20848     while( (*(*pz) & 0xc0)==0x80 ){
20849       c = (c<<6) + (0x3f & *((*pz)++));
20850     }
20851     if( c<0x80
20852         || (c&0xFFFFF800)==0xD800
20853         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
20854   }
20855   return c;
20856 }
20857
20858
20859
20860
20861 /*
20862 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
20863 ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
20864 */ 
20865 /* #define TRANSLATE_TRACE 1 */
20866
20867 #ifndef SQLITE_OMIT_UTF16
20868 /*
20869 ** This routine transforms the internal text encoding used by pMem to
20870 ** desiredEnc. It is an error if the string is already of the desired
20871 ** encoding, or if *pMem does not contain a string value.
20872 */
20873 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
20874   int len;                    /* Maximum length of output string in bytes */
20875   unsigned char *zOut;                  /* Output buffer */
20876   unsigned char *zIn;                   /* Input iterator */
20877   unsigned char *zTerm;                 /* End of input */
20878   unsigned char *z;                     /* Output iterator */
20879   unsigned int c;
20880
20881   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
20882   assert( pMem->flags&MEM_Str );
20883   assert( pMem->enc!=desiredEnc );
20884   assert( pMem->enc!=0 );
20885   assert( pMem->n>=0 );
20886
20887 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
20888   {
20889     char zBuf[100];
20890     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
20891     fprintf(stderr, "INPUT:  %s\n", zBuf);
20892   }
20893 #endif
20894
20895   /* If the translation is between UTF-16 little and big endian, then 
20896   ** all that is required is to swap the byte order. This case is handled
20897   ** differently from the others.
20898   */
20899   if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
20900     u8 temp;
20901     int rc;
20902     rc = sqlite3VdbeMemMakeWriteable(pMem);
20903     if( rc!=SQLITE_OK ){
20904       assert( rc==SQLITE_NOMEM );
20905       return SQLITE_NOMEM;
20906     }
20907     zIn = (u8*)pMem->z;
20908     zTerm = &zIn[pMem->n&~1];
20909     while( zIn<zTerm ){
20910       temp = *zIn;
20911       *zIn = *(zIn+1);
20912       zIn++;
20913       *zIn++ = temp;
20914     }
20915     pMem->enc = desiredEnc;
20916     goto translate_out;
20917   }
20918
20919   /* Set len to the maximum number of bytes required in the output buffer. */
20920   if( desiredEnc==SQLITE_UTF8 ){
20921     /* When converting from UTF-16, the maximum growth results from
20922     ** translating a 2-byte character to a 4-byte UTF-8 character.
20923     ** A single byte is required for the output string
20924     ** nul-terminator.
20925     */
20926     pMem->n &= ~1;
20927     len = pMem->n * 2 + 1;
20928   }else{
20929     /* When converting from UTF-8 to UTF-16 the maximum growth is caused
20930     ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
20931     ** character. Two bytes are required in the output buffer for the
20932     ** nul-terminator.
20933     */
20934     len = pMem->n * 2 + 2;
20935   }
20936
20937   /* Set zIn to point at the start of the input buffer and zTerm to point 1
20938   ** byte past the end.
20939   **
20940   ** Variable zOut is set to point at the output buffer, space obtained
20941   ** from sqlite3_malloc().
20942   */
20943   zIn = (u8*)pMem->z;
20944   zTerm = &zIn[pMem->n];
20945   zOut = sqlite3DbMallocRaw(pMem->db, len);
20946   if( !zOut ){
20947     return SQLITE_NOMEM;
20948   }
20949   z = zOut;
20950
20951   if( pMem->enc==SQLITE_UTF8 ){
20952     if( desiredEnc==SQLITE_UTF16LE ){
20953       /* UTF-8 -> UTF-16 Little-endian */
20954       while( zIn<zTerm ){
20955         READ_UTF8(zIn, zTerm, c);
20956         WRITE_UTF16LE(z, c);
20957       }
20958     }else{
20959       assert( desiredEnc==SQLITE_UTF16BE );
20960       /* UTF-8 -> UTF-16 Big-endian */
20961       while( zIn<zTerm ){
20962         READ_UTF8(zIn, zTerm, c);
20963         WRITE_UTF16BE(z, c);
20964       }
20965     }
20966     pMem->n = (int)(z - zOut);
20967     *z++ = 0;
20968   }else{
20969     assert( desiredEnc==SQLITE_UTF8 );
20970     if( pMem->enc==SQLITE_UTF16LE ){
20971       /* UTF-16 Little-endian -> UTF-8 */
20972       while( zIn<zTerm ){
20973         READ_UTF16LE(zIn, zIn<zTerm, c); 
20974         WRITE_UTF8(z, c);
20975       }
20976     }else{
20977       /* UTF-16 Big-endian -> UTF-8 */
20978       while( zIn<zTerm ){
20979         READ_UTF16BE(zIn, zIn<zTerm, c); 
20980         WRITE_UTF8(z, c);
20981       }
20982     }
20983     pMem->n = (int)(z - zOut);
20984   }
20985   *z = 0;
20986   assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
20987
20988   sqlite3VdbeMemRelease(pMem);
20989   pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
20990   pMem->enc = desiredEnc;
20991   pMem->flags |= (MEM_Term|MEM_Dyn);
20992   pMem->z = (char*)zOut;
20993   pMem->zMalloc = pMem->z;
20994
20995 translate_out:
20996 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
20997   {
20998     char zBuf[100];
20999     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
21000     fprintf(stderr, "OUTPUT: %s\n", zBuf);
21001   }
21002 #endif
21003   return SQLITE_OK;
21004 }
21005
21006 /*
21007 ** This routine checks for a byte-order mark at the beginning of the 
21008 ** UTF-16 string stored in *pMem. If one is present, it is removed and
21009 ** the encoding of the Mem adjusted. This routine does not do any
21010 ** byte-swapping, it just sets Mem.enc appropriately.
21011 **
21012 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
21013 ** changed by this function.
21014 */
21015 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
21016   int rc = SQLITE_OK;
21017   u8 bom = 0;
21018
21019   assert( pMem->n>=0 );
21020   if( pMem->n>1 ){
21021     u8 b1 = *(u8 *)pMem->z;
21022     u8 b2 = *(((u8 *)pMem->z) + 1);
21023     if( b1==0xFE && b2==0xFF ){
21024       bom = SQLITE_UTF16BE;
21025     }
21026     if( b1==0xFF && b2==0xFE ){
21027       bom = SQLITE_UTF16LE;
21028     }
21029   }
21030   
21031   if( bom ){
21032     rc = sqlite3VdbeMemMakeWriteable(pMem);
21033     if( rc==SQLITE_OK ){
21034       pMem->n -= 2;
21035       memmove(pMem->z, &pMem->z[2], pMem->n);
21036       pMem->z[pMem->n] = '\0';
21037       pMem->z[pMem->n+1] = '\0';
21038       pMem->flags |= MEM_Term;
21039       pMem->enc = bom;
21040     }
21041   }
21042   return rc;
21043 }
21044 #endif /* SQLITE_OMIT_UTF16 */
21045
21046 /*
21047 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
21048 ** return the number of unicode characters in pZ up to (but not including)
21049 ** the first 0x00 byte. If nByte is not less than zero, return the
21050 ** number of unicode characters in the first nByte of pZ (or up to 
21051 ** the first 0x00, whichever comes first).
21052 */
21053 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
21054   int r = 0;
21055   const u8 *z = (const u8*)zIn;
21056   const u8 *zTerm;
21057   if( nByte>=0 ){
21058     zTerm = &z[nByte];
21059   }else{
21060     zTerm = (const u8*)(-1);
21061   }
21062   assert( z<=zTerm );
21063   while( *z!=0 && z<zTerm ){
21064     SQLITE_SKIP_UTF8(z);
21065     r++;
21066   }
21067   return r;
21068 }
21069
21070 /* This test function is not currently used by the automated test-suite. 
21071 ** Hence it is only available in debug builds.
21072 */
21073 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
21074 /*
21075 ** Translate UTF-8 to UTF-8.
21076 **
21077 ** This has the effect of making sure that the string is well-formed
21078 ** UTF-8.  Miscoded characters are removed.
21079 **
21080 ** The translation is done in-place and aborted if the output
21081 ** overruns the input.
21082 */
21083 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
21084   unsigned char *zOut = zIn;
21085   unsigned char *zStart = zIn;
21086   u32 c;
21087
21088   while( zIn[0] && zOut<=zIn ){
21089     c = sqlite3Utf8Read((const u8**)&zIn);
21090     if( c!=0xfffd ){
21091       WRITE_UTF8(zOut, c);
21092     }
21093   }
21094   *zOut = 0;
21095   return (int)(zOut - zStart);
21096 }
21097 #endif
21098
21099 #ifndef SQLITE_OMIT_UTF16
21100 /*
21101 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
21102 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
21103 ** be freed by the calling function.
21104 **
21105 ** NULL is returned if there is an allocation error.
21106 */
21107 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
21108   Mem m;
21109   memset(&m, 0, sizeof(m));
21110   m.db = db;
21111   sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
21112   sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
21113   if( db->mallocFailed ){
21114     sqlite3VdbeMemRelease(&m);
21115     m.z = 0;
21116   }
21117   assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
21118   assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
21119   assert( (m.flags & MEM_Dyn)!=0 || db->mallocFailed );
21120   assert( m.z || db->mallocFailed );
21121   return m.z;
21122 }
21123
21124 /*
21125 ** Convert a UTF-8 string to the UTF-16 encoding specified by parameter
21126 ** enc. A pointer to the new string is returned, and the value of *pnOut
21127 ** is set to the length of the returned string in bytes. The call should
21128 ** arrange to call sqlite3DbFree() on the returned pointer when it is
21129 ** no longer required.
21130 ** 
21131 ** If a malloc failure occurs, NULL is returned and the db.mallocFailed
21132 ** flag set.
21133 */
21134 #ifdef SQLITE_ENABLE_STAT3
21135 SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *db, u8 enc, char *z, int n, int *pnOut){
21136   Mem m;
21137   memset(&m, 0, sizeof(m));
21138   m.db = db;
21139   sqlite3VdbeMemSetStr(&m, z, n, SQLITE_UTF8, SQLITE_STATIC);
21140   if( sqlite3VdbeMemTranslate(&m, enc) ){
21141     assert( db->mallocFailed );
21142     return 0;
21143   }
21144   assert( m.z==m.zMalloc );
21145   *pnOut = m.n;
21146   return m.z;
21147 }
21148 #endif
21149
21150 /*
21151 ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
21152 ** Return the number of bytes in the first nChar unicode characters
21153 ** in pZ.  nChar must be non-negative.
21154 */
21155 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
21156   int c;
21157   unsigned char const *z = zIn;
21158   int n = 0;
21159   
21160   if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
21161     while( n<nChar ){
21162       READ_UTF16BE(z, 1, c);
21163       n++;
21164     }
21165   }else{
21166     while( n<nChar ){
21167       READ_UTF16LE(z, 1, c);
21168       n++;
21169     }
21170   }
21171   return (int)(z-(unsigned char const *)zIn);
21172 }
21173
21174 #if defined(SQLITE_TEST)
21175 /*
21176 ** This routine is called from the TCL test function "translate_selftest".
21177 ** It checks that the primitives for serializing and deserializing
21178 ** characters in each encoding are inverses of each other.
21179 */
21180 SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
21181   unsigned int i, t;
21182   unsigned char zBuf[20];
21183   unsigned char *z;
21184   int n;
21185   unsigned int c;
21186
21187   for(i=0; i<0x00110000; i++){
21188     z = zBuf;
21189     WRITE_UTF8(z, i);
21190     n = (int)(z-zBuf);
21191     assert( n>0 && n<=4 );
21192     z[0] = 0;
21193     z = zBuf;
21194     c = sqlite3Utf8Read((const u8**)&z);
21195     t = i;
21196     if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
21197     if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
21198     assert( c==t );
21199     assert( (z-zBuf)==n );
21200   }
21201   for(i=0; i<0x00110000; i++){
21202     if( i>=0xD800 && i<0xE000 ) continue;
21203     z = zBuf;
21204     WRITE_UTF16LE(z, i);
21205     n = (int)(z-zBuf);
21206     assert( n>0 && n<=4 );
21207     z[0] = 0;
21208     z = zBuf;
21209     READ_UTF16LE(z, 1, c);
21210     assert( c==i );
21211     assert( (z-zBuf)==n );
21212   }
21213   for(i=0; i<0x00110000; i++){
21214     if( i>=0xD800 && i<0xE000 ) continue;
21215     z = zBuf;
21216     WRITE_UTF16BE(z, i);
21217     n = (int)(z-zBuf);
21218     assert( n>0 && n<=4 );
21219     z[0] = 0;
21220     z = zBuf;
21221     READ_UTF16BE(z, 1, c);
21222     assert( c==i );
21223     assert( (z-zBuf)==n );
21224   }
21225 }
21226 #endif /* SQLITE_TEST */
21227 #endif /* SQLITE_OMIT_UTF16 */
21228
21229 /************** End of utf.c *************************************************/
21230 /************** Begin file util.c ********************************************/
21231 /*
21232 ** 2001 September 15
21233 **
21234 ** The author disclaims copyright to this source code.  In place of
21235 ** a legal notice, here is a blessing:
21236 **
21237 **    May you do good and not evil.
21238 **    May you find forgiveness for yourself and forgive others.
21239 **    May you share freely, never taking more than you give.
21240 **
21241 *************************************************************************
21242 ** Utility functions used throughout sqlite.
21243 **
21244 ** This file contains functions for allocating memory, comparing
21245 ** strings, and stuff like that.
21246 **
21247 */
21248 /* #include <stdarg.h> */
21249 #ifdef SQLITE_HAVE_ISNAN
21250 # include <math.h>
21251 #endif
21252
21253 /*
21254 ** Routine needed to support the testcase() macro.
21255 */
21256 #ifdef SQLITE_COVERAGE_TEST
21257 SQLITE_PRIVATE void sqlite3Coverage(int x){
21258   static unsigned dummy = 0;
21259   dummy += (unsigned)x;
21260 }
21261 #endif
21262
21263 #ifndef SQLITE_OMIT_FLOATING_POINT
21264 /*
21265 ** Return true if the floating point value is Not a Number (NaN).
21266 **
21267 ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
21268 ** Otherwise, we have our own implementation that works on most systems.
21269 */
21270 SQLITE_PRIVATE int sqlite3IsNaN(double x){
21271   int rc;   /* The value return */
21272 #if !defined(SQLITE_HAVE_ISNAN)
21273   /*
21274   ** Systems that support the isnan() library function should probably
21275   ** make use of it by compiling with -DSQLITE_HAVE_ISNAN.  But we have
21276   ** found that many systems do not have a working isnan() function so
21277   ** this implementation is provided as an alternative.
21278   **
21279   ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
21280   ** On the other hand, the use of -ffast-math comes with the following
21281   ** warning:
21282   **
21283   **      This option [-ffast-math] should never be turned on by any
21284   **      -O option since it can result in incorrect output for programs
21285   **      which depend on an exact implementation of IEEE or ISO 
21286   **      rules/specifications for math functions.
21287   **
21288   ** Under MSVC, this NaN test may fail if compiled with a floating-
21289   ** point precision mode other than /fp:precise.  From the MSDN 
21290   ** documentation:
21291   **
21292   **      The compiler [with /fp:precise] will properly handle comparisons 
21293   **      involving NaN. For example, x != x evaluates to true if x is NaN 
21294   **      ...
21295   */
21296 #ifdef __FAST_MATH__
21297 # error SQLite will not work correctly with the -ffast-math option of GCC.
21298 #endif
21299   volatile double y = x;
21300   volatile double z = y;
21301   rc = (y!=z);
21302 #else  /* if defined(SQLITE_HAVE_ISNAN) */
21303   rc = isnan(x);
21304 #endif /* SQLITE_HAVE_ISNAN */
21305   testcase( rc );
21306   return rc;
21307 }
21308 #endif /* SQLITE_OMIT_FLOATING_POINT */
21309
21310 /*
21311 ** Compute a string length that is limited to what can be stored in
21312 ** lower 30 bits of a 32-bit signed integer.
21313 **
21314 ** The value returned will never be negative.  Nor will it ever be greater
21315 ** than the actual length of the string.  For very long strings (greater
21316 ** than 1GiB) the value returned might be less than the true string length.
21317 */
21318 SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
21319   const char *z2 = z;
21320   if( z==0 ) return 0;
21321   while( *z2 ){ z2++; }
21322   return 0x3fffffff & (int)(z2 - z);
21323 }
21324
21325 /*
21326 ** Set the most recent error code and error string for the sqlite
21327 ** handle "db". The error code is set to "err_code".
21328 **
21329 ** If it is not NULL, string zFormat specifies the format of the
21330 ** error string in the style of the printf functions: The following
21331 ** format characters are allowed:
21332 **
21333 **      %s      Insert a string
21334 **      %z      A string that should be freed after use
21335 **      %d      Insert an integer
21336 **      %T      Insert a token
21337 **      %S      Insert the first element of a SrcList
21338 **
21339 ** zFormat and any string tokens that follow it are assumed to be
21340 ** encoded in UTF-8.
21341 **
21342 ** To clear the most recent error for sqlite handle "db", sqlite3Error
21343 ** should be called with err_code set to SQLITE_OK and zFormat set
21344 ** to NULL.
21345 */
21346 SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
21347   if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
21348     db->errCode = err_code;
21349     if( zFormat ){
21350       char *z;
21351       va_list ap;
21352       va_start(ap, zFormat);
21353       z = sqlite3VMPrintf(db, zFormat, ap);
21354       va_end(ap);
21355       sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
21356     }else{
21357       sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
21358     }
21359   }
21360 }
21361
21362 /*
21363 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
21364 ** The following formatting characters are allowed:
21365 **
21366 **      %s      Insert a string
21367 **      %z      A string that should be freed after use
21368 **      %d      Insert an integer
21369 **      %T      Insert a token
21370 **      %S      Insert the first element of a SrcList
21371 **
21372 ** This function should be used to report any error that occurs whilst
21373 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
21374 ** last thing the sqlite3_prepare() function does is copy the error
21375 ** stored by this function into the database handle using sqlite3Error().
21376 ** Function sqlite3Error() should be used during statement execution
21377 ** (sqlite3_step() etc.).
21378 */
21379 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
21380   char *zMsg;
21381   va_list ap;
21382   sqlite3 *db = pParse->db;
21383   va_start(ap, zFormat);
21384   zMsg = sqlite3VMPrintf(db, zFormat, ap);
21385   va_end(ap);
21386   if( db->suppressErr ){
21387     sqlite3DbFree(db, zMsg);
21388   }else{
21389     pParse->nErr++;
21390     sqlite3DbFree(db, pParse->zErrMsg);
21391     pParse->zErrMsg = zMsg;
21392     pParse->rc = SQLITE_ERROR;
21393   }
21394 }
21395
21396 /*
21397 ** Convert an SQL-style quoted string into a normal string by removing
21398 ** the quote characters.  The conversion is done in-place.  If the
21399 ** input does not begin with a quote character, then this routine
21400 ** is a no-op.
21401 **
21402 ** The input string must be zero-terminated.  A new zero-terminator
21403 ** is added to the dequoted string.
21404 **
21405 ** The return value is -1 if no dequoting occurs or the length of the
21406 ** dequoted string, exclusive of the zero terminator, if dequoting does
21407 ** occur.
21408 **
21409 ** 2002-Feb-14: This routine is extended to remove MS-Access style
21410 ** brackets from around identifers.  For example:  "[a-b-c]" becomes
21411 ** "a-b-c".
21412 */
21413 SQLITE_PRIVATE int sqlite3Dequote(char *z){
21414   char quote;
21415   int i, j;
21416   if( z==0 ) return -1;
21417   quote = z[0];
21418   switch( quote ){
21419     case '\'':  break;
21420     case '"':   break;
21421     case '`':   break;                /* For MySQL compatibility */
21422     case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
21423     default:    return -1;
21424   }
21425   for(i=1, j=0; ALWAYS(z[i]); i++){
21426     if( z[i]==quote ){
21427       if( z[i+1]==quote ){
21428         z[j++] = quote;
21429         i++;
21430       }else{
21431         break;
21432       }
21433     }else{
21434       z[j++] = z[i];
21435     }
21436   }
21437   z[j] = 0;
21438   return j;
21439 }
21440
21441 /* Convenient short-hand */
21442 #define UpperToLower sqlite3UpperToLower
21443
21444 /*
21445 ** Some systems have stricmp().  Others have strcasecmp().  Because
21446 ** there is no consistency, we will define our own.
21447 **
21448 ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
21449 ** sqlite3_strnicmp() APIs allow applications and extensions to compare
21450 ** the contents of two buffers containing UTF-8 strings in a
21451 ** case-independent fashion, using the same definition of "case
21452 ** independence" that SQLite uses internally when comparing identifiers.
21453 */
21454 SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){
21455   register unsigned char *a, *b;
21456   a = (unsigned char *)zLeft;
21457   b = (unsigned char *)zRight;
21458   while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
21459   return UpperToLower[*a] - UpperToLower[*b];
21460 }
21461 SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
21462   register unsigned char *a, *b;
21463   a = (unsigned char *)zLeft;
21464   b = (unsigned char *)zRight;
21465   while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
21466   return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
21467 }
21468
21469 /*
21470 ** The string z[] is an text representation of a real number.
21471 ** Convert this string to a double and write it into *pResult.
21472 **
21473 ** The string z[] is length bytes in length (bytes, not characters) and
21474 ** uses the encoding enc.  The string is not necessarily zero-terminated.
21475 **
21476 ** Return TRUE if the result is a valid real number (or integer) and FALSE
21477 ** if the string is empty or contains extraneous text.  Valid numbers
21478 ** are in one of these formats:
21479 **
21480 **    [+-]digits[E[+-]digits]
21481 **    [+-]digits.[digits][E[+-]digits]
21482 **    [+-].digits[E[+-]digits]
21483 **
21484 ** Leading and trailing whitespace is ignored for the purpose of determining
21485 ** validity.
21486 **
21487 ** If some prefix of the input string is a valid number, this routine
21488 ** returns FALSE but it still converts the prefix and writes the result
21489 ** into *pResult.
21490 */
21491 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
21492 #ifndef SQLITE_OMIT_FLOATING_POINT
21493   int incr;
21494   const char *zEnd = z + length;
21495   /* sign * significand * (10 ^ (esign * exponent)) */
21496   int sign = 1;    /* sign of significand */
21497   i64 s = 0;       /* significand */
21498   int d = 0;       /* adjust exponent for shifting decimal point */
21499   int esign = 1;   /* sign of exponent */
21500   int e = 0;       /* exponent */
21501   int eValid = 1;  /* True exponent is either not used or is well-formed */
21502   double result;
21503   int nDigits = 0;
21504   int nonNum = 0;
21505
21506   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
21507   *pResult = 0.0;   /* Default return value, in case of an error */
21508
21509   if( enc==SQLITE_UTF8 ){
21510     incr = 1;
21511   }else{
21512     int i;
21513     incr = 2;
21514     assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
21515     for(i=3-enc; i<length && z[i]==0; i+=2){}
21516     nonNum = i<length;
21517     zEnd = z+i+enc-3;
21518     z += (enc&1);
21519   }
21520
21521   /* skip leading spaces */
21522   while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
21523   if( z>=zEnd ) return 0;
21524
21525   /* get sign of significand */
21526   if( *z=='-' ){
21527     sign = -1;
21528     z+=incr;
21529   }else if( *z=='+' ){
21530     z+=incr;
21531   }
21532
21533   /* skip leading zeroes */
21534   while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
21535
21536   /* copy max significant digits to significand */
21537   while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
21538     s = s*10 + (*z - '0');
21539     z+=incr, nDigits++;
21540   }
21541
21542   /* skip non-significant significand digits
21543   ** (increase exponent by d to shift decimal left) */
21544   while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
21545   if( z>=zEnd ) goto do_atof_calc;
21546
21547   /* if decimal point is present */
21548   if( *z=='.' ){
21549     z+=incr;
21550     /* copy digits from after decimal to significand
21551     ** (decrease exponent by d to shift decimal right) */
21552     while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
21553       s = s*10 + (*z - '0');
21554       z+=incr, nDigits++, d--;
21555     }
21556     /* skip non-significant digits */
21557     while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
21558   }
21559   if( z>=zEnd ) goto do_atof_calc;
21560
21561   /* if exponent is present */
21562   if( *z=='e' || *z=='E' ){
21563     z+=incr;
21564     eValid = 0;
21565     if( z>=zEnd ) goto do_atof_calc;
21566     /* get sign of exponent */
21567     if( *z=='-' ){
21568       esign = -1;
21569       z+=incr;
21570     }else if( *z=='+' ){
21571       z+=incr;
21572     }
21573     /* copy digits to exponent */
21574     while( z<zEnd && sqlite3Isdigit(*z) ){
21575       e = e<10000 ? (e*10 + (*z - '0')) : 10000;
21576       z+=incr;
21577       eValid = 1;
21578     }
21579   }
21580
21581   /* skip trailing spaces */
21582   if( nDigits && eValid ){
21583     while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
21584   }
21585
21586 do_atof_calc:
21587   /* adjust exponent by d, and update sign */
21588   e = (e*esign) + d;
21589   if( e<0 ) {
21590     esign = -1;
21591     e *= -1;
21592   } else {
21593     esign = 1;
21594   }
21595
21596   /* if 0 significand */
21597   if( !s ) {
21598     /* In the IEEE 754 standard, zero is signed.
21599     ** Add the sign if we've seen at least one digit */
21600     result = (sign<0 && nDigits) ? -(double)0 : (double)0;
21601   } else {
21602     /* attempt to reduce exponent */
21603     if( esign>0 ){
21604       while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
21605     }else{
21606       while( !(s%10) && e>0 ) e--,s/=10;
21607     }
21608
21609     /* adjust the sign of significand */
21610     s = sign<0 ? -s : s;
21611
21612     /* if exponent, scale significand as appropriate
21613     ** and store in result. */
21614     if( e ){
21615       LONGDOUBLE_TYPE scale = 1.0;
21616       /* attempt to handle extremely small/large numbers better */
21617       if( e>307 && e<342 ){
21618         while( e%308 ) { scale *= 1.0e+1; e -= 1; }
21619         if( esign<0 ){
21620           result = s / scale;
21621           result /= 1.0e+308;
21622         }else{
21623           result = s * scale;
21624           result *= 1.0e+308;
21625         }
21626       }else if( e>=342 ){
21627         if( esign<0 ){
21628           result = 0.0*s;
21629         }else{
21630           result = 1e308*1e308*s;  /* Infinity */
21631         }
21632       }else{
21633         /* 1.0e+22 is the largest power of 10 than can be 
21634         ** represented exactly. */
21635         while( e%22 ) { scale *= 1.0e+1; e -= 1; }
21636         while( e>0 ) { scale *= 1.0e+22; e -= 22; }
21637         if( esign<0 ){
21638           result = s / scale;
21639         }else{
21640           result = s * scale;
21641         }
21642       }
21643     } else {
21644       result = (double)s;
21645     }
21646   }
21647
21648   /* store the result */
21649   *pResult = result;
21650
21651   /* return true if number and no extra non-whitespace chracters after */
21652   return z>=zEnd && nDigits>0 && eValid && nonNum==0;
21653 #else
21654   return !sqlite3Atoi64(z, pResult, length, enc);
21655 #endif /* SQLITE_OMIT_FLOATING_POINT */
21656 }
21657
21658 /*
21659 ** Compare the 19-character string zNum against the text representation
21660 ** value 2^63:  9223372036854775808.  Return negative, zero, or positive
21661 ** if zNum is less than, equal to, or greater than the string.
21662 ** Note that zNum must contain exactly 19 characters.
21663 **
21664 ** Unlike memcmp() this routine is guaranteed to return the difference
21665 ** in the values of the last digit if the only difference is in the
21666 ** last digit.  So, for example,
21667 **
21668 **      compare2pow63("9223372036854775800", 1)
21669 **
21670 ** will return -8.
21671 */
21672 static int compare2pow63(const char *zNum, int incr){
21673   int c = 0;
21674   int i;
21675                     /* 012345678901234567 */
21676   const char *pow63 = "922337203685477580";
21677   for(i=0; c==0 && i<18; i++){
21678     c = (zNum[i*incr]-pow63[i])*10;
21679   }
21680   if( c==0 ){
21681     c = zNum[18*incr] - '8';
21682     testcase( c==(-1) );
21683     testcase( c==0 );
21684     testcase( c==(+1) );
21685   }
21686   return c;
21687 }
21688
21689
21690 /*
21691 ** Convert zNum to a 64-bit signed integer.
21692 **
21693 ** If the zNum value is representable as a 64-bit twos-complement 
21694 ** integer, then write that value into *pNum and return 0.
21695 **
21696 ** If zNum is exactly 9223372036854665808, return 2.  This special
21697 ** case is broken out because while 9223372036854665808 cannot be a 
21698 ** signed 64-bit integer, its negative -9223372036854665808 can be.
21699 **
21700 ** If zNum is too big for a 64-bit integer and is not
21701 ** 9223372036854665808  or if zNum contains any non-numeric text,
21702 ** then return 1.
21703 **
21704 ** length is the number of bytes in the string (bytes, not characters).
21705 ** The string is not necessarily zero-terminated.  The encoding is
21706 ** given by enc.
21707 */
21708 SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
21709   int incr;
21710   u64 u = 0;
21711   int neg = 0; /* assume positive */
21712   int i;
21713   int c = 0;
21714   int nonNum = 0;
21715   const char *zStart;
21716   const char *zEnd = zNum + length;
21717   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
21718   if( enc==SQLITE_UTF8 ){
21719     incr = 1;
21720   }else{
21721     incr = 2;
21722     assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
21723     for(i=3-enc; i<length && zNum[i]==0; i+=2){}
21724     nonNum = i<length;
21725     zEnd = zNum+i+enc-3;
21726     zNum += (enc&1);
21727   }
21728   while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
21729   if( zNum<zEnd ){
21730     if( *zNum=='-' ){
21731       neg = 1;
21732       zNum+=incr;
21733     }else if( *zNum=='+' ){
21734       zNum+=incr;
21735     }
21736   }
21737   zStart = zNum;
21738   while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
21739   for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
21740     u = u*10 + c - '0';
21741   }
21742   if( u>LARGEST_INT64 ){
21743     *pNum = SMALLEST_INT64;
21744   }else if( neg ){
21745     *pNum = -(i64)u;
21746   }else{
21747     *pNum = (i64)u;
21748   }
21749   testcase( i==18 );
21750   testcase( i==19 );
21751   testcase( i==20 );
21752   if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr || nonNum ){
21753     /* zNum is empty or contains non-numeric text or is longer
21754     ** than 19 digits (thus guaranteeing that it is too large) */
21755     return 1;
21756   }else if( i<19*incr ){
21757     /* Less than 19 digits, so we know that it fits in 64 bits */
21758     assert( u<=LARGEST_INT64 );
21759     return 0;
21760   }else{
21761     /* zNum is a 19-digit numbers.  Compare it against 9223372036854775808. */
21762     c = compare2pow63(zNum, incr);
21763     if( c<0 ){
21764       /* zNum is less than 9223372036854775808 so it fits */
21765       assert( u<=LARGEST_INT64 );
21766       return 0;
21767     }else if( c>0 ){
21768       /* zNum is greater than 9223372036854775808 so it overflows */
21769       return 1;
21770     }else{
21771       /* zNum is exactly 9223372036854775808.  Fits if negative.  The
21772       ** special case 2 overflow if positive */
21773       assert( u-1==LARGEST_INT64 );
21774       assert( (*pNum)==SMALLEST_INT64 );
21775       return neg ? 0 : 2;
21776     }
21777   }
21778 }
21779
21780 /*
21781 ** If zNum represents an integer that will fit in 32-bits, then set
21782 ** *pValue to that integer and return true.  Otherwise return false.
21783 **
21784 ** Any non-numeric characters that following zNum are ignored.
21785 ** This is different from sqlite3Atoi64() which requires the
21786 ** input number to be zero-terminated.
21787 */
21788 SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
21789   sqlite_int64 v = 0;
21790   int i, c;
21791   int neg = 0;
21792   if( zNum[0]=='-' ){
21793     neg = 1;
21794     zNum++;
21795   }else if( zNum[0]=='+' ){
21796     zNum++;
21797   }
21798   while( zNum[0]=='0' ) zNum++;
21799   for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
21800     v = v*10 + c;
21801   }
21802
21803   /* The longest decimal representation of a 32 bit integer is 10 digits:
21804   **
21805   **             1234567890
21806   **     2^31 -> 2147483648
21807   */
21808   testcase( i==10 );
21809   if( i>10 ){
21810     return 0;
21811   }
21812   testcase( v-neg==2147483647 );
21813   if( v-neg>2147483647 ){
21814     return 0;
21815   }
21816   if( neg ){
21817     v = -v;
21818   }
21819   *pValue = (int)v;
21820   return 1;
21821 }
21822
21823 /*
21824 ** Return a 32-bit integer value extracted from a string.  If the
21825 ** string is not an integer, just return 0.
21826 */
21827 SQLITE_PRIVATE int sqlite3Atoi(const char *z){
21828   int x = 0;
21829   if( z ) sqlite3GetInt32(z, &x);
21830   return x;
21831 }
21832
21833 /*
21834 ** The variable-length integer encoding is as follows:
21835 **
21836 ** KEY:
21837 **         A = 0xxxxxxx    7 bits of data and one flag bit
21838 **         B = 1xxxxxxx    7 bits of data and one flag bit
21839 **         C = xxxxxxxx    8 bits of data
21840 **
21841 **  7 bits - A
21842 ** 14 bits - BA
21843 ** 21 bits - BBA
21844 ** 28 bits - BBBA
21845 ** 35 bits - BBBBA
21846 ** 42 bits - BBBBBA
21847 ** 49 bits - BBBBBBA
21848 ** 56 bits - BBBBBBBA
21849 ** 64 bits - BBBBBBBBC
21850 */
21851
21852 /*
21853 ** Write a 64-bit variable-length integer to memory starting at p[0].
21854 ** The length of data write will be between 1 and 9 bytes.  The number
21855 ** of bytes written is returned.
21856 **
21857 ** A variable-length integer consists of the lower 7 bits of each byte
21858 ** for all bytes that have the 8th bit set and one byte with the 8th
21859 ** bit clear.  Except, if we get to the 9th byte, it stores the full
21860 ** 8 bits and is the last byte.
21861 */
21862 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
21863   int i, j, n;
21864   u8 buf[10];
21865   if( v & (((u64)0xff000000)<<32) ){
21866     p[8] = (u8)v;
21867     v >>= 8;
21868     for(i=7; i>=0; i--){
21869       p[i] = (u8)((v & 0x7f) | 0x80);
21870       v >>= 7;
21871     }
21872     return 9;
21873   }    
21874   n = 0;
21875   do{
21876     buf[n++] = (u8)((v & 0x7f) | 0x80);
21877     v >>= 7;
21878   }while( v!=0 );
21879   buf[0] &= 0x7f;
21880   assert( n<=9 );
21881   for(i=0, j=n-1; j>=0; j--, i++){
21882     p[i] = buf[j];
21883   }
21884   return n;
21885 }
21886
21887 /*
21888 ** This routine is a faster version of sqlite3PutVarint() that only
21889 ** works for 32-bit positive integers and which is optimized for
21890 ** the common case of small integers.  A MACRO version, putVarint32,
21891 ** is provided which inlines the single-byte case.  All code should use
21892 ** the MACRO version as this function assumes the single-byte case has
21893 ** already been handled.
21894 */
21895 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
21896 #ifndef putVarint32
21897   if( (v & ~0x7f)==0 ){
21898     p[0] = v;
21899     return 1;
21900   }
21901 #endif
21902   if( (v & ~0x3fff)==0 ){
21903     p[0] = (u8)((v>>7) | 0x80);
21904     p[1] = (u8)(v & 0x7f);
21905     return 2;
21906   }
21907   return sqlite3PutVarint(p, v);
21908 }
21909
21910 /*
21911 ** Bitmasks used by sqlite3GetVarint().  These precomputed constants
21912 ** are defined here rather than simply putting the constant expressions
21913 ** inline in order to work around bugs in the RVT compiler.
21914 **
21915 ** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
21916 **
21917 ** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
21918 */
21919 #define SLOT_2_0     0x001fc07f
21920 #define SLOT_4_2_0   0xf01fc07f
21921
21922
21923 /*
21924 ** Read a 64-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 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
21928   u32 a,b,s;
21929
21930   a = *p;
21931   /* a: p0 (unmasked) */
21932   if (!(a&0x80))
21933   {
21934     *v = a;
21935     return 1;
21936   }
21937
21938   p++;
21939   b = *p;
21940   /* b: p1 (unmasked) */
21941   if (!(b&0x80))
21942   {
21943     a &= 0x7f;
21944     a = a<<7;
21945     a |= b;
21946     *v = a;
21947     return 2;
21948   }
21949
21950   /* Verify that constants are precomputed correctly */
21951   assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
21952   assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
21953
21954   p++;
21955   a = a<<14;
21956   a |= *p;
21957   /* a: p0<<14 | p2 (unmasked) */
21958   if (!(a&0x80))
21959   {
21960     a &= SLOT_2_0;
21961     b &= 0x7f;
21962     b = b<<7;
21963     a |= b;
21964     *v = a;
21965     return 3;
21966   }
21967
21968   /* CSE1 from below */
21969   a &= SLOT_2_0;
21970   p++;
21971   b = b<<14;
21972   b |= *p;
21973   /* b: p1<<14 | p3 (unmasked) */
21974   if (!(b&0x80))
21975   {
21976     b &= SLOT_2_0;
21977     /* moved CSE1 up */
21978     /* a &= (0x7f<<14)|(0x7f); */
21979     a = a<<7;
21980     a |= b;
21981     *v = a;
21982     return 4;
21983   }
21984
21985   /* a: p0<<14 | p2 (masked) */
21986   /* b: p1<<14 | p3 (unmasked) */
21987   /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
21988   /* moved CSE1 up */
21989   /* a &= (0x7f<<14)|(0x7f); */
21990   b &= SLOT_2_0;
21991   s = a;
21992   /* s: p0<<14 | p2 (masked) */
21993
21994   p++;
21995   a = a<<14;
21996   a |= *p;
21997   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
21998   if (!(a&0x80))
21999   {
22000     /* we can skip these cause they were (effectively) done above in calc'ing s */
22001     /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
22002     /* b &= (0x7f<<14)|(0x7f); */
22003     b = b<<7;
22004     a |= b;
22005     s = s>>18;
22006     *v = ((u64)s)<<32 | a;
22007     return 5;
22008   }
22009
22010   /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
22011   s = s<<7;
22012   s |= b;
22013   /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
22014
22015   p++;
22016   b = b<<14;
22017   b |= *p;
22018   /* b: p1<<28 | p3<<14 | p5 (unmasked) */
22019   if (!(b&0x80))
22020   {
22021     /* we can skip this cause it was (effectively) done above in calc'ing s */
22022     /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
22023     a &= SLOT_2_0;
22024     a = a<<7;
22025     a |= b;
22026     s = s>>18;
22027     *v = ((u64)s)<<32 | a;
22028     return 6;
22029   }
22030
22031   p++;
22032   a = a<<14;
22033   a |= *p;
22034   /* a: p2<<28 | p4<<14 | p6 (unmasked) */
22035   if (!(a&0x80))
22036   {
22037     a &= SLOT_4_2_0;
22038     b &= SLOT_2_0;
22039     b = b<<7;
22040     a |= b;
22041     s = s>>11;
22042     *v = ((u64)s)<<32 | a;
22043     return 7;
22044   }
22045
22046   /* CSE2 from below */
22047   a &= SLOT_2_0;
22048   p++;
22049   b = b<<14;
22050   b |= *p;
22051   /* b: p3<<28 | p5<<14 | p7 (unmasked) */
22052   if (!(b&0x80))
22053   {
22054     b &= SLOT_4_2_0;
22055     /* moved CSE2 up */
22056     /* a &= (0x7f<<14)|(0x7f); */
22057     a = a<<7;
22058     a |= b;
22059     s = s>>4;
22060     *v = ((u64)s)<<32 | a;
22061     return 8;
22062   }
22063
22064   p++;
22065   a = a<<15;
22066   a |= *p;
22067   /* a: p4<<29 | p6<<15 | p8 (unmasked) */
22068
22069   /* moved CSE2 up */
22070   /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
22071   b &= SLOT_2_0;
22072   b = b<<8;
22073   a |= b;
22074
22075   s = s<<4;
22076   b = p[-4];
22077   b &= 0x7f;
22078   b = b>>3;
22079   s |= b;
22080
22081   *v = ((u64)s)<<32 | a;
22082
22083   return 9;
22084 }
22085
22086 /*
22087 ** Read a 32-bit variable-length integer from memory starting at p[0].
22088 ** Return the number of bytes read.  The value is stored in *v.
22089 **
22090 ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
22091 ** integer, then set *v to 0xffffffff.
22092 **
22093 ** A MACRO version, getVarint32, is provided which inlines the 
22094 ** single-byte case.  All code should use the MACRO version as 
22095 ** this function assumes the single-byte case has already been handled.
22096 */
22097 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
22098   u32 a,b;
22099
22100   /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
22101   ** by the getVarin32() macro */
22102   a = *p;
22103   /* a: p0 (unmasked) */
22104 #ifndef getVarint32
22105   if (!(a&0x80))
22106   {
22107     /* Values between 0 and 127 */
22108     *v = a;
22109     return 1;
22110   }
22111 #endif
22112
22113   /* The 2-byte case */
22114   p++;
22115   b = *p;
22116   /* b: p1 (unmasked) */
22117   if (!(b&0x80))
22118   {
22119     /* Values between 128 and 16383 */
22120     a &= 0x7f;
22121     a = a<<7;
22122     *v = a | b;
22123     return 2;
22124   }
22125
22126   /* The 3-byte case */
22127   p++;
22128   a = a<<14;
22129   a |= *p;
22130   /* a: p0<<14 | p2 (unmasked) */
22131   if (!(a&0x80))
22132   {
22133     /* Values between 16384 and 2097151 */
22134     a &= (0x7f<<14)|(0x7f);
22135     b &= 0x7f;
22136     b = b<<7;
22137     *v = a | b;
22138     return 3;
22139   }
22140
22141   /* A 32-bit varint is used to store size information in btrees.
22142   ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
22143   ** A 3-byte varint is sufficient, for example, to record the size
22144   ** of a 1048569-byte BLOB or string.
22145   **
22146   ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
22147   ** rare larger cases can be handled by the slower 64-bit varint
22148   ** routine.
22149   */
22150 #if 1
22151   {
22152     u64 v64;
22153     u8 n;
22154
22155     p -= 2;
22156     n = sqlite3GetVarint(p, &v64);
22157     assert( n>3 && n<=9 );
22158     if( (v64 & SQLITE_MAX_U32)!=v64 ){
22159       *v = 0xffffffff;
22160     }else{
22161       *v = (u32)v64;
22162     }
22163     return n;
22164   }
22165
22166 #else
22167   /* For following code (kept for historical record only) shows an
22168   ** unrolling for the 3- and 4-byte varint cases.  This code is
22169   ** slightly faster, but it is also larger and much harder to test.
22170   */
22171   p++;
22172   b = b<<14;
22173   b |= *p;
22174   /* b: p1<<14 | p3 (unmasked) */
22175   if (!(b&0x80))
22176   {
22177     /* Values between 2097152 and 268435455 */
22178     b &= (0x7f<<14)|(0x7f);
22179     a &= (0x7f<<14)|(0x7f);
22180     a = a<<7;
22181     *v = a | b;
22182     return 4;
22183   }
22184
22185   p++;
22186   a = a<<14;
22187   a |= *p;
22188   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
22189   if (!(a&0x80))
22190   {
22191     /* Values  between 268435456 and 34359738367 */
22192     a &= SLOT_4_2_0;
22193     b &= SLOT_4_2_0;
22194     b = b<<7;
22195     *v = a | b;
22196     return 5;
22197   }
22198
22199   /* We can only reach this point when reading a corrupt database
22200   ** file.  In that case we are not in any hurry.  Use the (relatively
22201   ** slow) general-purpose sqlite3GetVarint() routine to extract the
22202   ** value. */
22203   {
22204     u64 v64;
22205     u8 n;
22206
22207     p -= 4;
22208     n = sqlite3GetVarint(p, &v64);
22209     assert( n>5 && n<=9 );
22210     *v = (u32)v64;
22211     return n;
22212   }
22213 #endif
22214 }
22215
22216 /*
22217 ** Return the number of bytes that will be needed to store the given
22218 ** 64-bit integer.
22219 */
22220 SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
22221   int i = 0;
22222   do{
22223     i++;
22224     v >>= 7;
22225   }while( v!=0 && ALWAYS(i<9) );
22226   return i;
22227 }
22228
22229
22230 /*
22231 ** Read or write a four-byte big-endian integer value.
22232 */
22233 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
22234   return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
22235 }
22236 SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
22237   p[0] = (u8)(v>>24);
22238   p[1] = (u8)(v>>16);
22239   p[2] = (u8)(v>>8);
22240   p[3] = (u8)v;
22241 }
22242
22243
22244
22245 /*
22246 ** Translate a single byte of Hex into an integer.
22247 ** This routine only works if h really is a valid hexadecimal
22248 ** character:  0..9a..fA..F
22249 */
22250 SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
22251   assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
22252 #ifdef SQLITE_ASCII
22253   h += 9*(1&(h>>6));
22254 #endif
22255 #ifdef SQLITE_EBCDIC
22256   h += 9*(1&~(h>>4));
22257 #endif
22258   return (u8)(h & 0xf);
22259 }
22260
22261 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
22262 /*
22263 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
22264 ** value.  Return a pointer to its binary value.  Space to hold the
22265 ** binary value has been obtained from malloc and must be freed by
22266 ** the calling routine.
22267 */
22268 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
22269   char *zBlob;
22270   int i;
22271
22272   zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
22273   n--;
22274   if( zBlob ){
22275     for(i=0; i<n; i+=2){
22276       zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
22277     }
22278     zBlob[i/2] = 0;
22279   }
22280   return zBlob;
22281 }
22282 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
22283
22284 /*
22285 ** Log an error that is an API call on a connection pointer that should
22286 ** not have been used.  The "type" of connection pointer is given as the
22287 ** argument.  The zType is a word like "NULL" or "closed" or "invalid".
22288 */
22289 static void logBadConnection(const char *zType){
22290   sqlite3_log(SQLITE_MISUSE, 
22291      "API call with %s database connection pointer",
22292      zType
22293   );
22294 }
22295
22296 /*
22297 ** Check to make sure we have a valid db pointer.  This test is not
22298 ** foolproof but it does provide some measure of protection against
22299 ** misuse of the interface such as passing in db pointers that are
22300 ** NULL or which have been previously closed.  If this routine returns
22301 ** 1 it means that the db pointer is valid and 0 if it should not be
22302 ** dereferenced for any reason.  The calling function should invoke
22303 ** SQLITE_MISUSE immediately.
22304 **
22305 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
22306 ** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
22307 ** open properly and is not fit for general use but which can be
22308 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
22309 */
22310 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
22311   u32 magic;
22312   if( db==0 ){
22313     logBadConnection("NULL");
22314     return 0;
22315   }
22316   magic = db->magic;
22317   if( magic!=SQLITE_MAGIC_OPEN ){
22318     if( sqlite3SafetyCheckSickOrOk(db) ){
22319       testcase( sqlite3GlobalConfig.xLog!=0 );
22320       logBadConnection("unopened");
22321     }
22322     return 0;
22323   }else{
22324     return 1;
22325   }
22326 }
22327 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
22328   u32 magic;
22329   magic = db->magic;
22330   if( magic!=SQLITE_MAGIC_SICK &&
22331       magic!=SQLITE_MAGIC_OPEN &&
22332       magic!=SQLITE_MAGIC_BUSY ){
22333     testcase( sqlite3GlobalConfig.xLog!=0 );
22334     logBadConnection("invalid");
22335     return 0;
22336   }else{
22337     return 1;
22338   }
22339 }
22340
22341 /*
22342 ** Attempt to add, substract, or multiply the 64-bit signed value iB against
22343 ** the other 64-bit signed integer at *pA and store the result in *pA.
22344 ** Return 0 on success.  Or if the operation would have resulted in an
22345 ** overflow, leave *pA unchanged and return 1.
22346 */
22347 SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
22348   i64 iA = *pA;
22349   testcase( iA==0 ); testcase( iA==1 );
22350   testcase( iB==-1 ); testcase( iB==0 );
22351   if( iB>=0 ){
22352     testcase( iA>0 && LARGEST_INT64 - iA == iB );
22353     testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
22354     if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
22355     *pA += iB;
22356   }else{
22357     testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
22358     testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
22359     if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
22360     *pA += iB;
22361   }
22362   return 0; 
22363 }
22364 SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
22365   testcase( iB==SMALLEST_INT64+1 );
22366   if( iB==SMALLEST_INT64 ){
22367     testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
22368     if( (*pA)>=0 ) return 1;
22369     *pA -= iB;
22370     return 0;
22371   }else{
22372     return sqlite3AddInt64(pA, -iB);
22373   }
22374 }
22375 #define TWOPOWER32 (((i64)1)<<32)
22376 #define TWOPOWER31 (((i64)1)<<31)
22377 SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
22378   i64 iA = *pA;
22379   i64 iA1, iA0, iB1, iB0, r;
22380
22381   iA1 = iA/TWOPOWER32;
22382   iA0 = iA % TWOPOWER32;
22383   iB1 = iB/TWOPOWER32;
22384   iB0 = iB % TWOPOWER32;
22385   if( iA1*iB1 != 0 ) return 1;
22386   assert( iA1*iB0==0 || iA0*iB1==0 );
22387   r = iA1*iB0 + iA0*iB1;
22388   testcase( r==(-TWOPOWER31)-1 );
22389   testcase( r==(-TWOPOWER31) );
22390   testcase( r==TWOPOWER31 );
22391   testcase( r==TWOPOWER31-1 );
22392   if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
22393   r *= TWOPOWER32;
22394   if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
22395   *pA = r;
22396   return 0;
22397 }
22398
22399 /*
22400 ** Compute the absolute value of a 32-bit signed integer, of possible.  Or 
22401 ** if the integer has a value of -2147483648, return +2147483647
22402 */
22403 SQLITE_PRIVATE int sqlite3AbsInt32(int x){
22404   if( x>=0 ) return x;
22405   if( x==(int)0x80000000 ) return 0x7fffffff;
22406   return -x;
22407 }
22408
22409 #ifdef SQLITE_ENABLE_8_3_NAMES
22410 /*
22411 ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
22412 ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
22413 ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
22414 ** three characters, then shorten the suffix on z[] to be the last three
22415 ** characters of the original suffix.
22416 **
22417 ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
22418 ** do the suffix shortening regardless of URI parameter.
22419 **
22420 ** Examples:
22421 **
22422 **     test.db-journal    =>   test.nal
22423 **     test.db-wal        =>   test.wal
22424 **     test.db-shm        =>   test.shm
22425 **     test.db-mj7f3319fa =>   test.9fa
22426 */
22427 SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
22428 #if SQLITE_ENABLE_8_3_NAMES<2
22429   if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
22430 #endif
22431   {
22432     int i, sz;
22433     sz = sqlite3Strlen30(z);
22434     for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
22435     if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
22436   }
22437 }
22438 #endif
22439
22440 /************** End of util.c ************************************************/
22441 /************** Begin file hash.c ********************************************/
22442 /*
22443 ** 2001 September 22
22444 **
22445 ** The author disclaims copyright to this source code.  In place of
22446 ** a legal notice, here is a blessing:
22447 **
22448 **    May you do good and not evil.
22449 **    May you find forgiveness for yourself and forgive others.
22450 **    May you share freely, never taking more than you give.
22451 **
22452 *************************************************************************
22453 ** This is the implementation of generic hash-tables
22454 ** used in SQLite.
22455 */
22456 /* #include <assert.h> */
22457
22458 /* Turn bulk memory into a hash table object by initializing the
22459 ** fields of the Hash structure.
22460 **
22461 ** "pNew" is a pointer to the hash table that is to be initialized.
22462 */
22463 SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
22464   assert( pNew!=0 );
22465   pNew->first = 0;
22466   pNew->count = 0;
22467   pNew->htsize = 0;
22468   pNew->ht = 0;
22469 }
22470
22471 /* Remove all entries from a hash table.  Reclaim all memory.
22472 ** Call this routine to delete a hash table or to reset a hash table
22473 ** to the empty state.
22474 */
22475 SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
22476   HashElem *elem;         /* For looping over all elements of the table */
22477
22478   assert( pH!=0 );
22479   elem = pH->first;
22480   pH->first = 0;
22481   sqlite3_free(pH->ht);
22482   pH->ht = 0;
22483   pH->htsize = 0;
22484   while( elem ){
22485     HashElem *next_elem = elem->next;
22486     sqlite3_free(elem);
22487     elem = next_elem;
22488   }
22489   pH->count = 0;
22490 }
22491
22492 /*
22493 ** The hashing function.
22494 */
22495 static unsigned int strHash(const char *z, int nKey){
22496   int h = 0;
22497   assert( nKey>=0 );
22498   while( nKey > 0  ){
22499     h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
22500     nKey--;
22501   }
22502   return h;
22503 }
22504
22505
22506 /* Link pNew element into the hash table pH.  If pEntry!=0 then also
22507 ** insert pNew into the pEntry hash bucket.
22508 */
22509 static void insertElement(
22510   Hash *pH,              /* The complete hash table */
22511   struct _ht *pEntry,    /* The entry into which pNew is inserted */
22512   HashElem *pNew         /* The element to be inserted */
22513 ){
22514   HashElem *pHead;       /* First element already in pEntry */
22515   if( pEntry ){
22516     pHead = pEntry->count ? pEntry->chain : 0;
22517     pEntry->count++;
22518     pEntry->chain = pNew;
22519   }else{
22520     pHead = 0;
22521   }
22522   if( pHead ){
22523     pNew->next = pHead;
22524     pNew->prev = pHead->prev;
22525     if( pHead->prev ){ pHead->prev->next = pNew; }
22526     else             { pH->first = pNew; }
22527     pHead->prev = pNew;
22528   }else{
22529     pNew->next = pH->first;
22530     if( pH->first ){ pH->first->prev = pNew; }
22531     pNew->prev = 0;
22532     pH->first = pNew;
22533   }
22534 }
22535
22536
22537 /* Resize the hash table so that it cantains "new_size" buckets.
22538 **
22539 ** The hash table might fail to resize if sqlite3_malloc() fails or
22540 ** if the new size is the same as the prior size.
22541 ** Return TRUE if the resize occurs and false if not.
22542 */
22543 static int rehash(Hash *pH, unsigned int new_size){
22544   struct _ht *new_ht;            /* The new hash table */
22545   HashElem *elem, *next_elem;    /* For looping over existing elements */
22546
22547 #if SQLITE_MALLOC_SOFT_LIMIT>0
22548   if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
22549     new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
22550   }
22551   if( new_size==pH->htsize ) return 0;
22552 #endif
22553
22554   /* The inability to allocates space for a larger hash table is
22555   ** a performance hit but it is not a fatal error.  So mark the
22556   ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of 
22557   ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
22558   ** only zeroes the requested number of bytes whereas this module will
22559   ** use the actual amount of space allocated for the hash table (which
22560   ** may be larger than the requested amount).
22561   */
22562   sqlite3BeginBenignMalloc();
22563   new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
22564   sqlite3EndBenignMalloc();
22565
22566   if( new_ht==0 ) return 0;
22567   sqlite3_free(pH->ht);
22568   pH->ht = new_ht;
22569   pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
22570   memset(new_ht, 0, new_size*sizeof(struct _ht));
22571   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
22572     unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
22573     next_elem = elem->next;
22574     insertElement(pH, &new_ht[h], elem);
22575   }
22576   return 1;
22577 }
22578
22579 /* This function (for internal use only) locates an element in an
22580 ** hash table that matches the given key.  The hash for this key has
22581 ** already been computed and is passed as the 4th parameter.
22582 */
22583 static HashElem *findElementGivenHash(
22584   const Hash *pH,     /* The pH to be searched */
22585   const char *pKey,   /* The key we are searching for */
22586   int nKey,           /* Bytes in key (not counting zero terminator) */
22587   unsigned int h      /* The hash for this key. */
22588 ){
22589   HashElem *elem;                /* Used to loop thru the element list */
22590   int count;                     /* Number of elements left to test */
22591
22592   if( pH->ht ){
22593     struct _ht *pEntry = &pH->ht[h];
22594     elem = pEntry->chain;
22595     count = pEntry->count;
22596   }else{
22597     elem = pH->first;
22598     count = pH->count;
22599   }
22600   while( count-- && ALWAYS(elem) ){
22601     if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){ 
22602       return elem;
22603     }
22604     elem = elem->next;
22605   }
22606   return 0;
22607 }
22608
22609 /* Remove a single entry from the hash table given a pointer to that
22610 ** element and a hash on the element's key.
22611 */
22612 static void removeElementGivenHash(
22613   Hash *pH,         /* The pH containing "elem" */
22614   HashElem* elem,   /* The element to be removed from the pH */
22615   unsigned int h    /* Hash value for the element */
22616 ){
22617   struct _ht *pEntry;
22618   if( elem->prev ){
22619     elem->prev->next = elem->next; 
22620   }else{
22621     pH->first = elem->next;
22622   }
22623   if( elem->next ){
22624     elem->next->prev = elem->prev;
22625   }
22626   if( pH->ht ){
22627     pEntry = &pH->ht[h];
22628     if( pEntry->chain==elem ){
22629       pEntry->chain = elem->next;
22630     }
22631     pEntry->count--;
22632     assert( pEntry->count>=0 );
22633   }
22634   sqlite3_free( elem );
22635   pH->count--;
22636   if( pH->count==0 ){
22637     assert( pH->first==0 );
22638     assert( pH->count==0 );
22639     sqlite3HashClear(pH);
22640   }
22641 }
22642
22643 /* Attempt to locate an element of the hash table pH with a key
22644 ** that matches pKey,nKey.  Return the data for this element if it is
22645 ** found, or NULL if there is no match.
22646 */
22647 SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){
22648   HashElem *elem;    /* The element that matches key */
22649   unsigned int h;    /* A hash on key */
22650
22651   assert( pH!=0 );
22652   assert( pKey!=0 );
22653   assert( nKey>=0 );
22654   if( pH->ht ){
22655     h = strHash(pKey, nKey) % pH->htsize;
22656   }else{
22657     h = 0;
22658   }
22659   elem = findElementGivenHash(pH, pKey, nKey, h);
22660   return elem ? elem->data : 0;
22661 }
22662
22663 /* Insert an element into the hash table pH.  The key is pKey,nKey
22664 ** and the data is "data".
22665 **
22666 ** If no element exists with a matching key, then a new
22667 ** element is created and NULL is returned.
22668 **
22669 ** If another element already exists with the same key, then the
22670 ** new data replaces the old data and the old data is returned.
22671 ** The key is not copied in this instance.  If a malloc fails, then
22672 ** the new data is returned and the hash table is unchanged.
22673 **
22674 ** If the "data" parameter to this function is NULL, then the
22675 ** element corresponding to "key" is removed from the hash table.
22676 */
22677 SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
22678   unsigned int h;       /* the hash of the key modulo hash table size */
22679   HashElem *elem;       /* Used to loop thru the element list */
22680   HashElem *new_elem;   /* New element added to the pH */
22681
22682   assert( pH!=0 );
22683   assert( pKey!=0 );
22684   assert( nKey>=0 );
22685   if( pH->htsize ){
22686     h = strHash(pKey, nKey) % pH->htsize;
22687   }else{
22688     h = 0;
22689   }
22690   elem = findElementGivenHash(pH,pKey,nKey,h);
22691   if( elem ){
22692     void *old_data = elem->data;
22693     if( data==0 ){
22694       removeElementGivenHash(pH,elem,h);
22695     }else{
22696       elem->data = data;
22697       elem->pKey = pKey;
22698       assert(nKey==elem->nKey);
22699     }
22700     return old_data;
22701   }
22702   if( data==0 ) return 0;
22703   new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
22704   if( new_elem==0 ) return data;
22705   new_elem->pKey = pKey;
22706   new_elem->nKey = nKey;
22707   new_elem->data = data;
22708   pH->count++;
22709   if( pH->count>=10 && pH->count > 2*pH->htsize ){
22710     if( rehash(pH, pH->count*2) ){
22711       assert( pH->htsize>0 );
22712       h = strHash(pKey, nKey) % pH->htsize;
22713     }
22714   }
22715   if( pH->ht ){
22716     insertElement(pH, &pH->ht[h], new_elem);
22717   }else{
22718     insertElement(pH, 0, new_elem);
22719   }
22720   return 0;
22721 }
22722
22723 /************** End of hash.c ************************************************/
22724 /************** Begin file opcodes.c *****************************************/
22725 /* Automatically generated.  Do not edit */
22726 /* See the mkopcodec.awk script for details. */
22727 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
22728 SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
22729  static const char *const azName[] = { "?",
22730      /*   1 */ "Goto",
22731      /*   2 */ "Gosub",
22732      /*   3 */ "Return",
22733      /*   4 */ "Yield",
22734      /*   5 */ "HaltIfNull",
22735      /*   6 */ "Halt",
22736      /*   7 */ "Integer",
22737      /*   8 */ "Int64",
22738      /*   9 */ "String",
22739      /*  10 */ "Null",
22740      /*  11 */ "Blob",
22741      /*  12 */ "Variable",
22742      /*  13 */ "Move",
22743      /*  14 */ "Copy",
22744      /*  15 */ "SCopy",
22745      /*  16 */ "ResultRow",
22746      /*  17 */ "CollSeq",
22747      /*  18 */ "Function",
22748      /*  19 */ "Not",
22749      /*  20 */ "AddImm",
22750      /*  21 */ "MustBeInt",
22751      /*  22 */ "RealAffinity",
22752      /*  23 */ "Permutation",
22753      /*  24 */ "Compare",
22754      /*  25 */ "Jump",
22755      /*  26 */ "Once",
22756      /*  27 */ "If",
22757      /*  28 */ "IfNot",
22758      /*  29 */ "Column",
22759      /*  30 */ "Affinity",
22760      /*  31 */ "MakeRecord",
22761      /*  32 */ "Count",
22762      /*  33 */ "Savepoint",
22763      /*  34 */ "AutoCommit",
22764      /*  35 */ "Transaction",
22765      /*  36 */ "ReadCookie",
22766      /*  37 */ "SetCookie",
22767      /*  38 */ "VerifyCookie",
22768      /*  39 */ "OpenRead",
22769      /*  40 */ "OpenWrite",
22770      /*  41 */ "OpenAutoindex",
22771      /*  42 */ "OpenEphemeral",
22772      /*  43 */ "SorterOpen",
22773      /*  44 */ "OpenPseudo",
22774      /*  45 */ "Close",
22775      /*  46 */ "SeekLt",
22776      /*  47 */ "SeekLe",
22777      /*  48 */ "SeekGe",
22778      /*  49 */ "SeekGt",
22779      /*  50 */ "Seek",
22780      /*  51 */ "NotFound",
22781      /*  52 */ "Found",
22782      /*  53 */ "IsUnique",
22783      /*  54 */ "NotExists",
22784      /*  55 */ "Sequence",
22785      /*  56 */ "NewRowid",
22786      /*  57 */ "Insert",
22787      /*  58 */ "InsertInt",
22788      /*  59 */ "Delete",
22789      /*  60 */ "ResetCount",
22790      /*  61 */ "SorterCompare",
22791      /*  62 */ "SorterData",
22792      /*  63 */ "RowKey",
22793      /*  64 */ "RowData",
22794      /*  65 */ "Rowid",
22795      /*  66 */ "NullRow",
22796      /*  67 */ "Last",
22797      /*  68 */ "Or",
22798      /*  69 */ "And",
22799      /*  70 */ "SorterSort",
22800      /*  71 */ "Sort",
22801      /*  72 */ "Rewind",
22802      /*  73 */ "IsNull",
22803      /*  74 */ "NotNull",
22804      /*  75 */ "Ne",
22805      /*  76 */ "Eq",
22806      /*  77 */ "Gt",
22807      /*  78 */ "Le",
22808      /*  79 */ "Lt",
22809      /*  80 */ "Ge",
22810      /*  81 */ "SorterNext",
22811      /*  82 */ "BitAnd",
22812      /*  83 */ "BitOr",
22813      /*  84 */ "ShiftLeft",
22814      /*  85 */ "ShiftRight",
22815      /*  86 */ "Add",
22816      /*  87 */ "Subtract",
22817      /*  88 */ "Multiply",
22818      /*  89 */ "Divide",
22819      /*  90 */ "Remainder",
22820      /*  91 */ "Concat",
22821      /*  92 */ "Prev",
22822      /*  93 */ "BitNot",
22823      /*  94 */ "String8",
22824      /*  95 */ "Next",
22825      /*  96 */ "SorterInsert",
22826      /*  97 */ "IdxInsert",
22827      /*  98 */ "IdxDelete",
22828      /*  99 */ "IdxRowid",
22829      /* 100 */ "IdxLT",
22830      /* 101 */ "IdxGE",
22831      /* 102 */ "Destroy",
22832      /* 103 */ "Clear",
22833      /* 104 */ "CreateIndex",
22834      /* 105 */ "CreateTable",
22835      /* 106 */ "ParseSchema",
22836      /* 107 */ "LoadAnalysis",
22837      /* 108 */ "DropTable",
22838      /* 109 */ "DropIndex",
22839      /* 110 */ "DropTrigger",
22840      /* 111 */ "IntegrityCk",
22841      /* 112 */ "RowSetAdd",
22842      /* 113 */ "RowSetRead",
22843      /* 114 */ "RowSetTest",
22844      /* 115 */ "Program",
22845      /* 116 */ "Param",
22846      /* 117 */ "FkCounter",
22847      /* 118 */ "FkIfZero",
22848      /* 119 */ "MemMax",
22849      /* 120 */ "IfPos",
22850      /* 121 */ "IfNeg",
22851      /* 122 */ "IfZero",
22852      /* 123 */ "AggStep",
22853      /* 124 */ "AggFinal",
22854      /* 125 */ "Checkpoint",
22855      /* 126 */ "JournalMode",
22856      /* 127 */ "Vacuum",
22857      /* 128 */ "IncrVacuum",
22858      /* 129 */ "Expire",
22859      /* 130 */ "Real",
22860      /* 131 */ "TableLock",
22861      /* 132 */ "VBegin",
22862      /* 133 */ "VCreate",
22863      /* 134 */ "VDestroy",
22864      /* 135 */ "VOpen",
22865      /* 136 */ "VFilter",
22866      /* 137 */ "VColumn",
22867      /* 138 */ "VNext",
22868      /* 139 */ "VRename",
22869      /* 140 */ "VUpdate",
22870      /* 141 */ "ToText",
22871      /* 142 */ "ToBlob",
22872      /* 143 */ "ToNumeric",
22873      /* 144 */ "ToInt",
22874      /* 145 */ "ToReal",
22875      /* 146 */ "Pagecount",
22876      /* 147 */ "MaxPgcnt",
22877      /* 148 */ "Trace",
22878      /* 149 */ "Noop",
22879      /* 150 */ "Explain",
22880   };
22881   return azName[i];
22882 }
22883 #endif
22884
22885 /************** End of opcodes.c *********************************************/
22886 /************** Begin file os_unix.c *****************************************/
22887 /*
22888 ** 2004 May 22
22889 **
22890 ** The author disclaims copyright to this source code.  In place of
22891 ** a legal notice, here is a blessing:
22892 **
22893 **    May you do good and not evil.
22894 **    May you find forgiveness for yourself and forgive others.
22895 **    May you share freely, never taking more than you give.
22896 **
22897 ******************************************************************************
22898 **
22899 ** This file contains the VFS implementation for unix-like operating systems
22900 ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
22901 **
22902 ** There are actually several different VFS implementations in this file.
22903 ** The differences are in the way that file locking is done.  The default
22904 ** implementation uses Posix Advisory Locks.  Alternative implementations
22905 ** use flock(), dot-files, various proprietary locking schemas, or simply
22906 ** skip locking all together.
22907 **
22908 ** This source file is organized into divisions where the logic for various
22909 ** subfunctions is contained within the appropriate division.  PLEASE
22910 ** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed
22911 ** in the correct division and should be clearly labeled.
22912 **
22913 ** The layout of divisions is as follows:
22914 **
22915 **   *  General-purpose declarations and utility functions.
22916 **   *  Unique file ID logic used by VxWorks.
22917 **   *  Various locking primitive implementations (all except proxy locking):
22918 **      + for Posix Advisory Locks
22919 **      + for no-op locks
22920 **      + for dot-file locks
22921 **      + for flock() locking
22922 **      + for named semaphore locks (VxWorks only)
22923 **      + for AFP filesystem locks (MacOSX only)
22924 **   *  sqlite3_file methods not associated with locking.
22925 **   *  Definitions of sqlite3_io_methods objects for all locking
22926 **      methods plus "finder" functions for each locking method.
22927 **   *  sqlite3_vfs method implementations.
22928 **   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
22929 **   *  Definitions of sqlite3_vfs objects for all locking methods
22930 **      plus implementations of sqlite3_os_init() and sqlite3_os_end().
22931 */
22932 #if SQLITE_OS_UNIX              /* This file is used on unix only */
22933
22934 /* Use posix_fallocate() if it is available
22935 */
22936 #if !defined(HAVE_POSIX_FALLOCATE) \
22937       && (_XOPEN_SOURCE >= 600 || _POSIX_C_SOURCE >= 200112L)
22938 # define HAVE_POSIX_FALLOCATE 1
22939 #endif
22940
22941 #ifdef __UCLIBC__
22942   #undef HAVE_POSIX_FALLOCATE
22943 #endif
22944
22945 /*
22946 ** There are various methods for file locking used for concurrency
22947 ** control:
22948 **
22949 **   1. POSIX locking (the default),
22950 **   2. No locking,
22951 **   3. Dot-file locking,
22952 **   4. flock() locking,
22953 **   5. AFP locking (OSX only),
22954 **   6. Named POSIX semaphores (VXWorks only),
22955 **   7. proxy locking. (OSX only)
22956 **
22957 ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
22958 ** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
22959 ** selection of the appropriate locking style based on the filesystem
22960 ** where the database is located.  
22961 */
22962 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
22963 #  if defined(__APPLE__)
22964 #    define SQLITE_ENABLE_LOCKING_STYLE 1
22965 #  else
22966 #    define SQLITE_ENABLE_LOCKING_STYLE 0
22967 #  endif
22968 #endif
22969
22970 /*
22971 ** Define the OS_VXWORKS pre-processor macro to 1 if building on 
22972 ** vxworks, or 0 otherwise.
22973 */
22974 #ifndef OS_VXWORKS
22975 #  if defined(__RTP__) || defined(_WRS_KERNEL)
22976 #    define OS_VXWORKS 1
22977 #  else
22978 #    define OS_VXWORKS 0
22979 #  endif
22980 #endif
22981
22982 /*
22983 ** These #defines should enable >2GB file support on Posix if the
22984 ** underlying operating system supports it.  If the OS lacks
22985 ** large file support, these should be no-ops.
22986 **
22987 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
22988 ** on the compiler command line.  This is necessary if you are compiling
22989 ** on a recent machine (ex: RedHat 7.2) but you want your code to work
22990 ** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
22991 ** without this option, LFS is enable.  But LFS does not exist in the kernel
22992 ** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
22993 ** portability you should omit LFS.
22994 **
22995 ** The previous paragraph was written in 2005.  (This paragraph is written
22996 ** on 2008-11-28.) These days, all Linux kernels support large files, so
22997 ** you should probably leave LFS enabled.  But some embedded platforms might
22998 ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
22999 */
23000 #ifndef SQLITE_DISABLE_LFS
23001 # define _LARGE_FILE       1
23002 # ifndef _FILE_OFFSET_BITS
23003 #   define _FILE_OFFSET_BITS 64
23004 # endif
23005 # define _LARGEFILE_SOURCE 1
23006 #endif
23007
23008 /*
23009 ** standard include files.
23010 */
23011 #include <sys/types.h>
23012 #include <sys/stat.h>
23013 #include <fcntl.h>
23014 #include <unistd.h>
23015 /* #include <time.h> */
23016 #include <sys/time.h>
23017 #include <errno.h>
23018 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
23019 #include <sys/mman.h>
23020 #endif
23021
23022
23023 #if SQLITE_ENABLE_LOCKING_STYLE
23024 # include <sys/ioctl.h>
23025 # if OS_VXWORKS
23026 #  include <semaphore.h>
23027 #  include <limits.h>
23028 # else
23029 #  include <sys/file.h>
23030 #  include <sys/param.h>
23031 # endif
23032 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
23033
23034 #if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
23035 # include <sys/mount.h>
23036 #endif
23037
23038 #ifdef HAVE_UTIME
23039 # include <utime.h>
23040 #endif
23041
23042 /*
23043 ** Allowed values of unixFile.fsFlags
23044 */
23045 #define SQLITE_FSFLAGS_IS_MSDOS     0x1
23046
23047 /*
23048 ** If we are to be thread-safe, include the pthreads header and define
23049 ** the SQLITE_UNIX_THREADS macro.
23050 */
23051 #if SQLITE_THREADSAFE
23052 /* # include <pthread.h> */
23053 # define SQLITE_UNIX_THREADS 1
23054 #endif
23055
23056 /*
23057 ** Default permissions when creating a new file
23058 */
23059 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
23060 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
23061 #endif
23062
23063 /*
23064 ** Default permissions when creating auto proxy dir
23065 */
23066 #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
23067 # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
23068 #endif
23069
23070 /*
23071 ** Maximum supported path-length.
23072 */
23073 #define MAX_PATHNAME 512
23074
23075 /*
23076 ** Only set the lastErrno if the error code is a real error and not 
23077 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
23078 */
23079 #define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
23080
23081 /* Forward references */
23082 typedef struct unixShm unixShm;               /* Connection shared memory */
23083 typedef struct unixShmNode unixShmNode;       /* Shared memory instance */
23084 typedef struct unixInodeInfo unixInodeInfo;   /* An i-node */
23085 typedef struct UnixUnusedFd UnixUnusedFd;     /* An unused file descriptor */
23086
23087 /*
23088 ** Sometimes, after a file handle is closed by SQLite, the file descriptor
23089 ** cannot be closed immediately. In these cases, instances of the following
23090 ** structure are used to store the file descriptor while waiting for an
23091 ** opportunity to either close or reuse it.
23092 */
23093 struct UnixUnusedFd {
23094   int fd;                   /* File descriptor to close */
23095   int flags;                /* Flags this file descriptor was opened with */
23096   UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
23097 };
23098
23099 /*
23100 ** The unixFile structure is subclass of sqlite3_file specific to the unix
23101 ** VFS implementations.
23102 */
23103 typedef struct unixFile unixFile;
23104 struct unixFile {
23105   sqlite3_io_methods const *pMethod;  /* Always the first entry */
23106   sqlite3_vfs *pVfs;                  /* The VFS that created this unixFile */
23107   unixInodeInfo *pInode;              /* Info about locks on this inode */
23108   int h;                              /* The file descriptor */
23109   unsigned char eFileLock;            /* The type of lock held on this fd */
23110   unsigned short int ctrlFlags;       /* Behavioral bits.  UNIXFILE_* flags */
23111   int lastErrno;                      /* The unix errno from last I/O error */
23112   void *lockingContext;               /* Locking style specific state */
23113   UnixUnusedFd *pUnused;              /* Pre-allocated UnixUnusedFd */
23114   const char *zPath;                  /* Name of the file */
23115   unixShm *pShm;                      /* Shared memory segment information */
23116   int szChunk;                        /* Configured by FCNTL_CHUNK_SIZE */
23117   int nFetchOut;                      /* Number of outstanding xFetch refs */
23118   sqlite3_int64 mmapSize;             /* Usable size of mapping at pMapRegion */
23119   sqlite3_int64 mmapSizeActual;       /* Actual size of mapping at pMapRegion */
23120   sqlite3_int64 mmapSizeMax;          /* Configured FCNTL_MMAP_SIZE value */
23121   void *pMapRegion;                   /* Memory mapped region */
23122 #ifdef __QNXNTO__
23123   int sectorSize;                     /* Device sector size */
23124   int deviceCharacteristics;          /* Precomputed device characteristics */
23125 #endif
23126 #if SQLITE_ENABLE_LOCKING_STYLE
23127   int openFlags;                      /* The flags specified at open() */
23128 #endif
23129 #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
23130   unsigned fsFlags;                   /* cached details from statfs() */
23131 #endif
23132 #if OS_VXWORKS
23133   struct vxworksFileId *pId;          /* Unique file ID */
23134 #endif
23135 #ifdef SQLITE_DEBUG
23136   /* The next group of variables are used to track whether or not the
23137   ** transaction counter in bytes 24-27 of database files are updated
23138   ** whenever any part of the database changes.  An assertion fault will
23139   ** occur if a file is updated without also updating the transaction
23140   ** counter.  This test is made to avoid new problems similar to the
23141   ** one described by ticket #3584. 
23142   */
23143   unsigned char transCntrChng;   /* True if the transaction counter changed */
23144   unsigned char dbUpdate;        /* True if any part of database file changed */
23145   unsigned char inNormalWrite;   /* True if in a normal write operation */
23146
23147 #endif
23148
23149 #ifdef SQLITE_TEST
23150   /* In test mode, increase the size of this structure a bit so that 
23151   ** it is larger than the struct CrashFile defined in test6.c.
23152   */
23153   char aPadding[32];
23154 #endif
23155 };
23156
23157 /*
23158 ** Allowed values for the unixFile.ctrlFlags bitmask:
23159 */
23160 #define UNIXFILE_EXCL        0x01     /* Connections from one process only */
23161 #define UNIXFILE_RDONLY      0x02     /* Connection is read only */
23162 #define UNIXFILE_PERSIST_WAL 0x04     /* Persistent WAL mode */
23163 #ifndef SQLITE_DISABLE_DIRSYNC
23164 # define UNIXFILE_DIRSYNC    0x08     /* Directory sync needed */
23165 #else
23166 # define UNIXFILE_DIRSYNC    0x00
23167 #endif
23168 #define UNIXFILE_PSOW        0x10     /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
23169 #define UNIXFILE_DELETE      0x20     /* Delete on close */
23170 #define UNIXFILE_URI         0x40     /* Filename might have query parameters */
23171 #define UNIXFILE_NOLOCK      0x80     /* Do no file locking */
23172 #define UNIXFILE_WARNED    0x0100     /* verifyDbFile() warnings have been issued */
23173
23174 /*
23175 ** Include code that is common to all os_*.c files
23176 */
23177 /************** Include os_common.h in the middle of os_unix.c ***************/
23178 /************** Begin file os_common.h ***************************************/
23179 /*
23180 ** 2004 May 22
23181 **
23182 ** The author disclaims copyright to this source code.  In place of
23183 ** a legal notice, here is a blessing:
23184 **
23185 **    May you do good and not evil.
23186 **    May you find forgiveness for yourself and forgive others.
23187 **    May you share freely, never taking more than you give.
23188 **
23189 ******************************************************************************
23190 **
23191 ** This file contains macros and a little bit of code that is common to
23192 ** all of the platform-specific files (os_*.c) and is #included into those
23193 ** files.
23194 **
23195 ** This file should be #included by the os_*.c files only.  It is not a
23196 ** general purpose header file.
23197 */
23198 #ifndef _OS_COMMON_H_
23199 #define _OS_COMMON_H_
23200
23201 /*
23202 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
23203 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
23204 ** switch.  The following code should catch this problem at compile-time.
23205 */
23206 #ifdef MEMORY_DEBUG
23207 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
23208 #endif
23209
23210 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
23211 # ifndef SQLITE_DEBUG_OS_TRACE
23212 #   define SQLITE_DEBUG_OS_TRACE 0
23213 # endif
23214   int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
23215 # define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
23216 #else
23217 # define OSTRACE(X)
23218 #endif
23219
23220 /*
23221 ** Macros for performance tracing.  Normally turned off.  Only works
23222 ** on i486 hardware.
23223 */
23224 #ifdef SQLITE_PERFORMANCE_TRACE
23225
23226 /* 
23227 ** hwtime.h contains inline assembler code for implementing 
23228 ** high-performance timing routines.
23229 */
23230 /************** Include hwtime.h in the middle of os_common.h ****************/
23231 /************** Begin file hwtime.h ******************************************/
23232 /*
23233 ** 2008 May 27
23234 **
23235 ** The author disclaims copyright to this source code.  In place of
23236 ** a legal notice, here is a blessing:
23237 **
23238 **    May you do good and not evil.
23239 **    May you find forgiveness for yourself and forgive others.
23240 **    May you share freely, never taking more than you give.
23241 **
23242 ******************************************************************************
23243 **
23244 ** This file contains inline asm code for retrieving "high-performance"
23245 ** counters for x86 class CPUs.
23246 */
23247 #ifndef _HWTIME_H_
23248 #define _HWTIME_H_
23249
23250 /*
23251 ** The following routine only works on pentium-class (or newer) processors.
23252 ** It uses the RDTSC opcode to read the cycle count value out of the
23253 ** processor and returns that value.  This can be used for high-res
23254 ** profiling.
23255 */
23256 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
23257       (defined(i386) || defined(__i386__) || defined(_M_IX86))
23258
23259   #if defined(__GNUC__)
23260
23261   __inline__ sqlite_uint64 sqlite3Hwtime(void){
23262      unsigned int lo, hi;
23263      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
23264      return (sqlite_uint64)hi << 32 | lo;
23265   }
23266
23267   #elif defined(_MSC_VER)
23268
23269   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
23270      __asm {
23271         rdtsc
23272         ret       ; return value at EDX:EAX
23273      }
23274   }
23275
23276   #endif
23277
23278 #elif (defined(__GNUC__) && defined(__x86_64__))
23279
23280   __inline__ sqlite_uint64 sqlite3Hwtime(void){
23281       unsigned long val;
23282       __asm__ __volatile__ ("rdtsc" : "=A" (val));
23283       return val;
23284   }
23285  
23286 #elif (defined(__GNUC__) && defined(__ppc__))
23287
23288   __inline__ sqlite_uint64 sqlite3Hwtime(void){
23289       unsigned long long retval;
23290       unsigned long junk;
23291       __asm__ __volatile__ ("\n\
23292           1:      mftbu   %1\n\
23293                   mftb    %L0\n\
23294                   mftbu   %0\n\
23295                   cmpw    %0,%1\n\
23296                   bne     1b"
23297                   : "=r" (retval), "=r" (junk));
23298       return retval;
23299   }
23300
23301 #else
23302
23303   #error Need implementation of sqlite3Hwtime() for your platform.
23304
23305   /*
23306   ** To compile without implementing sqlite3Hwtime() for your platform,
23307   ** you can remove the above #error and use the following
23308   ** stub function.  You will lose timing support for many
23309   ** of the debugging and testing utilities, but it should at
23310   ** least compile and run.
23311   */
23312 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
23313
23314 #endif
23315
23316 #endif /* !defined(_HWTIME_H_) */
23317
23318 /************** End of hwtime.h **********************************************/
23319 /************** Continuing where we left off in os_common.h ******************/
23320
23321 static sqlite_uint64 g_start;
23322 static sqlite_uint64 g_elapsed;
23323 #define TIMER_START       g_start=sqlite3Hwtime()
23324 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
23325 #define TIMER_ELAPSED     g_elapsed
23326 #else
23327 #define TIMER_START
23328 #define TIMER_END
23329 #define TIMER_ELAPSED     ((sqlite_uint64)0)
23330 #endif
23331
23332 /*
23333 ** If we compile with the SQLITE_TEST macro set, then the following block
23334 ** of code will give us the ability to simulate a disk I/O error.  This
23335 ** is used for testing the I/O recovery logic.
23336 */
23337 #ifdef SQLITE_TEST
23338 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
23339 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
23340 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
23341 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
23342 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
23343 SQLITE_API int sqlite3_diskfull_pending = 0;
23344 SQLITE_API int sqlite3_diskfull = 0;
23345 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
23346 #define SimulateIOError(CODE)  \
23347   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
23348        || sqlite3_io_error_pending-- == 1 )  \
23349               { local_ioerr(); CODE; }
23350 static void local_ioerr(){
23351   IOTRACE(("IOERR\n"));
23352   sqlite3_io_error_hit++;
23353   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
23354 }
23355 #define SimulateDiskfullError(CODE) \
23356    if( sqlite3_diskfull_pending ){ \
23357      if( sqlite3_diskfull_pending == 1 ){ \
23358        local_ioerr(); \
23359        sqlite3_diskfull = 1; \
23360        sqlite3_io_error_hit = 1; \
23361        CODE; \
23362      }else{ \
23363        sqlite3_diskfull_pending--; \
23364      } \
23365    }
23366 #else
23367 #define SimulateIOErrorBenign(X)
23368 #define SimulateIOError(A)
23369 #define SimulateDiskfullError(A)
23370 #endif
23371
23372 /*
23373 ** When testing, keep a count of the number of open files.
23374 */
23375 #ifdef SQLITE_TEST
23376 SQLITE_API int sqlite3_open_file_count = 0;
23377 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
23378 #else
23379 #define OpenCounter(X)
23380 #endif
23381
23382 #endif /* !defined(_OS_COMMON_H_) */
23383
23384 /************** End of os_common.h *******************************************/
23385 /************** Continuing where we left off in os_unix.c ********************/
23386
23387 /*
23388 ** Define various macros that are missing from some systems.
23389 */
23390 #ifndef O_LARGEFILE
23391 # define O_LARGEFILE 0
23392 #endif
23393 #ifdef SQLITE_DISABLE_LFS
23394 # undef O_LARGEFILE
23395 # define O_LARGEFILE 0
23396 #endif
23397 #ifndef O_NOFOLLOW
23398 # define O_NOFOLLOW 0
23399 #endif
23400 #ifndef O_BINARY
23401 # define O_BINARY 0
23402 #endif
23403
23404 /*
23405 ** The threadid macro resolves to the thread-id or to 0.  Used for
23406 ** testing and debugging only.
23407 */
23408 #if SQLITE_THREADSAFE
23409 #define threadid pthread_self()
23410 #else
23411 #define threadid 0
23412 #endif
23413
23414 /*
23415 ** HAVE_MREMAP defaults to true on Linux and false everywhere else.
23416 */
23417 #if !defined(HAVE_MREMAP)
23418 # if defined(__linux__) && defined(_GNU_SOURCE)
23419 #  define HAVE_MREMAP 1
23420 # else
23421 #  define HAVE_MREMAP 0
23422 # endif
23423 #endif
23424
23425 /*
23426 ** Different Unix systems declare open() in different ways.  Same use
23427 ** open(const char*,int,mode_t).  Others use open(const char*,int,...).
23428 ** The difference is important when using a pointer to the function.
23429 **
23430 ** The safest way to deal with the problem is to always use this wrapper
23431 ** which always has the same well-defined interface.
23432 */
23433 static int posixOpen(const char *zFile, int flags, int mode){
23434   return open(zFile, flags, mode);
23435 }
23436
23437 /*
23438 ** On some systems, calls to fchown() will trigger a message in a security
23439 ** log if they come from non-root processes.  So avoid calling fchown() if
23440 ** we are not running as root.
23441 */
23442 static int posixFchown(int fd, uid_t uid, gid_t gid){
23443   return geteuid() ? 0 : fchown(fd,uid,gid);
23444 }
23445
23446 /* Forward reference */
23447 static int openDirectory(const char*, int*);
23448
23449 /*
23450 ** Many system calls are accessed through pointer-to-functions so that
23451 ** they may be overridden at runtime to facilitate fault injection during
23452 ** testing and sandboxing.  The following array holds the names and pointers
23453 ** to all overrideable system calls.
23454 */
23455 static struct unix_syscall {
23456   const char *zName;            /* Name of the system call */
23457   sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
23458   sqlite3_syscall_ptr pDefault; /* Default value */
23459 } aSyscall[] = {
23460   { "open",         (sqlite3_syscall_ptr)posixOpen,  0  },
23461 #define osOpen      ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
23462
23463   { "close",        (sqlite3_syscall_ptr)close,      0  },
23464 #define osClose     ((int(*)(int))aSyscall[1].pCurrent)
23465
23466   { "access",       (sqlite3_syscall_ptr)access,     0  },
23467 #define osAccess    ((int(*)(const char*,int))aSyscall[2].pCurrent)
23468
23469   { "getcwd",       (sqlite3_syscall_ptr)getcwd,     0  },
23470 #define osGetcwd    ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
23471
23472   { "stat",         (sqlite3_syscall_ptr)stat,       0  },
23473 #define osStat      ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
23474
23475 /*
23476 ** The DJGPP compiler environment looks mostly like Unix, but it
23477 ** lacks the fcntl() system call.  So redefine fcntl() to be something
23478 ** that always succeeds.  This means that locking does not occur under
23479 ** DJGPP.  But it is DOS - what did you expect?
23480 */
23481 #ifdef __DJGPP__
23482   { "fstat",        0,                 0  },
23483 #define osFstat(a,b,c)    0
23484 #else     
23485   { "fstat",        (sqlite3_syscall_ptr)fstat,      0  },
23486 #define osFstat     ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
23487 #endif
23488
23489   { "ftruncate",    (sqlite3_syscall_ptr)ftruncate,  0  },
23490 #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
23491
23492   { "fcntl",        (sqlite3_syscall_ptr)fcntl,      0  },
23493 #define osFcntl     ((int(*)(int,int,...))aSyscall[7].pCurrent)
23494
23495   { "read",         (sqlite3_syscall_ptr)read,       0  },
23496 #define osRead      ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
23497
23498 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
23499   { "pread",        (sqlite3_syscall_ptr)pread,      0  },
23500 #else
23501   { "pread",        (sqlite3_syscall_ptr)0,          0  },
23502 #endif
23503 #define osPread     ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
23504
23505 #if defined(USE_PREAD64)
23506   { "pread64",      (sqlite3_syscall_ptr)pread64,    0  },
23507 #else
23508   { "pread64",      (sqlite3_syscall_ptr)0,          0  },
23509 #endif
23510 #define osPread64   ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
23511
23512   { "write",        (sqlite3_syscall_ptr)write,      0  },
23513 #define osWrite     ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
23514
23515 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
23516   { "pwrite",       (sqlite3_syscall_ptr)pwrite,     0  },
23517 #else
23518   { "pwrite",       (sqlite3_syscall_ptr)0,          0  },
23519 #endif
23520 #define osPwrite    ((ssize_t(*)(int,const void*,size_t,off_t))\
23521                     aSyscall[12].pCurrent)
23522
23523 #if defined(USE_PREAD64)
23524   { "pwrite64",     (sqlite3_syscall_ptr)pwrite64,   0  },
23525 #else
23526   { "pwrite64",     (sqlite3_syscall_ptr)0,          0  },
23527 #endif
23528 #define osPwrite64  ((ssize_t(*)(int,const void*,size_t,off_t))\
23529                     aSyscall[13].pCurrent)
23530
23531   { "fchmod",       (sqlite3_syscall_ptr)fchmod,     0  },
23532 #define osFchmod    ((int(*)(int,mode_t))aSyscall[14].pCurrent)
23533
23534 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
23535   { "fallocate",    (sqlite3_syscall_ptr)posix_fallocate,  0 },
23536 #else
23537   { "fallocate",    (sqlite3_syscall_ptr)0,                0 },
23538 #endif
23539 #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
23540
23541   { "unlink",       (sqlite3_syscall_ptr)unlink,           0 },
23542 #define osUnlink    ((int(*)(const char*))aSyscall[16].pCurrent)
23543
23544   { "openDirectory",    (sqlite3_syscall_ptr)openDirectory,      0 },
23545 #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
23546
23547   { "mkdir",        (sqlite3_syscall_ptr)mkdir,           0 },
23548 #define osMkdir     ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
23549
23550   { "rmdir",        (sqlite3_syscall_ptr)rmdir,           0 },
23551 #define osRmdir     ((int(*)(const char*))aSyscall[19].pCurrent)
23552
23553   { "fchown",       (sqlite3_syscall_ptr)posixFchown,     0 },
23554 #define osFchown    ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
23555
23556   { "mmap",       (sqlite3_syscall_ptr)mmap,     0 },
23557 #define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[21].pCurrent)
23558
23559   { "munmap",       (sqlite3_syscall_ptr)munmap,          0 },
23560 #define osMunmap ((void*(*)(void*,size_t))aSyscall[22].pCurrent)
23561
23562 #if HAVE_MREMAP
23563   { "mremap",       (sqlite3_syscall_ptr)mremap,          0 },
23564 #else
23565   { "mremap",       (sqlite3_syscall_ptr)0,               0 },
23566 #endif
23567 #define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[23].pCurrent)
23568
23569 }; /* End of the overrideable system calls */
23570
23571 /*
23572 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
23573 ** "unix" VFSes.  Return SQLITE_OK opon successfully updating the
23574 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
23575 ** system call named zName.
23576 */
23577 static int unixSetSystemCall(
23578   sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
23579   const char *zName,            /* Name of system call to override */
23580   sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
23581 ){
23582   unsigned int i;
23583   int rc = SQLITE_NOTFOUND;
23584
23585   UNUSED_PARAMETER(pNotUsed);
23586   if( zName==0 ){
23587     /* If no zName is given, restore all system calls to their default
23588     ** settings and return NULL
23589     */
23590     rc = SQLITE_OK;
23591     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
23592       if( aSyscall[i].pDefault ){
23593         aSyscall[i].pCurrent = aSyscall[i].pDefault;
23594       }
23595     }
23596   }else{
23597     /* If zName is specified, operate on only the one system call
23598     ** specified.
23599     */
23600     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
23601       if( strcmp(zName, aSyscall[i].zName)==0 ){
23602         if( aSyscall[i].pDefault==0 ){
23603           aSyscall[i].pDefault = aSyscall[i].pCurrent;
23604         }
23605         rc = SQLITE_OK;
23606         if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
23607         aSyscall[i].pCurrent = pNewFunc;
23608         break;
23609       }
23610     }
23611   }
23612   return rc;
23613 }
23614
23615 /*
23616 ** Return the value of a system call.  Return NULL if zName is not a
23617 ** recognized system call name.  NULL is also returned if the system call
23618 ** is currently undefined.
23619 */
23620 static sqlite3_syscall_ptr unixGetSystemCall(
23621   sqlite3_vfs *pNotUsed,
23622   const char *zName
23623 ){
23624   unsigned int i;
23625
23626   UNUSED_PARAMETER(pNotUsed);
23627   for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
23628     if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
23629   }
23630   return 0;
23631 }
23632
23633 /*
23634 ** Return the name of the first system call after zName.  If zName==NULL
23635 ** then return the name of the first system call.  Return NULL if zName
23636 ** is the last system call or if zName is not the name of a valid
23637 ** system call.
23638 */
23639 static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
23640   int i = -1;
23641
23642   UNUSED_PARAMETER(p);
23643   if( zName ){
23644     for(i=0; i<ArraySize(aSyscall)-1; i++){
23645       if( strcmp(zName, aSyscall[i].zName)==0 ) break;
23646     }
23647   }
23648   for(i++; i<ArraySize(aSyscall); i++){
23649     if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
23650   }
23651   return 0;
23652 }
23653
23654 /*
23655 ** Invoke open().  Do so multiple times, until it either succeeds or
23656 ** fails for some reason other than EINTR.
23657 **
23658 ** If the file creation mode "m" is 0 then set it to the default for
23659 ** SQLite.  The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
23660 ** 0644) as modified by the system umask.  If m is not 0, then
23661 ** make the file creation mode be exactly m ignoring the umask.
23662 **
23663 ** The m parameter will be non-zero only when creating -wal, -journal,
23664 ** and -shm files.  We want those files to have *exactly* the same
23665 ** permissions as their original database, unadulterated by the umask.
23666 ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
23667 ** transaction crashes and leaves behind hot journals, then any
23668 ** process that is able to write to the database will also be able to
23669 ** recover the hot journals.
23670 */
23671 static int robust_open(const char *z, int f, mode_t m){
23672   int fd;
23673   mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
23674   do{
23675 #if defined(O_CLOEXEC)
23676     fd = osOpen(z,f|O_CLOEXEC,m2);
23677 #else
23678     fd = osOpen(z,f,m2);
23679 #endif
23680   }while( fd<0 && errno==EINTR );
23681   if( fd>=0 ){
23682     if( m!=0 ){
23683       struct stat statbuf;
23684       if( osFstat(fd, &statbuf)==0 
23685        && statbuf.st_size==0
23686        && (statbuf.st_mode&0777)!=m 
23687       ){
23688         osFchmod(fd, m);
23689       }
23690     }
23691 #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
23692     osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
23693 #endif
23694   }
23695   return fd;
23696 }
23697
23698 /*
23699 ** Helper functions to obtain and relinquish the global mutex. The
23700 ** global mutex is used to protect the unixInodeInfo and
23701 ** vxworksFileId objects used by this file, all of which may be 
23702 ** shared by multiple threads.
23703 **
23704 ** Function unixMutexHeld() is used to assert() that the global mutex 
23705 ** is held when required. This function is only used as part of assert() 
23706 ** statements. e.g.
23707 **
23708 **   unixEnterMutex()
23709 **     assert( unixMutexHeld() );
23710 **   unixEnterLeave()
23711 */
23712 static void unixEnterMutex(void){
23713   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
23714 }
23715 static void unixLeaveMutex(void){
23716   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
23717 }
23718 #ifdef SQLITE_DEBUG
23719 static int unixMutexHeld(void) {
23720   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
23721 }
23722 #endif
23723
23724
23725 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
23726 /*
23727 ** Helper function for printing out trace information from debugging
23728 ** binaries. This returns the string represetation of the supplied
23729 ** integer lock-type.
23730 */
23731 static const char *azFileLock(int eFileLock){
23732   switch( eFileLock ){
23733     case NO_LOCK: return "NONE";
23734     case SHARED_LOCK: return "SHARED";
23735     case RESERVED_LOCK: return "RESERVED";
23736     case PENDING_LOCK: return "PENDING";
23737     case EXCLUSIVE_LOCK: return "EXCLUSIVE";
23738   }
23739   return "ERROR";
23740 }
23741 #endif
23742
23743 #ifdef SQLITE_LOCK_TRACE
23744 /*
23745 ** Print out information about all locking operations.
23746 **
23747 ** This routine is used for troubleshooting locks on multithreaded
23748 ** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
23749 ** command-line option on the compiler.  This code is normally
23750 ** turned off.
23751 */
23752 static int lockTrace(int fd, int op, struct flock *p){
23753   char *zOpName, *zType;
23754   int s;
23755   int savedErrno;
23756   if( op==F_GETLK ){
23757     zOpName = "GETLK";
23758   }else if( op==F_SETLK ){
23759     zOpName = "SETLK";
23760   }else{
23761     s = osFcntl(fd, op, p);
23762     sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
23763     return s;
23764   }
23765   if( p->l_type==F_RDLCK ){
23766     zType = "RDLCK";
23767   }else if( p->l_type==F_WRLCK ){
23768     zType = "WRLCK";
23769   }else if( p->l_type==F_UNLCK ){
23770     zType = "UNLCK";
23771   }else{
23772     assert( 0 );
23773   }
23774   assert( p->l_whence==SEEK_SET );
23775   s = osFcntl(fd, op, p);
23776   savedErrno = errno;
23777   sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
23778      threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
23779      (int)p->l_pid, s);
23780   if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
23781     struct flock l2;
23782     l2 = *p;
23783     osFcntl(fd, F_GETLK, &l2);
23784     if( l2.l_type==F_RDLCK ){
23785       zType = "RDLCK";
23786     }else if( l2.l_type==F_WRLCK ){
23787       zType = "WRLCK";
23788     }else if( l2.l_type==F_UNLCK ){
23789       zType = "UNLCK";
23790     }else{
23791       assert( 0 );
23792     }
23793     sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
23794        zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
23795   }
23796   errno = savedErrno;
23797   return s;
23798 }
23799 #undef osFcntl
23800 #define osFcntl lockTrace
23801 #endif /* SQLITE_LOCK_TRACE */
23802
23803 /*
23804 ** Retry ftruncate() calls that fail due to EINTR
23805 */
23806 static int robust_ftruncate(int h, sqlite3_int64 sz){
23807   int rc;
23808   do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
23809   return rc;
23810 }
23811
23812 /*
23813 ** This routine translates a standard POSIX errno code into something
23814 ** useful to the clients of the sqlite3 functions.  Specifically, it is
23815 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
23816 ** and a variety of "please close the file descriptor NOW" errors into 
23817 ** SQLITE_IOERR
23818 ** 
23819 ** Errors during initialization of locks, or file system support for locks,
23820 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
23821 */
23822 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
23823   switch (posixError) {
23824 #if 0
23825   /* At one point this code was not commented out. In theory, this branch
23826   ** should never be hit, as this function should only be called after
23827   ** a locking-related function (i.e. fcntl()) has returned non-zero with
23828   ** the value of errno as the first argument. Since a system call has failed,
23829   ** errno should be non-zero.
23830   **
23831   ** Despite this, if errno really is zero, we still don't want to return
23832   ** SQLITE_OK. The system call failed, and *some* SQLite error should be
23833   ** propagated back to the caller. Commenting this branch out means errno==0
23834   ** will be handled by the "default:" case below.
23835   */
23836   case 0: 
23837     return SQLITE_OK;
23838 #endif
23839
23840   case EAGAIN:
23841   case ETIMEDOUT:
23842   case EBUSY:
23843   case EINTR:
23844   case ENOLCK:  
23845     /* random NFS retry error, unless during file system support 
23846      * introspection, in which it actually means what it says */
23847     return SQLITE_BUSY;
23848     
23849   case EACCES: 
23850     /* EACCES is like EAGAIN during locking operations, but not any other time*/
23851     if( (sqliteIOErr == SQLITE_IOERR_LOCK) || 
23852         (sqliteIOErr == SQLITE_IOERR_UNLOCK) || 
23853         (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
23854         (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
23855       return SQLITE_BUSY;
23856     }
23857     /* else fall through */
23858   case EPERM: 
23859     return SQLITE_PERM;
23860     
23861   /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
23862   ** this module never makes such a call. And the code in SQLite itself 
23863   ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
23864   ** this case is also commented out. If the system does set errno to EDEADLK,
23865   ** the default SQLITE_IOERR_XXX code will be returned. */
23866 #if 0
23867   case EDEADLK:
23868     return SQLITE_IOERR_BLOCKED;
23869 #endif
23870     
23871 #if EOPNOTSUPP!=ENOTSUP
23872   case EOPNOTSUPP: 
23873     /* something went terribly awry, unless during file system support 
23874      * introspection, in which it actually means what it says */
23875 #endif
23876 #ifdef ENOTSUP
23877   case ENOTSUP: 
23878     /* invalid fd, unless during file system support introspection, in which 
23879      * it actually means what it says */
23880 #endif
23881   case EIO:
23882   case EBADF:
23883   case EINVAL:
23884   case ENOTCONN:
23885   case ENODEV:
23886   case ENXIO:
23887   case ENOENT:
23888 #ifdef ESTALE                     /* ESTALE is not defined on Interix systems */
23889   case ESTALE:
23890 #endif
23891   case ENOSYS:
23892     /* these should force the client to close the file and reconnect */
23893     
23894   default: 
23895     return sqliteIOErr;
23896   }
23897 }
23898
23899
23900 /******************************************************************************
23901 ****************** Begin Unique File ID Utility Used By VxWorks ***************
23902 **
23903 ** On most versions of unix, we can get a unique ID for a file by concatenating
23904 ** the device number and the inode number.  But this does not work on VxWorks.
23905 ** On VxWorks, a unique file id must be based on the canonical filename.
23906 **
23907 ** A pointer to an instance of the following structure can be used as a
23908 ** unique file ID in VxWorks.  Each instance of this structure contains
23909 ** a copy of the canonical filename.  There is also a reference count.  
23910 ** The structure is reclaimed when the number of pointers to it drops to
23911 ** zero.
23912 **
23913 ** There are never very many files open at one time and lookups are not
23914 ** a performance-critical path, so it is sufficient to put these
23915 ** structures on a linked list.
23916 */
23917 struct vxworksFileId {
23918   struct vxworksFileId *pNext;  /* Next in a list of them all */
23919   int nRef;                     /* Number of references to this one */
23920   int nName;                    /* Length of the zCanonicalName[] string */
23921   char *zCanonicalName;         /* Canonical filename */
23922 };
23923
23924 #if OS_VXWORKS
23925 /* 
23926 ** All unique filenames are held on a linked list headed by this
23927 ** variable:
23928 */
23929 static struct vxworksFileId *vxworksFileList = 0;
23930
23931 /*
23932 ** Simplify a filename into its canonical form
23933 ** by making the following changes:
23934 **
23935 **  * removing any trailing and duplicate /
23936 **  * convert /./ into just /
23937 **  * convert /A/../ where A is any simple name into just /
23938 **
23939 ** Changes are made in-place.  Return the new name length.
23940 **
23941 ** The original filename is in z[0..n-1].  Return the number of
23942 ** characters in the simplified name.
23943 */
23944 static int vxworksSimplifyName(char *z, int n){
23945   int i, j;
23946   while( n>1 && z[n-1]=='/' ){ n--; }
23947   for(i=j=0; i<n; i++){
23948     if( z[i]=='/' ){
23949       if( z[i+1]=='/' ) continue;
23950       if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
23951         i += 1;
23952         continue;
23953       }
23954       if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
23955         while( j>0 && z[j-1]!='/' ){ j--; }
23956         if( j>0 ){ j--; }
23957         i += 2;
23958         continue;
23959       }
23960     }
23961     z[j++] = z[i];
23962   }
23963   z[j] = 0;
23964   return j;
23965 }
23966
23967 /*
23968 ** Find a unique file ID for the given absolute pathname.  Return
23969 ** a pointer to the vxworksFileId object.  This pointer is the unique
23970 ** file ID.
23971 **
23972 ** The nRef field of the vxworksFileId object is incremented before
23973 ** the object is returned.  A new vxworksFileId object is created
23974 ** and added to the global list if necessary.
23975 **
23976 ** If a memory allocation error occurs, return NULL.
23977 */
23978 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
23979   struct vxworksFileId *pNew;         /* search key and new file ID */
23980   struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
23981   int n;                              /* Length of zAbsoluteName string */
23982
23983   assert( zAbsoluteName[0]=='/' );
23984   n = (int)strlen(zAbsoluteName);
23985   pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
23986   if( pNew==0 ) return 0;
23987   pNew->zCanonicalName = (char*)&pNew[1];
23988   memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
23989   n = vxworksSimplifyName(pNew->zCanonicalName, n);
23990
23991   /* Search for an existing entry that matching the canonical name.
23992   ** If found, increment the reference count and return a pointer to
23993   ** the existing file ID.
23994   */
23995   unixEnterMutex();
23996   for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
23997     if( pCandidate->nName==n 
23998      && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
23999     ){
24000        sqlite3_free(pNew);
24001        pCandidate->nRef++;
24002        unixLeaveMutex();
24003        return pCandidate;
24004     }
24005   }
24006
24007   /* No match was found.  We will make a new file ID */
24008   pNew->nRef = 1;
24009   pNew->nName = n;
24010   pNew->pNext = vxworksFileList;
24011   vxworksFileList = pNew;
24012   unixLeaveMutex();
24013   return pNew;
24014 }
24015
24016 /*
24017 ** Decrement the reference count on a vxworksFileId object.  Free
24018 ** the object when the reference count reaches zero.
24019 */
24020 static void vxworksReleaseFileId(struct vxworksFileId *pId){
24021   unixEnterMutex();
24022   assert( pId->nRef>0 );
24023   pId->nRef--;
24024   if( pId->nRef==0 ){
24025     struct vxworksFileId **pp;
24026     for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
24027     assert( *pp==pId );
24028     *pp = pId->pNext;
24029     sqlite3_free(pId);
24030   }
24031   unixLeaveMutex();
24032 }
24033 #endif /* OS_VXWORKS */
24034 /*************** End of Unique File ID Utility Used By VxWorks ****************
24035 ******************************************************************************/
24036
24037
24038 /******************************************************************************
24039 *************************** Posix Advisory Locking ****************************
24040 **
24041 ** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
24042 ** section 6.5.2.2 lines 483 through 490 specify that when a process
24043 ** sets or clears a lock, that operation overrides any prior locks set
24044 ** by the same process.  It does not explicitly say so, but this implies
24045 ** that it overrides locks set by the same process using a different
24046 ** file descriptor.  Consider this test case:
24047 **
24048 **       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
24049 **       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
24050 **
24051 ** Suppose ./file1 and ./file2 are really the same file (because
24052 ** one is a hard or symbolic link to the other) then if you set
24053 ** an exclusive lock on fd1, then try to get an exclusive lock
24054 ** on fd2, it works.  I would have expected the second lock to
24055 ** fail since there was already a lock on the file due to fd1.
24056 ** But not so.  Since both locks came from the same process, the
24057 ** second overrides the first, even though they were on different
24058 ** file descriptors opened on different file names.
24059 **
24060 ** This means that we cannot use POSIX locks to synchronize file access
24061 ** among competing threads of the same process.  POSIX locks will work fine
24062 ** to synchronize access for threads in separate processes, but not
24063 ** threads within the same process.
24064 **
24065 ** To work around the problem, SQLite has to manage file locks internally
24066 ** on its own.  Whenever a new database is opened, we have to find the
24067 ** specific inode of the database file (the inode is determined by the
24068 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
24069 ** and check for locks already existing on that inode.  When locks are
24070 ** created or removed, we have to look at our own internal record of the
24071 ** locks to see if another thread has previously set a lock on that same
24072 ** inode.
24073 **
24074 ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
24075 ** For VxWorks, we have to use the alternative unique ID system based on
24076 ** canonical filename and implemented in the previous division.)
24077 **
24078 ** The sqlite3_file structure for POSIX is no longer just an integer file
24079 ** descriptor.  It is now a structure that holds the integer file
24080 ** descriptor and a pointer to a structure that describes the internal
24081 ** locks on the corresponding inode.  There is one locking structure
24082 ** per inode, so if the same inode is opened twice, both unixFile structures
24083 ** point to the same locking structure.  The locking structure keeps
24084 ** a reference count (so we will know when to delete it) and a "cnt"
24085 ** field that tells us its internal lock status.  cnt==0 means the
24086 ** file is unlocked.  cnt==-1 means the file has an exclusive lock.
24087 ** cnt>0 means there are cnt shared locks on the file.
24088 **
24089 ** Any attempt to lock or unlock a file first checks the locking
24090 ** structure.  The fcntl() system call is only invoked to set a 
24091 ** POSIX lock if the internal lock structure transitions between
24092 ** a locked and an unlocked state.
24093 **
24094 ** But wait:  there are yet more problems with POSIX advisory locks.
24095 **
24096 ** If you close a file descriptor that points to a file that has locks,
24097 ** all locks on that file that are owned by the current process are
24098 ** released.  To work around this problem, each unixInodeInfo object
24099 ** maintains a count of the number of pending locks on tha inode.
24100 ** When an attempt is made to close an unixFile, if there are
24101 ** other unixFile open on the same inode that are holding locks, the call
24102 ** to close() the file descriptor is deferred until all of the locks clear.
24103 ** The unixInodeInfo structure keeps a list of file descriptors that need to
24104 ** be closed and that list is walked (and cleared) when the last lock
24105 ** clears.
24106 **
24107 ** Yet another problem:  LinuxThreads do not play well with posix locks.
24108 **
24109 ** Many older versions of linux use the LinuxThreads library which is
24110 ** not posix compliant.  Under LinuxThreads, a lock created by thread
24111 ** A cannot be modified or overridden by a different thread B.
24112 ** Only thread A can modify the lock.  Locking behavior is correct
24113 ** if the appliation uses the newer Native Posix Thread Library (NPTL)
24114 ** on linux - with NPTL a lock created by thread A can override locks
24115 ** in thread B.  But there is no way to know at compile-time which
24116 ** threading library is being used.  So there is no way to know at
24117 ** compile-time whether or not thread A can override locks on thread B.
24118 ** One has to do a run-time check to discover the behavior of the
24119 ** current process.
24120 **
24121 ** SQLite used to support LinuxThreads.  But support for LinuxThreads
24122 ** was dropped beginning with version 3.7.0.  SQLite will still work with
24123 ** LinuxThreads provided that (1) there is no more than one connection 
24124 ** per database file in the same process and (2) database connections
24125 ** do not move across threads.
24126 */
24127
24128 /*
24129 ** An instance of the following structure serves as the key used
24130 ** to locate a particular unixInodeInfo object.
24131 */
24132 struct unixFileId {
24133   dev_t dev;                  /* Device number */
24134 #if OS_VXWORKS
24135   struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
24136 #else
24137   ino_t ino;                  /* Inode number */
24138 #endif
24139 };
24140
24141 /*
24142 ** An instance of the following structure is allocated for each open
24143 ** inode.  Or, on LinuxThreads, there is one of these structures for
24144 ** each inode opened by each thread.
24145 **
24146 ** A single inode can have multiple file descriptors, so each unixFile
24147 ** structure contains a pointer to an instance of this object and this
24148 ** object keeps a count of the number of unixFile pointing to it.
24149 */
24150 struct unixInodeInfo {
24151   struct unixFileId fileId;       /* The lookup key */
24152   int nShared;                    /* Number of SHARED locks held */
24153   unsigned char eFileLock;        /* One of SHARED_LOCK, RESERVED_LOCK etc. */
24154   unsigned char bProcessLock;     /* An exclusive process lock is held */
24155   int nRef;                       /* Number of pointers to this structure */
24156   unixShmNode *pShmNode;          /* Shared memory associated with this inode */
24157   int nLock;                      /* Number of outstanding file locks */
24158   UnixUnusedFd *pUnused;          /* Unused file descriptors to close */
24159   unixInodeInfo *pNext;           /* List of all unixInodeInfo objects */
24160   unixInodeInfo *pPrev;           /*    .... doubly linked */
24161 #if SQLITE_ENABLE_LOCKING_STYLE
24162   unsigned long long sharedByte;  /* for AFP simulated shared lock */
24163 #endif
24164 #if OS_VXWORKS
24165   sem_t *pSem;                    /* Named POSIX semaphore */
24166   char aSemName[MAX_PATHNAME+2];  /* Name of that semaphore */
24167 #endif
24168 };
24169
24170 /*
24171 ** A lists of all unixInodeInfo objects.
24172 */
24173 static unixInodeInfo *inodeList = 0;
24174
24175 /*
24176 **
24177 ** This function - unixLogError_x(), is only ever called via the macro
24178 ** unixLogError().
24179 **
24180 ** It is invoked after an error occurs in an OS function and errno has been
24181 ** set. It logs a message using sqlite3_log() containing the current value of
24182 ** errno and, if possible, the human-readable equivalent from strerror() or
24183 ** strerror_r().
24184 **
24185 ** The first argument passed to the macro should be the error code that
24186 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN). 
24187 ** The two subsequent arguments should be the name of the OS function that
24188 ** failed (e.g. "unlink", "open") and the associated file-system path,
24189 ** if any.
24190 */
24191 #define unixLogError(a,b,c)     unixLogErrorAtLine(a,b,c,__LINE__)
24192 static int unixLogErrorAtLine(
24193   int errcode,                    /* SQLite error code */
24194   const char *zFunc,              /* Name of OS function that failed */
24195   const char *zPath,              /* File path associated with error */
24196   int iLine                       /* Source line number where error occurred */
24197 ){
24198   char *zErr;                     /* Message from strerror() or equivalent */
24199   int iErrno = errno;             /* Saved syscall error number */
24200
24201   /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
24202   ** the strerror() function to obtain the human-readable error message
24203   ** equivalent to errno. Otherwise, use strerror_r().
24204   */ 
24205 #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
24206   char aErr[80];
24207   memset(aErr, 0, sizeof(aErr));
24208   zErr = aErr;
24209
24210   /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
24211   ** assume that the system provides the GNU version of strerror_r() that
24212   ** returns a pointer to a buffer containing the error message. That pointer 
24213   ** may point to aErr[], or it may point to some static storage somewhere. 
24214   ** Otherwise, assume that the system provides the POSIX version of 
24215   ** strerror_r(), which always writes an error message into aErr[].
24216   **
24217   ** If the code incorrectly assumes that it is the POSIX version that is
24218   ** available, the error message will often be an empty string. Not a
24219   ** huge problem. Incorrectly concluding that the GNU version is available 
24220   ** could lead to a segfault though.
24221   */
24222 #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
24223   zErr = 
24224 # endif
24225   strerror_r(iErrno, aErr, sizeof(aErr)-1);
24226
24227 #elif SQLITE_THREADSAFE
24228   /* This is a threadsafe build, but strerror_r() is not available. */
24229   zErr = "";
24230 #else
24231   /* Non-threadsafe build, use strerror(). */
24232   zErr = strerror(iErrno);
24233 #endif
24234
24235   if( zPath==0 ) zPath = "";
24236   sqlite3_log(errcode,
24237       "os_unix.c:%d: (%d) %s(%s) - %s",
24238       iLine, iErrno, zFunc, zPath, zErr
24239   );
24240
24241   return errcode;
24242 }
24243
24244 /*
24245 ** Close a file descriptor.
24246 **
24247 ** We assume that close() almost always works, since it is only in a
24248 ** very sick application or on a very sick platform that it might fail.
24249 ** If it does fail, simply leak the file descriptor, but do log the
24250 ** error.
24251 **
24252 ** Note that it is not safe to retry close() after EINTR since the
24253 ** file descriptor might have already been reused by another thread.
24254 ** So we don't even try to recover from an EINTR.  Just log the error
24255 ** and move on.
24256 */
24257 static void robust_close(unixFile *pFile, int h, int lineno){
24258   if( osClose(h) ){
24259     unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
24260                        pFile ? pFile->zPath : 0, lineno);
24261   }
24262 }
24263
24264 /*
24265 ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
24266 */ 
24267 static void closePendingFds(unixFile *pFile){
24268   unixInodeInfo *pInode = pFile->pInode;
24269   UnixUnusedFd *p;
24270   UnixUnusedFd *pNext;
24271   for(p=pInode->pUnused; p; p=pNext){
24272     pNext = p->pNext;
24273     robust_close(pFile, p->fd, __LINE__);
24274     sqlite3_free(p);
24275   }
24276   pInode->pUnused = 0;
24277 }
24278
24279 /*
24280 ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
24281 **
24282 ** The mutex entered using the unixEnterMutex() function must be held
24283 ** when this function is called.
24284 */
24285 static void releaseInodeInfo(unixFile *pFile){
24286   unixInodeInfo *pInode = pFile->pInode;
24287   assert( unixMutexHeld() );
24288   if( ALWAYS(pInode) ){
24289     pInode->nRef--;
24290     if( pInode->nRef==0 ){
24291       assert( pInode->pShmNode==0 );
24292       closePendingFds(pFile);
24293       if( pInode->pPrev ){
24294         assert( pInode->pPrev->pNext==pInode );
24295         pInode->pPrev->pNext = pInode->pNext;
24296       }else{
24297         assert( inodeList==pInode );
24298         inodeList = pInode->pNext;
24299       }
24300       if( pInode->pNext ){
24301         assert( pInode->pNext->pPrev==pInode );
24302         pInode->pNext->pPrev = pInode->pPrev;
24303       }
24304       sqlite3_free(pInode);
24305     }
24306   }
24307 }
24308
24309 /*
24310 ** Given a file descriptor, locate the unixInodeInfo object that
24311 ** describes that file descriptor.  Create a new one if necessary.  The
24312 ** return value might be uninitialized if an error occurs.
24313 **
24314 ** The mutex entered using the unixEnterMutex() function must be held
24315 ** when this function is called.
24316 **
24317 ** Return an appropriate error code.
24318 */
24319 static int findInodeInfo(
24320   unixFile *pFile,               /* Unix file with file desc used in the key */
24321   unixInodeInfo **ppInode        /* Return the unixInodeInfo object here */
24322 ){
24323   int rc;                        /* System call return code */
24324   int fd;                        /* The file descriptor for pFile */
24325   struct unixFileId fileId;      /* Lookup key for the unixInodeInfo */
24326   struct stat statbuf;           /* Low-level file information */
24327   unixInodeInfo *pInode = 0;     /* Candidate unixInodeInfo object */
24328
24329   assert( unixMutexHeld() );
24330
24331   /* Get low-level information about the file that we can used to
24332   ** create a unique name for the file.
24333   */
24334   fd = pFile->h;
24335   rc = osFstat(fd, &statbuf);
24336   if( rc!=0 ){
24337     pFile->lastErrno = errno;
24338 #ifdef EOVERFLOW
24339     if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
24340 #endif
24341     return SQLITE_IOERR;
24342   }
24343
24344 #ifdef __APPLE__
24345   /* On OS X on an msdos filesystem, the inode number is reported
24346   ** incorrectly for zero-size files.  See ticket #3260.  To work
24347   ** around this problem (we consider it a bug in OS X, not SQLite)
24348   ** we always increase the file size to 1 by writing a single byte
24349   ** prior to accessing the inode number.  The one byte written is
24350   ** an ASCII 'S' character which also happens to be the first byte
24351   ** in the header of every SQLite database.  In this way, if there
24352   ** is a race condition such that another thread has already populated
24353   ** the first page of the database, no damage is done.
24354   */
24355   if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
24356     do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
24357     if( rc!=1 ){
24358       pFile->lastErrno = errno;
24359       return SQLITE_IOERR;
24360     }
24361     rc = osFstat(fd, &statbuf);
24362     if( rc!=0 ){
24363       pFile->lastErrno = errno;
24364       return SQLITE_IOERR;
24365     }
24366   }
24367 #endif
24368
24369   memset(&fileId, 0, sizeof(fileId));
24370   fileId.dev = statbuf.st_dev;
24371 #if OS_VXWORKS
24372   fileId.pId = pFile->pId;
24373 #else
24374   fileId.ino = statbuf.st_ino;
24375 #endif
24376   pInode = inodeList;
24377   while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
24378     pInode = pInode->pNext;
24379   }
24380   if( pInode==0 ){
24381     pInode = sqlite3_malloc( sizeof(*pInode) );
24382     if( pInode==0 ){
24383       return SQLITE_NOMEM;
24384     }
24385     memset(pInode, 0, sizeof(*pInode));
24386     memcpy(&pInode->fileId, &fileId, sizeof(fileId));
24387     pInode->nRef = 1;
24388     pInode->pNext = inodeList;
24389     pInode->pPrev = 0;
24390     if( inodeList ) inodeList->pPrev = pInode;
24391     inodeList = pInode;
24392   }else{
24393     pInode->nRef++;
24394   }
24395   *ppInode = pInode;
24396   return SQLITE_OK;
24397 }
24398
24399
24400 /*
24401 ** Check a unixFile that is a database.  Verify the following:
24402 **
24403 ** (1) There is exactly one hard link on the file
24404 ** (2) The file is not a symbolic link
24405 ** (3) The file has not been renamed or unlinked
24406 **
24407 ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
24408 */
24409 static void verifyDbFile(unixFile *pFile){
24410   struct stat buf;
24411   int rc;
24412   if( pFile->ctrlFlags & UNIXFILE_WARNED ){
24413     /* One or more of the following warnings have already been issued.  Do not
24414     ** repeat them so as not to clutter the error log */
24415     return;
24416   }
24417   rc = osFstat(pFile->h, &buf);
24418   if( rc!=0 ){
24419     sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
24420     pFile->ctrlFlags |= UNIXFILE_WARNED;
24421     return;
24422   }
24423   if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
24424     sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
24425     pFile->ctrlFlags |= UNIXFILE_WARNED;
24426     return;
24427   }
24428   if( buf.st_nlink>1 ){
24429     sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
24430     pFile->ctrlFlags |= UNIXFILE_WARNED;
24431     return;
24432   }
24433   if( pFile->pInode!=0
24434    && ((rc = osStat(pFile->zPath, &buf))!=0
24435        || buf.st_ino!=pFile->pInode->fileId.ino)
24436   ){
24437     sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
24438     pFile->ctrlFlags |= UNIXFILE_WARNED;
24439     return;
24440   }
24441 }
24442
24443
24444 /*
24445 ** This routine checks if there is a RESERVED lock held on the specified
24446 ** file by this or any other process. If such a lock is held, set *pResOut
24447 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
24448 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
24449 */
24450 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
24451   int rc = SQLITE_OK;
24452   int reserved = 0;
24453   unixFile *pFile = (unixFile*)id;
24454
24455   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
24456
24457   assert( pFile );
24458   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
24459
24460   /* Check if a thread in this process holds such a lock */
24461   if( pFile->pInode->eFileLock>SHARED_LOCK ){
24462     reserved = 1;
24463   }
24464
24465   /* Otherwise see if some other process holds it.
24466   */
24467 #ifndef __DJGPP__
24468   if( !reserved && !pFile->pInode->bProcessLock ){
24469     struct flock lock;
24470     lock.l_whence = SEEK_SET;
24471     lock.l_start = RESERVED_BYTE;
24472     lock.l_len = 1;
24473     lock.l_type = F_WRLCK;
24474     if( osFcntl(pFile->h, F_GETLK, &lock) ){
24475       rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
24476       pFile->lastErrno = errno;
24477     } else if( lock.l_type!=F_UNLCK ){
24478       reserved = 1;
24479     }
24480   }
24481 #endif
24482   
24483   unixLeaveMutex();
24484   OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
24485
24486   *pResOut = reserved;
24487   return rc;
24488 }
24489
24490 /*
24491 ** Attempt to set a system-lock on the file pFile.  The lock is 
24492 ** described by pLock.
24493 **
24494 ** If the pFile was opened read/write from unix-excl, then the only lock
24495 ** ever obtained is an exclusive lock, and it is obtained exactly once
24496 ** the first time any lock is attempted.  All subsequent system locking
24497 ** operations become no-ops.  Locking operations still happen internally,
24498 ** in order to coordinate access between separate database connections
24499 ** within this process, but all of that is handled in memory and the
24500 ** operating system does not participate.
24501 **
24502 ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
24503 ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
24504 ** and is read-only.
24505 **
24506 ** Zero is returned if the call completes successfully, or -1 if a call
24507 ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
24508 */
24509 static int unixFileLock(unixFile *pFile, struct flock *pLock){
24510   int rc;
24511   unixInodeInfo *pInode = pFile->pInode;
24512   assert( unixMutexHeld() );
24513   assert( pInode!=0 );
24514   if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
24515    && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
24516   ){
24517     if( pInode->bProcessLock==0 ){
24518       struct flock lock;
24519       assert( pInode->nLock==0 );
24520       lock.l_whence = SEEK_SET;
24521       lock.l_start = SHARED_FIRST;
24522       lock.l_len = SHARED_SIZE;
24523       lock.l_type = F_WRLCK;
24524       rc = osFcntl(pFile->h, F_SETLK, &lock);
24525       if( rc<0 ) return rc;
24526       pInode->bProcessLock = 1;
24527       pInode->nLock++;
24528     }else{
24529       rc = 0;
24530     }
24531   }else{
24532     rc = osFcntl(pFile->h, F_SETLK, pLock);
24533   }
24534   return rc;
24535 }
24536
24537 /*
24538 ** Lock the file with the lock specified by parameter eFileLock - one
24539 ** of the following:
24540 **
24541 **     (1) SHARED_LOCK
24542 **     (2) RESERVED_LOCK
24543 **     (3) PENDING_LOCK
24544 **     (4) EXCLUSIVE_LOCK
24545 **
24546 ** Sometimes when requesting one lock state, additional lock states
24547 ** are inserted in between.  The locking might fail on one of the later
24548 ** transitions leaving the lock state different from what it started but
24549 ** still short of its goal.  The following chart shows the allowed
24550 ** transitions and the inserted intermediate states:
24551 **
24552 **    UNLOCKED -> SHARED
24553 **    SHARED -> RESERVED
24554 **    SHARED -> (PENDING) -> EXCLUSIVE
24555 **    RESERVED -> (PENDING) -> EXCLUSIVE
24556 **    PENDING -> EXCLUSIVE
24557 **
24558 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
24559 ** routine to lower a locking level.
24560 */
24561 static int unixLock(sqlite3_file *id, int eFileLock){
24562   /* The following describes the implementation of the various locks and
24563   ** lock transitions in terms of the POSIX advisory shared and exclusive
24564   ** lock primitives (called read-locks and write-locks below, to avoid
24565   ** confusion with SQLite lock names). The algorithms are complicated
24566   ** slightly in order to be compatible with windows systems simultaneously
24567   ** accessing the same database file, in case that is ever required.
24568   **
24569   ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
24570   ** byte', each single bytes at well known offsets, and the 'shared byte
24571   ** range', a range of 510 bytes at a well known offset.
24572   **
24573   ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
24574   ** byte'.  If this is successful, a random byte from the 'shared byte
24575   ** range' is read-locked and the lock on the 'pending byte' released.
24576   **
24577   ** A process may only obtain a RESERVED lock after it has a SHARED lock.
24578   ** A RESERVED lock is implemented by grabbing a write-lock on the
24579   ** 'reserved byte'. 
24580   **
24581   ** A process may only obtain a PENDING lock after it has obtained a
24582   ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
24583   ** on the 'pending byte'. This ensures that no new SHARED locks can be
24584   ** obtained, but existing SHARED locks are allowed to persist. A process
24585   ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
24586   ** This property is used by the algorithm for rolling back a journal file
24587   ** after a crash.
24588   **
24589   ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
24590   ** implemented by obtaining a write-lock on the entire 'shared byte
24591   ** range'. Since all other locks require a read-lock on one of the bytes
24592   ** within this range, this ensures that no other locks are held on the
24593   ** database. 
24594   **
24595   ** The reason a single byte cannot be used instead of the 'shared byte
24596   ** range' is that some versions of windows do not support read-locks. By
24597   ** locking a random byte from a range, concurrent SHARED locks may exist
24598   ** even if the locking primitive used is always a write-lock.
24599   */
24600   int rc = SQLITE_OK;
24601   unixFile *pFile = (unixFile*)id;
24602   unixInodeInfo *pInode;
24603   struct flock lock;
24604   int tErrno = 0;
24605
24606   assert( pFile );
24607   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
24608       azFileLock(eFileLock), azFileLock(pFile->eFileLock),
24609       azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
24610
24611   /* If there is already a lock of this type or more restrictive on the
24612   ** unixFile, do nothing. Don't use the end_lock: exit path, as
24613   ** unixEnterMutex() hasn't been called yet.
24614   */
24615   if( pFile->eFileLock>=eFileLock ){
24616     OSTRACE(("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
24617             azFileLock(eFileLock)));
24618     return SQLITE_OK;
24619   }
24620
24621   /* Make sure the locking sequence is correct.
24622   **  (1) We never move from unlocked to anything higher than shared lock.
24623   **  (2) SQLite never explicitly requests a pendig lock.
24624   **  (3) A shared lock is always held when a reserve lock is requested.
24625   */
24626   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
24627   assert( eFileLock!=PENDING_LOCK );
24628   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
24629
24630   /* This mutex is needed because pFile->pInode is shared across threads
24631   */
24632   unixEnterMutex();
24633   pInode = pFile->pInode;
24634
24635   /* If some thread using this PID has a lock via a different unixFile*
24636   ** handle that precludes the requested lock, return BUSY.
24637   */
24638   if( (pFile->eFileLock!=pInode->eFileLock && 
24639           (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
24640   ){
24641     rc = SQLITE_BUSY;
24642     goto end_lock;
24643   }
24644
24645   /* If a SHARED lock is requested, and some thread using this PID already
24646   ** has a SHARED or RESERVED lock, then increment reference counts and
24647   ** return SQLITE_OK.
24648   */
24649   if( eFileLock==SHARED_LOCK && 
24650       (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
24651     assert( eFileLock==SHARED_LOCK );
24652     assert( pFile->eFileLock==0 );
24653     assert( pInode->nShared>0 );
24654     pFile->eFileLock = SHARED_LOCK;
24655     pInode->nShared++;
24656     pInode->nLock++;
24657     goto end_lock;
24658   }
24659
24660
24661   /* A PENDING lock is needed before acquiring a SHARED lock and before
24662   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
24663   ** be released.
24664   */
24665   lock.l_len = 1L;
24666   lock.l_whence = SEEK_SET;
24667   if( eFileLock==SHARED_LOCK 
24668       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
24669   ){
24670     lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
24671     lock.l_start = PENDING_BYTE;
24672     if( unixFileLock(pFile, &lock) ){
24673       tErrno = errno;
24674       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24675       if( rc!=SQLITE_BUSY ){
24676         pFile->lastErrno = tErrno;
24677       }
24678       goto end_lock;
24679     }
24680   }
24681
24682
24683   /* If control gets to this point, then actually go ahead and make
24684   ** operating system calls for the specified lock.
24685   */
24686   if( eFileLock==SHARED_LOCK ){
24687     assert( pInode->nShared==0 );
24688     assert( pInode->eFileLock==0 );
24689     assert( rc==SQLITE_OK );
24690
24691     /* Now get the read-lock */
24692     lock.l_start = SHARED_FIRST;
24693     lock.l_len = SHARED_SIZE;
24694     if( unixFileLock(pFile, &lock) ){
24695       tErrno = errno;
24696       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24697     }
24698
24699     /* Drop the temporary PENDING lock */
24700     lock.l_start = PENDING_BYTE;
24701     lock.l_len = 1L;
24702     lock.l_type = F_UNLCK;
24703     if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
24704       /* This could happen with a network mount */
24705       tErrno = errno;
24706       rc = SQLITE_IOERR_UNLOCK; 
24707     }
24708
24709     if( rc ){
24710       if( rc!=SQLITE_BUSY ){
24711         pFile->lastErrno = tErrno;
24712       }
24713       goto end_lock;
24714     }else{
24715       pFile->eFileLock = SHARED_LOCK;
24716       pInode->nLock++;
24717       pInode->nShared = 1;
24718     }
24719   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
24720     /* We are trying for an exclusive lock but another thread in this
24721     ** same process is still holding a shared lock. */
24722     rc = SQLITE_BUSY;
24723   }else{
24724     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
24725     ** assumed that there is a SHARED or greater lock on the file
24726     ** already.
24727     */
24728     assert( 0!=pFile->eFileLock );
24729     lock.l_type = F_WRLCK;
24730
24731     assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
24732     if( eFileLock==RESERVED_LOCK ){
24733       lock.l_start = RESERVED_BYTE;
24734       lock.l_len = 1L;
24735     }else{
24736       lock.l_start = SHARED_FIRST;
24737       lock.l_len = SHARED_SIZE;
24738     }
24739
24740     if( unixFileLock(pFile, &lock) ){
24741       tErrno = errno;
24742       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24743       if( rc!=SQLITE_BUSY ){
24744         pFile->lastErrno = tErrno;
24745       }
24746     }
24747   }
24748   
24749
24750 #ifdef SQLITE_DEBUG
24751   /* Set up the transaction-counter change checking flags when
24752   ** transitioning from a SHARED to a RESERVED lock.  The change
24753   ** from SHARED to RESERVED marks the beginning of a normal
24754   ** write operation (not a hot journal rollback).
24755   */
24756   if( rc==SQLITE_OK
24757    && pFile->eFileLock<=SHARED_LOCK
24758    && eFileLock==RESERVED_LOCK
24759   ){
24760     pFile->transCntrChng = 0;
24761     pFile->dbUpdate = 0;
24762     pFile->inNormalWrite = 1;
24763   }
24764 #endif
24765
24766
24767   if( rc==SQLITE_OK ){
24768     pFile->eFileLock = eFileLock;
24769     pInode->eFileLock = eFileLock;
24770   }else if( eFileLock==EXCLUSIVE_LOCK ){
24771     pFile->eFileLock = PENDING_LOCK;
24772     pInode->eFileLock = PENDING_LOCK;
24773   }
24774
24775 end_lock:
24776   unixLeaveMutex();
24777   OSTRACE(("LOCK    %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock), 
24778       rc==SQLITE_OK ? "ok" : "failed"));
24779   return rc;
24780 }
24781
24782 /*
24783 ** Add the file descriptor used by file handle pFile to the corresponding
24784 ** pUnused list.
24785 */
24786 static void setPendingFd(unixFile *pFile){
24787   unixInodeInfo *pInode = pFile->pInode;
24788   UnixUnusedFd *p = pFile->pUnused;
24789   p->pNext = pInode->pUnused;
24790   pInode->pUnused = p;
24791   pFile->h = -1;
24792   pFile->pUnused = 0;
24793 }
24794
24795 /*
24796 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
24797 ** must be either NO_LOCK or SHARED_LOCK.
24798 **
24799 ** If the locking level of the file descriptor is already at or below
24800 ** the requested locking level, this routine is a no-op.
24801 ** 
24802 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
24803 ** the byte range is divided into 2 parts and the first part is unlocked then
24804 ** set to a read lock, then the other part is simply unlocked.  This works 
24805 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to 
24806 ** remove the write lock on a region when a read lock is set.
24807 */
24808 static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
24809   unixFile *pFile = (unixFile*)id;
24810   unixInodeInfo *pInode;
24811   struct flock lock;
24812   int rc = SQLITE_OK;
24813
24814   assert( pFile );
24815   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
24816       pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
24817       getpid()));
24818
24819   assert( eFileLock<=SHARED_LOCK );
24820   if( pFile->eFileLock<=eFileLock ){
24821     return SQLITE_OK;
24822   }
24823   unixEnterMutex();
24824   pInode = pFile->pInode;
24825   assert( pInode->nShared!=0 );
24826   if( pFile->eFileLock>SHARED_LOCK ){
24827     assert( pInode->eFileLock==pFile->eFileLock );
24828
24829 #ifdef SQLITE_DEBUG
24830     /* When reducing a lock such that other processes can start
24831     ** reading the database file again, make sure that the
24832     ** transaction counter was updated if any part of the database
24833     ** file changed.  If the transaction counter is not updated,
24834     ** other connections to the same file might not realize that
24835     ** the file has changed and hence might not know to flush their
24836     ** cache.  The use of a stale cache can lead to database corruption.
24837     */
24838     pFile->inNormalWrite = 0;
24839 #endif
24840
24841     /* downgrading to a shared lock on NFS involves clearing the write lock
24842     ** before establishing the readlock - to avoid a race condition we downgrade
24843     ** the lock in 2 blocks, so that part of the range will be covered by a 
24844     ** write lock until the rest is covered by a read lock:
24845     **  1:   [WWWWW]
24846     **  2:   [....W]
24847     **  3:   [RRRRW]
24848     **  4:   [RRRR.]
24849     */
24850     if( eFileLock==SHARED_LOCK ){
24851
24852 #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
24853       (void)handleNFSUnlock;
24854       assert( handleNFSUnlock==0 );
24855 #endif
24856 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
24857       if( handleNFSUnlock ){
24858         int tErrno;               /* Error code from system call errors */
24859         off_t divSize = SHARED_SIZE - 1;
24860         
24861         lock.l_type = F_UNLCK;
24862         lock.l_whence = SEEK_SET;
24863         lock.l_start = SHARED_FIRST;
24864         lock.l_len = divSize;
24865         if( unixFileLock(pFile, &lock)==(-1) ){
24866           tErrno = errno;
24867           rc = SQLITE_IOERR_UNLOCK;
24868           if( IS_LOCK_ERROR(rc) ){
24869             pFile->lastErrno = tErrno;
24870           }
24871           goto end_unlock;
24872         }
24873         lock.l_type = F_RDLCK;
24874         lock.l_whence = SEEK_SET;
24875         lock.l_start = SHARED_FIRST;
24876         lock.l_len = divSize;
24877         if( unixFileLock(pFile, &lock)==(-1) ){
24878           tErrno = errno;
24879           rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
24880           if( IS_LOCK_ERROR(rc) ){
24881             pFile->lastErrno = tErrno;
24882           }
24883           goto end_unlock;
24884         }
24885         lock.l_type = F_UNLCK;
24886         lock.l_whence = SEEK_SET;
24887         lock.l_start = SHARED_FIRST+divSize;
24888         lock.l_len = SHARED_SIZE-divSize;
24889         if( unixFileLock(pFile, &lock)==(-1) ){
24890           tErrno = errno;
24891           rc = SQLITE_IOERR_UNLOCK;
24892           if( IS_LOCK_ERROR(rc) ){
24893             pFile->lastErrno = tErrno;
24894           }
24895           goto end_unlock;
24896         }
24897       }else
24898 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
24899       {
24900         lock.l_type = F_RDLCK;
24901         lock.l_whence = SEEK_SET;
24902         lock.l_start = SHARED_FIRST;
24903         lock.l_len = SHARED_SIZE;
24904         if( unixFileLock(pFile, &lock) ){
24905           /* In theory, the call to unixFileLock() cannot fail because another
24906           ** process is holding an incompatible lock. If it does, this 
24907           ** indicates that the other process is not following the locking
24908           ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
24909           ** SQLITE_BUSY would confuse the upper layer (in practice it causes 
24910           ** an assert to fail). */ 
24911           rc = SQLITE_IOERR_RDLOCK;
24912           pFile->lastErrno = errno;
24913           goto end_unlock;
24914         }
24915       }
24916     }
24917     lock.l_type = F_UNLCK;
24918     lock.l_whence = SEEK_SET;
24919     lock.l_start = PENDING_BYTE;
24920     lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
24921     if( unixFileLock(pFile, &lock)==0 ){
24922       pInode->eFileLock = SHARED_LOCK;
24923     }else{
24924       rc = SQLITE_IOERR_UNLOCK;
24925       pFile->lastErrno = errno;
24926       goto end_unlock;
24927     }
24928   }
24929   if( eFileLock==NO_LOCK ){
24930     /* Decrement the shared lock counter.  Release the lock using an
24931     ** OS call only when all threads in this same process have released
24932     ** the lock.
24933     */
24934     pInode->nShared--;
24935     if( pInode->nShared==0 ){
24936       lock.l_type = F_UNLCK;
24937       lock.l_whence = SEEK_SET;
24938       lock.l_start = lock.l_len = 0L;
24939       if( unixFileLock(pFile, &lock)==0 ){
24940         pInode->eFileLock = NO_LOCK;
24941       }else{
24942         rc = SQLITE_IOERR_UNLOCK;
24943         pFile->lastErrno = errno;
24944         pInode->eFileLock = NO_LOCK;
24945         pFile->eFileLock = NO_LOCK;
24946       }
24947     }
24948
24949     /* Decrement the count of locks against this same file.  When the
24950     ** count reaches zero, close any other file descriptors whose close
24951     ** was deferred because of outstanding locks.
24952     */
24953     pInode->nLock--;
24954     assert( pInode->nLock>=0 );
24955     if( pInode->nLock==0 ){
24956       closePendingFds(pFile);
24957     }
24958   }
24959
24960 end_unlock:
24961   unixLeaveMutex();
24962   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
24963   return rc;
24964 }
24965
24966 /*
24967 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
24968 ** must be either NO_LOCK or SHARED_LOCK.
24969 **
24970 ** If the locking level of the file descriptor is already at or below
24971 ** the requested locking level, this routine is a no-op.
24972 */
24973 static int unixUnlock(sqlite3_file *id, int eFileLock){
24974   assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
24975   return posixUnlock(id, eFileLock, 0);
24976 }
24977
24978 static int unixMapfile(unixFile *pFd, i64 nByte);
24979 static void unixUnmapfile(unixFile *pFd);
24980
24981 /*
24982 ** This function performs the parts of the "close file" operation 
24983 ** common to all locking schemes. It closes the directory and file
24984 ** handles, if they are valid, and sets all fields of the unixFile
24985 ** structure to 0.
24986 **
24987 ** It is *not* necessary to hold the mutex when this routine is called,
24988 ** even on VxWorks.  A mutex will be acquired on VxWorks by the
24989 ** vxworksReleaseFileId() routine.
24990 */
24991 static int closeUnixFile(sqlite3_file *id){
24992   unixFile *pFile = (unixFile*)id;
24993   unixUnmapfile(pFile);
24994   if( pFile->h>=0 ){
24995     robust_close(pFile, pFile->h, __LINE__);
24996     pFile->h = -1;
24997   }
24998 #if OS_VXWORKS
24999   if( pFile->pId ){
25000     if( pFile->ctrlFlags & UNIXFILE_DELETE ){
25001       osUnlink(pFile->pId->zCanonicalName);
25002     }
25003     vxworksReleaseFileId(pFile->pId);
25004     pFile->pId = 0;
25005   }
25006 #endif
25007   OSTRACE(("CLOSE   %-3d\n", pFile->h));
25008   OpenCounter(-1);
25009   sqlite3_free(pFile->pUnused);
25010   memset(pFile, 0, sizeof(unixFile));
25011   return SQLITE_OK;
25012 }
25013
25014 /*
25015 ** Close a file.
25016 */
25017 static int unixClose(sqlite3_file *id){
25018   int rc = SQLITE_OK;
25019   unixFile *pFile = (unixFile *)id;
25020   verifyDbFile(pFile);
25021   unixUnlock(id, NO_LOCK);
25022   unixEnterMutex();
25023
25024   /* unixFile.pInode is always valid here. Otherwise, a different close
25025   ** routine (e.g. nolockClose()) would be called instead.
25026   */
25027   assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
25028   if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
25029     /* If there are outstanding locks, do not actually close the file just
25030     ** yet because that would clear those locks.  Instead, add the file
25031     ** descriptor to pInode->pUnused list.  It will be automatically closed 
25032     ** when the last lock is cleared.
25033     */
25034     setPendingFd(pFile);
25035   }
25036   releaseInodeInfo(pFile);
25037   rc = closeUnixFile(id);
25038   unixLeaveMutex();
25039   return rc;
25040 }
25041
25042 /************** End of the posix advisory lock implementation *****************
25043 ******************************************************************************/
25044
25045 /******************************************************************************
25046 ****************************** No-op Locking **********************************
25047 **
25048 ** Of the various locking implementations available, this is by far the
25049 ** simplest:  locking is ignored.  No attempt is made to lock the database
25050 ** file for reading or writing.
25051 **
25052 ** This locking mode is appropriate for use on read-only databases
25053 ** (ex: databases that are burned into CD-ROM, for example.)  It can
25054 ** also be used if the application employs some external mechanism to
25055 ** prevent simultaneous access of the same database by two or more
25056 ** database connections.  But there is a serious risk of database
25057 ** corruption if this locking mode is used in situations where multiple
25058 ** database connections are accessing the same database file at the same
25059 ** time and one or more of those connections are writing.
25060 */
25061
25062 static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
25063   UNUSED_PARAMETER(NotUsed);
25064   *pResOut = 0;
25065   return SQLITE_OK;
25066 }
25067 static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
25068   UNUSED_PARAMETER2(NotUsed, NotUsed2);
25069   return SQLITE_OK;
25070 }
25071 static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
25072   UNUSED_PARAMETER2(NotUsed, NotUsed2);
25073   return SQLITE_OK;
25074 }
25075
25076 /*
25077 ** Close the file.
25078 */
25079 static int nolockClose(sqlite3_file *id) {
25080   return closeUnixFile(id);
25081 }
25082
25083 /******************* End of the no-op lock implementation *********************
25084 ******************************************************************************/
25085
25086 /******************************************************************************
25087 ************************* Begin dot-file Locking ******************************
25088 **
25089 ** The dotfile locking implementation uses the existence of separate lock
25090 ** files (really a directory) to control access to the database.  This works
25091 ** on just about every filesystem imaginable.  But there are serious downsides:
25092 **
25093 **    (1)  There is zero concurrency.  A single reader blocks all other
25094 **         connections from reading or writing the database.
25095 **
25096 **    (2)  An application crash or power loss can leave stale lock files
25097 **         sitting around that need to be cleared manually.
25098 **
25099 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
25100 ** other locking strategy is available.
25101 **
25102 ** Dotfile locking works by creating a subdirectory in the same directory as
25103 ** the database and with the same name but with a ".lock" extension added.
25104 ** The existence of a lock directory implies an EXCLUSIVE lock.  All other
25105 ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
25106 */
25107
25108 /*
25109 ** The file suffix added to the data base filename in order to create the
25110 ** lock directory.
25111 */
25112 #define DOTLOCK_SUFFIX ".lock"
25113
25114 /*
25115 ** This routine checks if there is a RESERVED lock held on the specified
25116 ** file by this or any other process. If such a lock is held, set *pResOut
25117 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
25118 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
25119 **
25120 ** In dotfile locking, either a lock exists or it does not.  So in this
25121 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
25122 ** is held on the file and false if the file is unlocked.
25123 */
25124 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
25125   int rc = SQLITE_OK;
25126   int reserved = 0;
25127   unixFile *pFile = (unixFile*)id;
25128
25129   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
25130   
25131   assert( pFile );
25132
25133   /* Check if a thread in this process holds such a lock */
25134   if( pFile->eFileLock>SHARED_LOCK ){
25135     /* Either this connection or some other connection in the same process
25136     ** holds a lock on the file.  No need to check further. */
25137     reserved = 1;
25138   }else{
25139     /* The lock is held if and only if the lockfile exists */
25140     const char *zLockFile = (const char*)pFile->lockingContext;
25141     reserved = osAccess(zLockFile, 0)==0;
25142   }
25143   OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
25144   *pResOut = reserved;
25145   return rc;
25146 }
25147
25148 /*
25149 ** Lock the file with the lock specified by parameter eFileLock - one
25150 ** of the following:
25151 **
25152 **     (1) SHARED_LOCK
25153 **     (2) RESERVED_LOCK
25154 **     (3) PENDING_LOCK
25155 **     (4) EXCLUSIVE_LOCK
25156 **
25157 ** Sometimes when requesting one lock state, additional lock states
25158 ** are inserted in between.  The locking might fail on one of the later
25159 ** transitions leaving the lock state different from what it started but
25160 ** still short of its goal.  The following chart shows the allowed
25161 ** transitions and the inserted intermediate states:
25162 **
25163 **    UNLOCKED -> SHARED
25164 **    SHARED -> RESERVED
25165 **    SHARED -> (PENDING) -> EXCLUSIVE
25166 **    RESERVED -> (PENDING) -> EXCLUSIVE
25167 **    PENDING -> EXCLUSIVE
25168 **
25169 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
25170 ** routine to lower a locking level.
25171 **
25172 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
25173 ** But we track the other locking levels internally.
25174 */
25175 static int dotlockLock(sqlite3_file *id, int eFileLock) {
25176   unixFile *pFile = (unixFile*)id;
25177   char *zLockFile = (char *)pFile->lockingContext;
25178   int rc = SQLITE_OK;
25179
25180
25181   /* If we have any lock, then the lock file already exists.  All we have
25182   ** to do is adjust our internal record of the lock level.
25183   */
25184   if( pFile->eFileLock > NO_LOCK ){
25185     pFile->eFileLock = eFileLock;
25186     /* Always update the timestamp on the old file */
25187 #ifdef HAVE_UTIME
25188     utime(zLockFile, NULL);
25189 #else
25190     utimes(zLockFile, NULL);
25191 #endif
25192     return SQLITE_OK;
25193   }
25194   
25195   /* grab an exclusive lock */
25196   rc = osMkdir(zLockFile, 0777);
25197   if( rc<0 ){
25198     /* failed to open/create the lock directory */
25199     int tErrno = errno;
25200     if( EEXIST == tErrno ){
25201       rc = SQLITE_BUSY;
25202     } else {
25203       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
25204       if( IS_LOCK_ERROR(rc) ){
25205         pFile->lastErrno = tErrno;
25206       }
25207     }
25208     return rc;
25209   } 
25210   
25211   /* got it, set the type and return ok */
25212   pFile->eFileLock = eFileLock;
25213   return rc;
25214 }
25215
25216 /*
25217 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
25218 ** must be either NO_LOCK or SHARED_LOCK.
25219 **
25220 ** If the locking level of the file descriptor is already at or below
25221 ** the requested locking level, this routine is a no-op.
25222 **
25223 ** When the locking level reaches NO_LOCK, delete the lock file.
25224 */
25225 static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
25226   unixFile *pFile = (unixFile*)id;
25227   char *zLockFile = (char *)pFile->lockingContext;
25228   int rc;
25229
25230   assert( pFile );
25231   OSTRACE(("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
25232            pFile->eFileLock, getpid()));
25233   assert( eFileLock<=SHARED_LOCK );
25234   
25235   /* no-op if possible */
25236   if( pFile->eFileLock==eFileLock ){
25237     return SQLITE_OK;
25238   }
25239
25240   /* To downgrade to shared, simply update our internal notion of the
25241   ** lock state.  No need to mess with the file on disk.
25242   */
25243   if( eFileLock==SHARED_LOCK ){
25244     pFile->eFileLock = SHARED_LOCK;
25245     return SQLITE_OK;
25246   }
25247   
25248   /* To fully unlock the database, delete the lock file */
25249   assert( eFileLock==NO_LOCK );
25250   rc = osRmdir(zLockFile);
25251   if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
25252   if( rc<0 ){
25253     int tErrno = errno;
25254     rc = 0;
25255     if( ENOENT != tErrno ){
25256       rc = SQLITE_IOERR_UNLOCK;
25257     }
25258     if( IS_LOCK_ERROR(rc) ){
25259       pFile->lastErrno = tErrno;
25260     }
25261     return rc; 
25262   }
25263   pFile->eFileLock = NO_LOCK;
25264   return SQLITE_OK;
25265 }
25266
25267 /*
25268 ** Close a file.  Make sure the lock has been released before closing.
25269 */
25270 static int dotlockClose(sqlite3_file *id) {
25271   int rc = SQLITE_OK;
25272   if( id ){
25273     unixFile *pFile = (unixFile*)id;
25274     dotlockUnlock(id, NO_LOCK);
25275     sqlite3_free(pFile->lockingContext);
25276     rc = closeUnixFile(id);
25277   }
25278   return rc;
25279 }
25280 /****************** End of the dot-file lock implementation *******************
25281 ******************************************************************************/
25282
25283 /******************************************************************************
25284 ************************** Begin flock Locking ********************************
25285 **
25286 ** Use the flock() system call to do file locking.
25287 **
25288 ** flock() locking is like dot-file locking in that the various
25289 ** fine-grain locking levels supported by SQLite are collapsed into
25290 ** a single exclusive lock.  In other words, SHARED, RESERVED, and
25291 ** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
25292 ** still works when you do this, but concurrency is reduced since
25293 ** only a single process can be reading the database at a time.
25294 **
25295 ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
25296 ** compiling for VXWORKS.
25297 */
25298 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
25299
25300 /*
25301 ** Retry flock() calls that fail with EINTR
25302 */
25303 #ifdef EINTR
25304 static int robust_flock(int fd, int op){
25305   int rc;
25306   do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
25307   return rc;
25308 }
25309 #else
25310 # define robust_flock(a,b) flock(a,b)
25311 #endif
25312      
25313
25314 /*
25315 ** This routine checks if there is a RESERVED lock held on the specified
25316 ** file by this or any other process. If such a lock is held, set *pResOut
25317 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
25318 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
25319 */
25320 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
25321   int rc = SQLITE_OK;
25322   int reserved = 0;
25323   unixFile *pFile = (unixFile*)id;
25324   
25325   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
25326   
25327   assert( pFile );
25328   
25329   /* Check if a thread in this process holds such a lock */
25330   if( pFile->eFileLock>SHARED_LOCK ){
25331     reserved = 1;
25332   }
25333   
25334   /* Otherwise see if some other process holds it. */
25335   if( !reserved ){
25336     /* attempt to get the lock */
25337     int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
25338     if( !lrc ){
25339       /* got the lock, unlock it */
25340       lrc = robust_flock(pFile->h, LOCK_UN);
25341       if ( lrc ) {
25342         int tErrno = errno;
25343         /* unlock failed with an error */
25344         lrc = SQLITE_IOERR_UNLOCK; 
25345         if( IS_LOCK_ERROR(lrc) ){
25346           pFile->lastErrno = tErrno;
25347           rc = lrc;
25348         }
25349       }
25350     } else {
25351       int tErrno = errno;
25352       reserved = 1;
25353       /* someone else might have it reserved */
25354       lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); 
25355       if( IS_LOCK_ERROR(lrc) ){
25356         pFile->lastErrno = tErrno;
25357         rc = lrc;
25358       }
25359     }
25360   }
25361   OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
25362
25363 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
25364   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
25365     rc = SQLITE_OK;
25366     reserved=1;
25367   }
25368 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
25369   *pResOut = reserved;
25370   return rc;
25371 }
25372
25373 /*
25374 ** Lock the file with the lock specified by parameter eFileLock - one
25375 ** of the following:
25376 **
25377 **     (1) SHARED_LOCK
25378 **     (2) RESERVED_LOCK
25379 **     (3) PENDING_LOCK
25380 **     (4) EXCLUSIVE_LOCK
25381 **
25382 ** Sometimes when requesting one lock state, additional lock states
25383 ** are inserted in between.  The locking might fail on one of the later
25384 ** transitions leaving the lock state different from what it started but
25385 ** still short of its goal.  The following chart shows the allowed
25386 ** transitions and the inserted intermediate states:
25387 **
25388 **    UNLOCKED -> SHARED
25389 **    SHARED -> RESERVED
25390 **    SHARED -> (PENDING) -> EXCLUSIVE
25391 **    RESERVED -> (PENDING) -> EXCLUSIVE
25392 **    PENDING -> EXCLUSIVE
25393 **
25394 ** flock() only really support EXCLUSIVE locks.  We track intermediate
25395 ** lock states in the sqlite3_file structure, but all locks SHARED or
25396 ** above are really EXCLUSIVE locks and exclude all other processes from
25397 ** access the file.
25398 **
25399 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
25400 ** routine to lower a locking level.
25401 */
25402 static int flockLock(sqlite3_file *id, int eFileLock) {
25403   int rc = SQLITE_OK;
25404   unixFile *pFile = (unixFile*)id;
25405
25406   assert( pFile );
25407
25408   /* if we already have a lock, it is exclusive.  
25409   ** Just adjust level and punt on outta here. */
25410   if (pFile->eFileLock > NO_LOCK) {
25411     pFile->eFileLock = eFileLock;
25412     return SQLITE_OK;
25413   }
25414   
25415   /* grab an exclusive lock */
25416   
25417   if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
25418     int tErrno = errno;
25419     /* didn't get, must be busy */
25420     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
25421     if( IS_LOCK_ERROR(rc) ){
25422       pFile->lastErrno = tErrno;
25423     }
25424   } else {
25425     /* got it, set the type and return ok */
25426     pFile->eFileLock = eFileLock;
25427   }
25428   OSTRACE(("LOCK    %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock), 
25429            rc==SQLITE_OK ? "ok" : "failed"));
25430 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
25431   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
25432     rc = SQLITE_BUSY;
25433   }
25434 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
25435   return rc;
25436 }
25437
25438
25439 /*
25440 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
25441 ** must be either NO_LOCK or SHARED_LOCK.
25442 **
25443 ** If the locking level of the file descriptor is already at or below
25444 ** the requested locking level, this routine is a no-op.
25445 */
25446 static int flockUnlock(sqlite3_file *id, int eFileLock) {
25447   unixFile *pFile = (unixFile*)id;
25448   
25449   assert( pFile );
25450   OSTRACE(("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
25451            pFile->eFileLock, getpid()));
25452   assert( eFileLock<=SHARED_LOCK );
25453   
25454   /* no-op if possible */
25455   if( pFile->eFileLock==eFileLock ){
25456     return SQLITE_OK;
25457   }
25458   
25459   /* shared can just be set because we always have an exclusive */
25460   if (eFileLock==SHARED_LOCK) {
25461     pFile->eFileLock = eFileLock;
25462     return SQLITE_OK;
25463   }
25464   
25465   /* no, really, unlock. */
25466   if( robust_flock(pFile->h, LOCK_UN) ){
25467 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
25468     return SQLITE_OK;
25469 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
25470     return SQLITE_IOERR_UNLOCK;
25471   }else{
25472     pFile->eFileLock = NO_LOCK;
25473     return SQLITE_OK;
25474   }
25475 }
25476
25477 /*
25478 ** Close a file.
25479 */
25480 static int flockClose(sqlite3_file *id) {
25481   int rc = SQLITE_OK;
25482   if( id ){
25483     flockUnlock(id, NO_LOCK);
25484     rc = closeUnixFile(id);
25485   }
25486   return rc;
25487 }
25488
25489 #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
25490
25491 /******************* End of the flock lock implementation *********************
25492 ******************************************************************************/
25493
25494 /******************************************************************************
25495 ************************ Begin Named Semaphore Locking ************************
25496 **
25497 ** Named semaphore locking is only supported on VxWorks.
25498 **
25499 ** Semaphore locking is like dot-lock and flock in that it really only
25500 ** supports EXCLUSIVE locking.  Only a single process can read or write
25501 ** the database file at a time.  This reduces potential concurrency, but
25502 ** makes the lock implementation much easier.
25503 */
25504 #if OS_VXWORKS
25505
25506 /*
25507 ** This routine checks if there is a RESERVED lock held on the specified
25508 ** file by this or any other process. If such a lock is held, set *pResOut
25509 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
25510 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
25511 */
25512 static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
25513   int rc = SQLITE_OK;
25514   int reserved = 0;
25515   unixFile *pFile = (unixFile*)id;
25516
25517   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
25518   
25519   assert( pFile );
25520
25521   /* Check if a thread in this process holds such a lock */
25522   if( pFile->eFileLock>SHARED_LOCK ){
25523     reserved = 1;
25524   }
25525   
25526   /* Otherwise see if some other process holds it. */
25527   if( !reserved ){
25528     sem_t *pSem = pFile->pInode->pSem;
25529     struct stat statBuf;
25530
25531     if( sem_trywait(pSem)==-1 ){
25532       int tErrno = errno;
25533       if( EAGAIN != tErrno ){
25534         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
25535         pFile->lastErrno = tErrno;
25536       } else {
25537         /* someone else has the lock when we are in NO_LOCK */
25538         reserved = (pFile->eFileLock < SHARED_LOCK);
25539       }
25540     }else{
25541       /* we could have it if we want it */
25542       sem_post(pSem);
25543     }
25544   }
25545   OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
25546
25547   *pResOut = reserved;
25548   return rc;
25549 }
25550
25551 /*
25552 ** Lock the file with the lock specified by parameter eFileLock - one
25553 ** of the following:
25554 **
25555 **     (1) SHARED_LOCK
25556 **     (2) RESERVED_LOCK
25557 **     (3) PENDING_LOCK
25558 **     (4) EXCLUSIVE_LOCK
25559 **
25560 ** Sometimes when requesting one lock state, additional lock states
25561 ** are inserted in between.  The locking might fail on one of the later
25562 ** transitions leaving the lock state different from what it started but
25563 ** still short of its goal.  The following chart shows the allowed
25564 ** transitions and the inserted intermediate states:
25565 **
25566 **    UNLOCKED -> SHARED
25567 **    SHARED -> RESERVED
25568 **    SHARED -> (PENDING) -> EXCLUSIVE
25569 **    RESERVED -> (PENDING) -> EXCLUSIVE
25570 **    PENDING -> EXCLUSIVE
25571 **
25572 ** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
25573 ** lock states in the sqlite3_file structure, but all locks SHARED or
25574 ** above are really EXCLUSIVE locks and exclude all other processes from
25575 ** access the file.
25576 **
25577 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
25578 ** routine to lower a locking level.
25579 */
25580 static int semLock(sqlite3_file *id, int eFileLock) {
25581   unixFile *pFile = (unixFile*)id;
25582   int fd;
25583   sem_t *pSem = pFile->pInode->pSem;
25584   int rc = SQLITE_OK;
25585
25586   /* if we already have a lock, it is exclusive.  
25587   ** Just adjust level and punt on outta here. */
25588   if (pFile->eFileLock > NO_LOCK) {
25589     pFile->eFileLock = eFileLock;
25590     rc = SQLITE_OK;
25591     goto sem_end_lock;
25592   }
25593   
25594   /* lock semaphore now but bail out when already locked. */
25595   if( sem_trywait(pSem)==-1 ){
25596     rc = SQLITE_BUSY;
25597     goto sem_end_lock;
25598   }
25599
25600   /* got it, set the type and return ok */
25601   pFile->eFileLock = eFileLock;
25602
25603  sem_end_lock:
25604   return rc;
25605 }
25606
25607 /*
25608 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
25609 ** must be either NO_LOCK or SHARED_LOCK.
25610 **
25611 ** If the locking level of the file descriptor is already at or below
25612 ** the requested locking level, this routine is a no-op.
25613 */
25614 static int semUnlock(sqlite3_file *id, int eFileLock) {
25615   unixFile *pFile = (unixFile*)id;
25616   sem_t *pSem = pFile->pInode->pSem;
25617
25618   assert( pFile );
25619   assert( pSem );
25620   OSTRACE(("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
25621            pFile->eFileLock, getpid()));
25622   assert( eFileLock<=SHARED_LOCK );
25623   
25624   /* no-op if possible */
25625   if( pFile->eFileLock==eFileLock ){
25626     return SQLITE_OK;
25627   }
25628   
25629   /* shared can just be set because we always have an exclusive */
25630   if (eFileLock==SHARED_LOCK) {
25631     pFile->eFileLock = eFileLock;
25632     return SQLITE_OK;
25633   }
25634   
25635   /* no, really unlock. */
25636   if ( sem_post(pSem)==-1 ) {
25637     int rc, tErrno = errno;
25638     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
25639     if( IS_LOCK_ERROR(rc) ){
25640       pFile->lastErrno = tErrno;
25641     }
25642     return rc; 
25643   }
25644   pFile->eFileLock = NO_LOCK;
25645   return SQLITE_OK;
25646 }
25647
25648 /*
25649  ** Close a file.
25650  */
25651 static int semClose(sqlite3_file *id) {
25652   if( id ){
25653     unixFile *pFile = (unixFile*)id;
25654     semUnlock(id, NO_LOCK);
25655     assert( pFile );
25656     unixEnterMutex();
25657     releaseInodeInfo(pFile);
25658     unixLeaveMutex();
25659     closeUnixFile(id);
25660   }
25661   return SQLITE_OK;
25662 }
25663
25664 #endif /* OS_VXWORKS */
25665 /*
25666 ** Named semaphore locking is only available on VxWorks.
25667 **
25668 *************** End of the named semaphore lock implementation ****************
25669 ******************************************************************************/
25670
25671
25672 /******************************************************************************
25673 *************************** Begin AFP Locking *********************************
25674 **
25675 ** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
25676 ** on Apple Macintosh computers - both OS9 and OSX.
25677 **
25678 ** Third-party implementations of AFP are available.  But this code here
25679 ** only works on OSX.
25680 */
25681
25682 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
25683 /*
25684 ** The afpLockingContext structure contains all afp lock specific state
25685 */
25686 typedef struct afpLockingContext afpLockingContext;
25687 struct afpLockingContext {
25688   int reserved;
25689   const char *dbPath;             /* Name of the open file */
25690 };
25691
25692 struct ByteRangeLockPB2
25693 {
25694   unsigned long long offset;        /* offset to first byte to lock */
25695   unsigned long long length;        /* nbr of bytes to lock */
25696   unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
25697   unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
25698   unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
25699   int fd;                           /* file desc to assoc this lock with */
25700 };
25701
25702 #define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
25703
25704 /*
25705 ** This is a utility for setting or clearing a bit-range lock on an
25706 ** AFP filesystem.
25707 ** 
25708 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
25709 */
25710 static int afpSetLock(
25711   const char *path,              /* Name of the file to be locked or unlocked */
25712   unixFile *pFile,               /* Open file descriptor on path */
25713   unsigned long long offset,     /* First byte to be locked */
25714   unsigned long long length,     /* Number of bytes to lock */
25715   int setLockFlag                /* True to set lock.  False to clear lock */
25716 ){
25717   struct ByteRangeLockPB2 pb;
25718   int err;
25719   
25720   pb.unLockFlag = setLockFlag ? 0 : 1;
25721   pb.startEndFlag = 0;
25722   pb.offset = offset;
25723   pb.length = length; 
25724   pb.fd = pFile->h;
25725   
25726   OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n", 
25727     (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
25728     offset, length));
25729   err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
25730   if ( err==-1 ) {
25731     int rc;
25732     int tErrno = errno;
25733     OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
25734              path, tErrno, strerror(tErrno)));
25735 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
25736     rc = SQLITE_BUSY;
25737 #else
25738     rc = sqliteErrorFromPosixError(tErrno,
25739                     setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
25740 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
25741     if( IS_LOCK_ERROR(rc) ){
25742       pFile->lastErrno = tErrno;
25743     }
25744     return rc;
25745   } else {
25746     return SQLITE_OK;
25747   }
25748 }
25749
25750 /*
25751 ** This routine checks if there is a RESERVED lock held on the specified
25752 ** file by this or any other process. If such a lock is held, set *pResOut
25753 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
25754 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
25755 */
25756 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
25757   int rc = SQLITE_OK;
25758   int reserved = 0;
25759   unixFile *pFile = (unixFile*)id;
25760   afpLockingContext *context;
25761   
25762   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
25763   
25764   assert( pFile );
25765   context = (afpLockingContext *) pFile->lockingContext;
25766   if( context->reserved ){
25767     *pResOut = 1;
25768     return SQLITE_OK;
25769   }
25770   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
25771   
25772   /* Check if a thread in this process holds such a lock */
25773   if( pFile->pInode->eFileLock>SHARED_LOCK ){
25774     reserved = 1;
25775   }
25776   
25777   /* Otherwise see if some other process holds it.
25778    */
25779   if( !reserved ){
25780     /* lock the RESERVED byte */
25781     int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);  
25782     if( SQLITE_OK==lrc ){
25783       /* if we succeeded in taking the reserved lock, unlock it to restore
25784       ** the original state */
25785       lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
25786     } else {
25787       /* if we failed to get the lock then someone else must have it */
25788       reserved = 1;
25789     }
25790     if( IS_LOCK_ERROR(lrc) ){
25791       rc=lrc;
25792     }
25793   }
25794   
25795   unixLeaveMutex();
25796   OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
25797   
25798   *pResOut = reserved;
25799   return rc;
25800 }
25801
25802 /*
25803 ** Lock the file with the lock specified by parameter eFileLock - one
25804 ** of the following:
25805 **
25806 **     (1) SHARED_LOCK
25807 **     (2) RESERVED_LOCK
25808 **     (3) PENDING_LOCK
25809 **     (4) EXCLUSIVE_LOCK
25810 **
25811 ** Sometimes when requesting one lock state, additional lock states
25812 ** are inserted in between.  The locking might fail on one of the later
25813 ** transitions leaving the lock state different from what it started but
25814 ** still short of its goal.  The following chart shows the allowed
25815 ** transitions and the inserted intermediate states:
25816 **
25817 **    UNLOCKED -> SHARED
25818 **    SHARED -> RESERVED
25819 **    SHARED -> (PENDING) -> EXCLUSIVE
25820 **    RESERVED -> (PENDING) -> EXCLUSIVE
25821 **    PENDING -> EXCLUSIVE
25822 **
25823 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
25824 ** routine to lower a locking level.
25825 */
25826 static int afpLock(sqlite3_file *id, int eFileLock){
25827   int rc = SQLITE_OK;
25828   unixFile *pFile = (unixFile*)id;
25829   unixInodeInfo *pInode = pFile->pInode;
25830   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
25831   
25832   assert( pFile );
25833   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
25834            azFileLock(eFileLock), azFileLock(pFile->eFileLock),
25835            azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
25836
25837   /* If there is already a lock of this type or more restrictive on the
25838   ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
25839   ** unixEnterMutex() hasn't been called yet.
25840   */
25841   if( pFile->eFileLock>=eFileLock ){
25842     OSTRACE(("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
25843            azFileLock(eFileLock)));
25844     return SQLITE_OK;
25845   }
25846
25847   /* Make sure the locking sequence is correct
25848   **  (1) We never move from unlocked to anything higher than shared lock.
25849   **  (2) SQLite never explicitly requests a pendig lock.
25850   **  (3) A shared lock is always held when a reserve lock is requested.
25851   */
25852   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
25853   assert( eFileLock!=PENDING_LOCK );
25854   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
25855   
25856   /* This mutex is needed because pFile->pInode is shared across threads
25857   */
25858   unixEnterMutex();
25859   pInode = pFile->pInode;
25860
25861   /* If some thread using this PID has a lock via a different unixFile*
25862   ** handle that precludes the requested lock, return BUSY.
25863   */
25864   if( (pFile->eFileLock!=pInode->eFileLock && 
25865        (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
25866      ){
25867     rc = SQLITE_BUSY;
25868     goto afp_end_lock;
25869   }
25870   
25871   /* If a SHARED lock is requested, and some thread using this PID already
25872   ** has a SHARED or RESERVED lock, then increment reference counts and
25873   ** return SQLITE_OK.
25874   */
25875   if( eFileLock==SHARED_LOCK && 
25876      (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
25877     assert( eFileLock==SHARED_LOCK );
25878     assert( pFile->eFileLock==0 );
25879     assert( pInode->nShared>0 );
25880     pFile->eFileLock = SHARED_LOCK;
25881     pInode->nShared++;
25882     pInode->nLock++;
25883     goto afp_end_lock;
25884   }
25885     
25886   /* A PENDING lock is needed before acquiring a SHARED lock and before
25887   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
25888   ** be released.
25889   */
25890   if( eFileLock==SHARED_LOCK 
25891       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
25892   ){
25893     int failed;
25894     failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
25895     if (failed) {
25896       rc = failed;
25897       goto afp_end_lock;
25898     }
25899   }
25900   
25901   /* If control gets to this point, then actually go ahead and make
25902   ** operating system calls for the specified lock.
25903   */
25904   if( eFileLock==SHARED_LOCK ){
25905     int lrc1, lrc2, lrc1Errno = 0;
25906     long lk, mask;
25907     
25908     assert( pInode->nShared==0 );
25909     assert( pInode->eFileLock==0 );
25910         
25911     mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
25912     /* Now get the read-lock SHARED_LOCK */
25913     /* note that the quality of the randomness doesn't matter that much */
25914     lk = random(); 
25915     pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
25916     lrc1 = afpSetLock(context->dbPath, pFile, 
25917           SHARED_FIRST+pInode->sharedByte, 1, 1);
25918     if( IS_LOCK_ERROR(lrc1) ){
25919       lrc1Errno = pFile->lastErrno;
25920     }
25921     /* Drop the temporary PENDING lock */
25922     lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
25923     
25924     if( IS_LOCK_ERROR(lrc1) ) {
25925       pFile->lastErrno = lrc1Errno;
25926       rc = lrc1;
25927       goto afp_end_lock;
25928     } else if( IS_LOCK_ERROR(lrc2) ){
25929       rc = lrc2;
25930       goto afp_end_lock;
25931     } else if( lrc1 != SQLITE_OK ) {
25932       rc = lrc1;
25933     } else {
25934       pFile->eFileLock = SHARED_LOCK;
25935       pInode->nLock++;
25936       pInode->nShared = 1;
25937     }
25938   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
25939     /* We are trying for an exclusive lock but another thread in this
25940      ** same process is still holding a shared lock. */
25941     rc = SQLITE_BUSY;
25942   }else{
25943     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
25944     ** assumed that there is a SHARED or greater lock on the file
25945     ** already.
25946     */
25947     int failed = 0;
25948     assert( 0!=pFile->eFileLock );
25949     if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
25950         /* Acquire a RESERVED lock */
25951         failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
25952       if( !failed ){
25953         context->reserved = 1;
25954       }
25955     }
25956     if (!failed && eFileLock == EXCLUSIVE_LOCK) {
25957       /* Acquire an EXCLUSIVE lock */
25958         
25959       /* Remove the shared lock before trying the range.  we'll need to 
25960       ** reestablish the shared lock if we can't get the  afpUnlock
25961       */
25962       if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
25963                          pInode->sharedByte, 1, 0)) ){
25964         int failed2 = SQLITE_OK;
25965         /* now attemmpt to get the exclusive lock range */
25966         failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST, 
25967                                SHARED_SIZE, 1);
25968         if( failed && (failed2 = afpSetLock(context->dbPath, pFile, 
25969                        SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
25970           /* Can't reestablish the shared lock.  Sqlite can't deal, this is
25971           ** a critical I/O error
25972           */
25973           rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 : 
25974                SQLITE_IOERR_LOCK;
25975           goto afp_end_lock;
25976         } 
25977       }else{
25978         rc = failed; 
25979       }
25980     }
25981     if( failed ){
25982       rc = failed;
25983     }
25984   }
25985   
25986   if( rc==SQLITE_OK ){
25987     pFile->eFileLock = eFileLock;
25988     pInode->eFileLock = eFileLock;
25989   }else if( eFileLock==EXCLUSIVE_LOCK ){
25990     pFile->eFileLock = PENDING_LOCK;
25991     pInode->eFileLock = PENDING_LOCK;
25992   }
25993   
25994 afp_end_lock:
25995   unixLeaveMutex();
25996   OSTRACE(("LOCK    %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock), 
25997          rc==SQLITE_OK ? "ok" : "failed"));
25998   return rc;
25999 }
26000
26001 /*
26002 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
26003 ** must be either NO_LOCK or SHARED_LOCK.
26004 **
26005 ** If the locking level of the file descriptor is already at or below
26006 ** the requested locking level, this routine is a no-op.
26007 */
26008 static int afpUnlock(sqlite3_file *id, int eFileLock) {
26009   int rc = SQLITE_OK;
26010   unixFile *pFile = (unixFile*)id;
26011   unixInodeInfo *pInode;
26012   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
26013   int skipShared = 0;
26014 #ifdef SQLITE_TEST
26015   int h = pFile->h;
26016 #endif
26017
26018   assert( pFile );
26019   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
26020            pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
26021            getpid()));
26022
26023   assert( eFileLock<=SHARED_LOCK );
26024   if( pFile->eFileLock<=eFileLock ){
26025     return SQLITE_OK;
26026   }
26027   unixEnterMutex();
26028   pInode = pFile->pInode;
26029   assert( pInode->nShared!=0 );
26030   if( pFile->eFileLock>SHARED_LOCK ){
26031     assert( pInode->eFileLock==pFile->eFileLock );
26032     SimulateIOErrorBenign(1);
26033     SimulateIOError( h=(-1) )
26034     SimulateIOErrorBenign(0);
26035     
26036 #ifdef SQLITE_DEBUG
26037     /* When reducing a lock such that other processes can start
26038     ** reading the database file again, make sure that the
26039     ** transaction counter was updated if any part of the database
26040     ** file changed.  If the transaction counter is not updated,
26041     ** other connections to the same file might not realize that
26042     ** the file has changed and hence might not know to flush their
26043     ** cache.  The use of a stale cache can lead to database corruption.
26044     */
26045     assert( pFile->inNormalWrite==0
26046            || pFile->dbUpdate==0
26047            || pFile->transCntrChng==1 );
26048     pFile->inNormalWrite = 0;
26049 #endif
26050     
26051     if( pFile->eFileLock==EXCLUSIVE_LOCK ){
26052       rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
26053       if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
26054         /* only re-establish the shared lock if necessary */
26055         int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
26056         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
26057       } else {
26058         skipShared = 1;
26059       }
26060     }
26061     if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
26062       rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
26063     } 
26064     if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
26065       rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
26066       if( !rc ){ 
26067         context->reserved = 0; 
26068       }
26069     }
26070     if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
26071       pInode->eFileLock = SHARED_LOCK;
26072     }
26073   }
26074   if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
26075
26076     /* Decrement the shared lock counter.  Release the lock using an
26077     ** OS call only when all threads in this same process have released
26078     ** the lock.
26079     */
26080     unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
26081     pInode->nShared--;
26082     if( pInode->nShared==0 ){
26083       SimulateIOErrorBenign(1);
26084       SimulateIOError( h=(-1) )
26085       SimulateIOErrorBenign(0);
26086       if( !skipShared ){
26087         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
26088       }
26089       if( !rc ){
26090         pInode->eFileLock = NO_LOCK;
26091         pFile->eFileLock = NO_LOCK;
26092       }
26093     }
26094     if( rc==SQLITE_OK ){
26095       pInode->nLock--;
26096       assert( pInode->nLock>=0 );
26097       if( pInode->nLock==0 ){
26098         closePendingFds(pFile);
26099       }
26100     }
26101   }
26102   
26103   unixLeaveMutex();
26104   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
26105   return rc;
26106 }
26107
26108 /*
26109 ** Close a file & cleanup AFP specific locking context 
26110 */
26111 static int afpClose(sqlite3_file *id) {
26112   int rc = SQLITE_OK;
26113   if( id ){
26114     unixFile *pFile = (unixFile*)id;
26115     afpUnlock(id, NO_LOCK);
26116     unixEnterMutex();
26117     if( pFile->pInode && pFile->pInode->nLock ){
26118       /* If there are outstanding locks, do not actually close the file just
26119       ** yet because that would clear those locks.  Instead, add the file
26120       ** descriptor to pInode->aPending.  It will be automatically closed when
26121       ** the last lock is cleared.
26122       */
26123       setPendingFd(pFile);
26124     }
26125     releaseInodeInfo(pFile);
26126     sqlite3_free(pFile->lockingContext);
26127     rc = closeUnixFile(id);
26128     unixLeaveMutex();
26129   }
26130   return rc;
26131 }
26132
26133 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
26134 /*
26135 ** The code above is the AFP lock implementation.  The code is specific
26136 ** to MacOSX and does not work on other unix platforms.  No alternative
26137 ** is available.  If you don't compile for a mac, then the "unix-afp"
26138 ** VFS is not available.
26139 **
26140 ********************* End of the AFP lock implementation **********************
26141 ******************************************************************************/
26142
26143 /******************************************************************************
26144 *************************** Begin NFS Locking ********************************/
26145
26146 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26147 /*
26148  ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
26149  ** must be either NO_LOCK or SHARED_LOCK.
26150  **
26151  ** If the locking level of the file descriptor is already at or below
26152  ** the requested locking level, this routine is a no-op.
26153  */
26154 static int nfsUnlock(sqlite3_file *id, int eFileLock){
26155   return posixUnlock(id, eFileLock, 1);
26156 }
26157
26158 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
26159 /*
26160 ** The code above is the NFS lock implementation.  The code is specific
26161 ** to MacOSX and does not work on other unix platforms.  No alternative
26162 ** is available.  
26163 **
26164 ********************* End of the NFS lock implementation **********************
26165 ******************************************************************************/
26166
26167 /******************************************************************************
26168 **************** Non-locking sqlite3_file methods *****************************
26169 **
26170 ** The next division contains implementations for all methods of the 
26171 ** sqlite3_file object other than the locking methods.  The locking
26172 ** methods were defined in divisions above (one locking method per
26173 ** division).  Those methods that are common to all locking modes
26174 ** are gather together into this division.
26175 */
26176
26177 /*
26178 ** Seek to the offset passed as the second argument, then read cnt 
26179 ** bytes into pBuf. Return the number of bytes actually read.
26180 **
26181 ** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
26182 ** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
26183 ** one system to another.  Since SQLite does not define USE_PREAD
26184 ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
26185 ** See tickets #2741 and #2681.
26186 **
26187 ** To avoid stomping the errno value on a failed read the lastErrno value
26188 ** is set before returning.
26189 */
26190 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
26191   int got;
26192   int prior = 0;
26193 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
26194   i64 newOffset;
26195 #endif
26196   TIMER_START;
26197   assert( cnt==(cnt&0x1ffff) );
26198   cnt &= 0x1ffff;
26199   do{
26200 #if defined(USE_PREAD)
26201     got = osPread(id->h, pBuf, cnt, offset);
26202     SimulateIOError( got = -1 );
26203 #elif defined(USE_PREAD64)
26204     got = osPread64(id->h, pBuf, cnt, offset);
26205     SimulateIOError( got = -1 );
26206 #else
26207     newOffset = lseek(id->h, offset, SEEK_SET);
26208     SimulateIOError( newOffset-- );
26209     if( newOffset!=offset ){
26210       if( newOffset == -1 ){
26211         ((unixFile*)id)->lastErrno = errno;
26212       }else{
26213         ((unixFile*)id)->lastErrno = 0;
26214       }
26215       return -1;
26216     }
26217     got = osRead(id->h, pBuf, cnt);
26218 #endif
26219     if( got==cnt ) break;
26220     if( got<0 ){
26221       if( errno==EINTR ){ got = 1; continue; }
26222       prior = 0;
26223       ((unixFile*)id)->lastErrno = errno;
26224       break;
26225     }else if( got>0 ){
26226       cnt -= got;
26227       offset += got;
26228       prior += got;
26229       pBuf = (void*)(got + (char*)pBuf);
26230     }
26231   }while( got>0 );
26232   TIMER_END;
26233   OSTRACE(("READ    %-3d %5d %7lld %llu\n",
26234             id->h, got+prior, offset-prior, TIMER_ELAPSED));
26235   return got+prior;
26236 }
26237
26238 /*
26239 ** Read data from a file into a buffer.  Return SQLITE_OK if all
26240 ** bytes were read successfully and SQLITE_IOERR if anything goes
26241 ** wrong.
26242 */
26243 static int unixRead(
26244   sqlite3_file *id, 
26245   void *pBuf, 
26246   int amt,
26247   sqlite3_int64 offset
26248 ){
26249   unixFile *pFile = (unixFile *)id;
26250   int got;
26251   assert( id );
26252   assert( offset>=0 );
26253   assert( amt>0 );
26254
26255   /* If this is a database file (not a journal, master-journal or temp
26256   ** file), the bytes in the locking range should never be read or written. */
26257 #if 0
26258   assert( pFile->pUnused==0
26259        || offset>=PENDING_BYTE+512
26260        || offset+amt<=PENDING_BYTE 
26261   );
26262 #endif
26263
26264 #if SQLITE_MAX_MMAP_SIZE>0
26265   /* Deal with as much of this read request as possible by transfering
26266   ** data from the memory mapping using memcpy().  */
26267   if( offset<pFile->mmapSize ){
26268     if( offset+amt <= pFile->mmapSize ){
26269       memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
26270       return SQLITE_OK;
26271     }else{
26272       int nCopy = pFile->mmapSize - offset;
26273       memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
26274       pBuf = &((u8 *)pBuf)[nCopy];
26275       amt -= nCopy;
26276       offset += nCopy;
26277     }
26278   }
26279 #endif
26280
26281   got = seekAndRead(pFile, offset, pBuf, amt);
26282   if( got==amt ){
26283     return SQLITE_OK;
26284   }else if( got<0 ){
26285     /* lastErrno set by seekAndRead */
26286     return SQLITE_IOERR_READ;
26287   }else{
26288     pFile->lastErrno = 0; /* not a system error */
26289     /* Unread parts of the buffer must be zero-filled */
26290     memset(&((char*)pBuf)[got], 0, amt-got);
26291     return SQLITE_IOERR_SHORT_READ;
26292   }
26293 }
26294
26295 /*
26296 ** Attempt to seek the file-descriptor passed as the first argument to
26297 ** absolute offset iOff, then attempt to write nBuf bytes of data from
26298 ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise, 
26299 ** return the actual number of bytes written (which may be less than
26300 ** nBuf).
26301 */
26302 static int seekAndWriteFd(
26303   int fd,                         /* File descriptor to write to */
26304   i64 iOff,                       /* File offset to begin writing at */
26305   const void *pBuf,               /* Copy data from this buffer to the file */
26306   int nBuf,                       /* Size of buffer pBuf in bytes */
26307   int *piErrno                    /* OUT: Error number if error occurs */
26308 ){
26309   int rc = 0;                     /* Value returned by system call */
26310
26311   assert( nBuf==(nBuf&0x1ffff) );
26312   nBuf &= 0x1ffff;
26313   TIMER_START;
26314
26315 #if defined(USE_PREAD)
26316   do{ rc = osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
26317 #elif defined(USE_PREAD64)
26318   do{ rc = osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
26319 #else
26320   do{
26321     i64 iSeek = lseek(fd, iOff, SEEK_SET);
26322     SimulateIOError( iSeek-- );
26323
26324     if( iSeek!=iOff ){
26325       if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0);
26326       return -1;
26327     }
26328     rc = osWrite(fd, pBuf, nBuf);
26329   }while( rc<0 && errno==EINTR );
26330 #endif
26331
26332   TIMER_END;
26333   OSTRACE(("WRITE   %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
26334
26335   if( rc<0 && piErrno ) *piErrno = errno;
26336   return rc;
26337 }
26338
26339
26340 /*
26341 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
26342 ** Return the number of bytes actually read.  Update the offset.
26343 **
26344 ** To avoid stomping the errno value on a failed write the lastErrno value
26345 ** is set before returning.
26346 */
26347 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
26348   return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
26349 }
26350
26351
26352 /*
26353 ** Write data from a buffer into a file.  Return SQLITE_OK on success
26354 ** or some other error code on failure.
26355 */
26356 static int unixWrite(
26357   sqlite3_file *id, 
26358   const void *pBuf, 
26359   int amt,
26360   sqlite3_int64 offset 
26361 ){
26362   unixFile *pFile = (unixFile*)id;
26363   int wrote = 0;
26364   assert( id );
26365   assert( amt>0 );
26366
26367   /* If this is a database file (not a journal, master-journal or temp
26368   ** file), the bytes in the locking range should never be read or written. */
26369 #if 0
26370   assert( pFile->pUnused==0
26371        || offset>=PENDING_BYTE+512
26372        || offset+amt<=PENDING_BYTE 
26373   );
26374 #endif
26375
26376 #ifdef SQLITE_DEBUG
26377   /* If we are doing a normal write to a database file (as opposed to
26378   ** doing a hot-journal rollback or a write to some file other than a
26379   ** normal database file) then record the fact that the database
26380   ** has changed.  If the transaction counter is modified, record that
26381   ** fact too.
26382   */
26383   if( pFile->inNormalWrite ){
26384     pFile->dbUpdate = 1;  /* The database has been modified */
26385     if( offset<=24 && offset+amt>=27 ){
26386       int rc;
26387       char oldCntr[4];
26388       SimulateIOErrorBenign(1);
26389       rc = seekAndRead(pFile, 24, oldCntr, 4);
26390       SimulateIOErrorBenign(0);
26391       if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
26392         pFile->transCntrChng = 1;  /* The transaction counter has changed */
26393       }
26394     }
26395   }
26396 #endif
26397
26398 #if SQLITE_MAX_MMAP_SIZE>0
26399   /* Deal with as much of this write request as possible by transfering
26400   ** data from the memory mapping using memcpy().  */
26401   if( offset<pFile->mmapSize ){
26402     if( offset+amt <= pFile->mmapSize ){
26403       memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
26404       return SQLITE_OK;
26405     }else{
26406       int nCopy = pFile->mmapSize - offset;
26407       memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
26408       pBuf = &((u8 *)pBuf)[nCopy];
26409       amt -= nCopy;
26410       offset += nCopy;
26411     }
26412   }
26413 #endif
26414
26415   while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
26416     amt -= wrote;
26417     offset += wrote;
26418     pBuf = &((char*)pBuf)[wrote];
26419   }
26420   SimulateIOError(( wrote=(-1), amt=1 ));
26421   SimulateDiskfullError(( wrote=0, amt=1 ));
26422
26423   if( amt>0 ){
26424     if( wrote<0 && pFile->lastErrno!=ENOSPC ){
26425       /* lastErrno set by seekAndWrite */
26426       return SQLITE_IOERR_WRITE;
26427     }else{
26428       pFile->lastErrno = 0; /* not a system error */
26429       return SQLITE_FULL;
26430     }
26431   }
26432
26433   return SQLITE_OK;
26434 }
26435
26436 #ifdef SQLITE_TEST
26437 /*
26438 ** Count the number of fullsyncs and normal syncs.  This is used to test
26439 ** that syncs and fullsyncs are occurring at the right times.
26440 */
26441 SQLITE_API int sqlite3_sync_count = 0;
26442 SQLITE_API int sqlite3_fullsync_count = 0;
26443 #endif
26444
26445 /*
26446 ** We do not trust systems to provide a working fdatasync().  Some do.
26447 ** Others do no.  To be safe, we will stick with the (slightly slower)
26448 ** fsync(). If you know that your system does support fdatasync() correctly,
26449 ** then simply compile with -Dfdatasync=fdatasync
26450 */
26451 #if !defined(fdatasync)
26452 # define fdatasync fsync
26453 #endif
26454
26455 /*
26456 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
26457 ** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
26458 ** only available on Mac OS X.  But that could change.
26459 */
26460 #ifdef F_FULLFSYNC
26461 # define HAVE_FULLFSYNC 1
26462 #else
26463 # define HAVE_FULLFSYNC 0
26464 #endif
26465
26466
26467 /*
26468 ** The fsync() system call does not work as advertised on many
26469 ** unix systems.  The following procedure is an attempt to make
26470 ** it work better.
26471 **
26472 ** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
26473 ** for testing when we want to run through the test suite quickly.
26474 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
26475 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
26476 ** or power failure will likely corrupt the database file.
26477 **
26478 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
26479 ** The idea behind dataOnly is that it should only write the file content
26480 ** to disk, not the inode.  We only set dataOnly if the file size is 
26481 ** unchanged since the file size is part of the inode.  However, 
26482 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
26483 ** file size has changed.  The only real difference between fdatasync()
26484 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
26485 ** inode if the mtime or owner or other inode attributes have changed.
26486 ** We only care about the file size, not the other file attributes, so
26487 ** as far as SQLite is concerned, an fdatasync() is always adequate.
26488 ** So, we always use fdatasync() if it is available, regardless of
26489 ** the value of the dataOnly flag.
26490 */
26491 static int full_fsync(int fd, int fullSync, int dataOnly){
26492   int rc;
26493
26494   /* The following "ifdef/elif/else/" block has the same structure as
26495   ** the one below. It is replicated here solely to avoid cluttering 
26496   ** up the real code with the UNUSED_PARAMETER() macros.
26497   */
26498 #ifdef SQLITE_NO_SYNC
26499   UNUSED_PARAMETER(fd);
26500   UNUSED_PARAMETER(fullSync);
26501   UNUSED_PARAMETER(dataOnly);
26502 #elif HAVE_FULLFSYNC
26503   UNUSED_PARAMETER(dataOnly);
26504 #else
26505   UNUSED_PARAMETER(fullSync);
26506   UNUSED_PARAMETER(dataOnly);
26507 #endif
26508
26509   /* Record the number of times that we do a normal fsync() and 
26510   ** FULLSYNC.  This is used during testing to verify that this procedure
26511   ** gets called with the correct arguments.
26512   */
26513 #ifdef SQLITE_TEST
26514   if( fullSync ) sqlite3_fullsync_count++;
26515   sqlite3_sync_count++;
26516 #endif
26517
26518   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
26519   ** no-op
26520   */
26521 #ifdef SQLITE_NO_SYNC
26522   rc = SQLITE_OK;
26523 #elif HAVE_FULLFSYNC
26524   if( fullSync ){
26525     rc = osFcntl(fd, F_FULLFSYNC, 0);
26526   }else{
26527     rc = 1;
26528   }
26529   /* If the FULLFSYNC failed, fall back to attempting an fsync().
26530   ** It shouldn't be possible for fullfsync to fail on the local 
26531   ** file system (on OSX), so failure indicates that FULLFSYNC
26532   ** isn't supported for this file system. So, attempt an fsync 
26533   ** and (for now) ignore the overhead of a superfluous fcntl call.  
26534   ** It'd be better to detect fullfsync support once and avoid 
26535   ** the fcntl call every time sync is called.
26536   */
26537   if( rc ) rc = fsync(fd);
26538
26539 #elif defined(__APPLE__)
26540   /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
26541   ** so currently we default to the macro that redefines fdatasync to fsync
26542   */
26543   rc = fsync(fd);
26544 #else 
26545   rc = fdatasync(fd);
26546 #if OS_VXWORKS
26547   if( rc==-1 && errno==ENOTSUP ){
26548     rc = fsync(fd);
26549   }
26550 #endif /* OS_VXWORKS */
26551 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
26552
26553   if( OS_VXWORKS && rc!= -1 ){
26554     rc = 0;
26555   }
26556   return rc;
26557 }
26558
26559 /*
26560 ** Open a file descriptor to the directory containing file zFilename.
26561 ** If successful, *pFd is set to the opened file descriptor and
26562 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
26563 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
26564 ** value.
26565 **
26566 ** The directory file descriptor is used for only one thing - to
26567 ** fsync() a directory to make sure file creation and deletion events
26568 ** are flushed to disk.  Such fsyncs are not needed on newer
26569 ** journaling filesystems, but are required on older filesystems.
26570 **
26571 ** This routine can be overridden using the xSetSysCall interface.
26572 ** The ability to override this routine was added in support of the
26573 ** chromium sandbox.  Opening a directory is a security risk (we are
26574 ** told) so making it overrideable allows the chromium sandbox to
26575 ** replace this routine with a harmless no-op.  To make this routine
26576 ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
26577 ** *pFd set to a negative number.
26578 **
26579 ** If SQLITE_OK is returned, the caller is responsible for closing
26580 ** the file descriptor *pFd using close().
26581 */
26582 static int openDirectory(const char *zFilename, int *pFd){
26583   int ii;
26584   int fd = -1;
26585   char zDirname[MAX_PATHNAME+1];
26586
26587   sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
26588   for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
26589   if( ii>0 ){
26590     zDirname[ii] = '\0';
26591     fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
26592     if( fd>=0 ){
26593       OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
26594     }
26595   }
26596   *pFd = fd;
26597   return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
26598 }
26599
26600 /*
26601 ** Make sure all writes to a particular file are committed to disk.
26602 **
26603 ** If dataOnly==0 then both the file itself and its metadata (file
26604 ** size, access time, etc) are synced.  If dataOnly!=0 then only the
26605 ** file data is synced.
26606 **
26607 ** Under Unix, also make sure that the directory entry for the file
26608 ** has been created by fsync-ing the directory that contains the file.
26609 ** If we do not do this and we encounter a power failure, the directory
26610 ** entry for the journal might not exist after we reboot.  The next
26611 ** SQLite to access the file will not know that the journal exists (because
26612 ** the directory entry for the journal was never created) and the transaction
26613 ** will not roll back - possibly leading to database corruption.
26614 */
26615 static int unixSync(sqlite3_file *id, int flags){
26616   int rc;
26617   unixFile *pFile = (unixFile*)id;
26618
26619   int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
26620   int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
26621
26622   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
26623   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
26624       || (flags&0x0F)==SQLITE_SYNC_FULL
26625   );
26626
26627   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
26628   ** line is to test that doing so does not cause any problems.
26629   */
26630   SimulateDiskfullError( return SQLITE_FULL );
26631
26632   assert( pFile );
26633   OSTRACE(("SYNC    %-3d\n", pFile->h));
26634   rc = full_fsync(pFile->h, isFullsync, isDataOnly);
26635   SimulateIOError( rc=1 );
26636   if( rc ){
26637     pFile->lastErrno = errno;
26638     return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
26639   }
26640
26641   /* Also fsync the directory containing the file if the DIRSYNC flag
26642   ** is set.  This is a one-time occurrence.  Many systems (examples: AIX)
26643   ** are unable to fsync a directory, so ignore errors on the fsync.
26644   */
26645   if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
26646     int dirfd;
26647     OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
26648             HAVE_FULLFSYNC, isFullsync));
26649     rc = osOpenDirectory(pFile->zPath, &dirfd);
26650     if( rc==SQLITE_OK && dirfd>=0 ){
26651       full_fsync(dirfd, 0, 0);
26652       robust_close(pFile, dirfd, __LINE__);
26653     }else if( rc==SQLITE_CANTOPEN ){
26654       rc = SQLITE_OK;
26655     }
26656     pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
26657   }
26658   return rc;
26659 }
26660
26661 /*
26662 ** Truncate an open file to a specified size
26663 */
26664 static int unixTruncate(sqlite3_file *id, i64 nByte){
26665   unixFile *pFile = (unixFile *)id;
26666   int rc;
26667   assert( pFile );
26668   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
26669
26670   /* If the user has configured a chunk-size for this file, truncate the
26671   ** file so that it consists of an integer number of chunks (i.e. the
26672   ** actual file size after the operation may be larger than the requested
26673   ** size).
26674   */
26675   if( pFile->szChunk>0 ){
26676     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
26677   }
26678
26679   rc = robust_ftruncate(pFile->h, (off_t)nByte);
26680   if( rc ){
26681     pFile->lastErrno = errno;
26682     return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
26683   }else{
26684 #ifdef SQLITE_DEBUG
26685     /* If we are doing a normal write to a database file (as opposed to
26686     ** doing a hot-journal rollback or a write to some file other than a
26687     ** normal database file) and we truncate the file to zero length,
26688     ** that effectively updates the change counter.  This might happen
26689     ** when restoring a database using the backup API from a zero-length
26690     ** source.
26691     */
26692     if( pFile->inNormalWrite && nByte==0 ){
26693       pFile->transCntrChng = 1;
26694     }
26695 #endif
26696
26697     /* If the file was just truncated to a size smaller than the currently
26698     ** mapped region, reduce the effective mapping size as well. SQLite will
26699     ** use read() and write() to access data beyond this point from now on.  
26700     */
26701     if( nByte<pFile->mmapSize ){
26702       pFile->mmapSize = nByte;
26703     }
26704
26705     return SQLITE_OK;
26706   }
26707 }
26708
26709 /*
26710 ** Determine the current size of a file in bytes
26711 */
26712 static int unixFileSize(sqlite3_file *id, i64 *pSize){
26713   int rc;
26714   struct stat buf;
26715   assert( id );
26716   rc = osFstat(((unixFile*)id)->h, &buf);
26717   SimulateIOError( rc=1 );
26718   if( rc!=0 ){
26719     ((unixFile*)id)->lastErrno = errno;
26720     return SQLITE_IOERR_FSTAT;
26721   }
26722   *pSize = buf.st_size;
26723
26724   /* When opening a zero-size database, the findInodeInfo() procedure
26725   ** writes a single byte into that file in order to work around a bug
26726   ** in the OS-X msdos filesystem.  In order to avoid problems with upper
26727   ** layers, we need to report this file size as zero even though it is
26728   ** really 1.   Ticket #3260.
26729   */
26730   if( *pSize==1 ) *pSize = 0;
26731
26732
26733   return SQLITE_OK;
26734 }
26735
26736 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
26737 /*
26738 ** Handler for proxy-locking file-control verbs.  Defined below in the
26739 ** proxying locking division.
26740 */
26741 static int proxyFileControl(sqlite3_file*,int,void*);
26742 #endif
26743
26744 /* 
26745 ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT 
26746 ** file-control operation.  Enlarge the database to nBytes in size
26747 ** (rounded up to the next chunk-size).  If the database is already
26748 ** nBytes or larger, this routine is a no-op.
26749 */
26750 static int fcntlSizeHint(unixFile *pFile, i64 nByte){
26751   if( pFile->szChunk>0 ){
26752     i64 nSize;                    /* Required file size */
26753     struct stat buf;              /* Used to hold return values of fstat() */
26754    
26755     if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
26756
26757     nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
26758     if( nSize>(i64)buf.st_size ){
26759
26760 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
26761       /* The code below is handling the return value of osFallocate() 
26762       ** correctly. posix_fallocate() is defined to "returns zero on success, 
26763       ** or an error number on  failure". See the manpage for details. */
26764       int err;
26765       do{
26766         err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
26767       }while( err==EINTR );
26768       if( err ) return SQLITE_IOERR_WRITE;
26769 #else
26770       /* If the OS does not have posix_fallocate(), fake it. First use
26771       ** ftruncate() to set the file size, then write a single byte to
26772       ** the last byte in each block within the extended region. This
26773       ** is the same technique used by glibc to implement posix_fallocate()
26774       ** on systems that do not have a real fallocate() system call.
26775       */
26776       int nBlk = buf.st_blksize;  /* File-system block size */
26777       i64 iWrite;                 /* Next offset to write to */
26778
26779       if( robust_ftruncate(pFile->h, nSize) ){
26780         pFile->lastErrno = errno;
26781         return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
26782       }
26783       iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
26784       while( iWrite<nSize ){
26785         int nWrite = seekAndWrite(pFile, iWrite, "", 1);
26786         if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
26787         iWrite += nBlk;
26788       }
26789 #endif
26790     }
26791   }
26792
26793   if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
26794     int rc;
26795     if( pFile->szChunk<=0 ){
26796       if( robust_ftruncate(pFile->h, nByte) ){
26797         pFile->lastErrno = errno;
26798         return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
26799       }
26800     }
26801
26802     rc = unixMapfile(pFile, nByte);
26803     return rc;
26804   }
26805
26806   return SQLITE_OK;
26807 }
26808
26809 /*
26810 ** If *pArg is inititially negative then this is a query.  Set *pArg to
26811 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
26812 **
26813 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
26814 */
26815 static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
26816   if( *pArg<0 ){
26817     *pArg = (pFile->ctrlFlags & mask)!=0;
26818   }else if( (*pArg)==0 ){
26819     pFile->ctrlFlags &= ~mask;
26820   }else{
26821     pFile->ctrlFlags |= mask;
26822   }
26823 }
26824
26825 /* Forward declaration */
26826 static int unixGetTempname(int nBuf, char *zBuf);
26827
26828 /*
26829 ** Information and control of an open file handle.
26830 */
26831 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
26832   unixFile *pFile = (unixFile*)id;
26833   switch( op ){
26834     case SQLITE_FCNTL_LOCKSTATE: {
26835       *(int*)pArg = pFile->eFileLock;
26836       return SQLITE_OK;
26837     }
26838     case SQLITE_LAST_ERRNO: {
26839       *(int*)pArg = pFile->lastErrno;
26840       return SQLITE_OK;
26841     }
26842     case SQLITE_FCNTL_CHUNK_SIZE: {
26843       pFile->szChunk = *(int *)pArg;
26844       return SQLITE_OK;
26845     }
26846     case SQLITE_FCNTL_SIZE_HINT: {
26847       int rc;
26848       SimulateIOErrorBenign(1);
26849       rc = fcntlSizeHint(pFile, *(i64 *)pArg);
26850       SimulateIOErrorBenign(0);
26851       return rc;
26852     }
26853     case SQLITE_FCNTL_PERSIST_WAL: {
26854       unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
26855       return SQLITE_OK;
26856     }
26857     case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
26858       unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
26859       return SQLITE_OK;
26860     }
26861     case SQLITE_FCNTL_VFSNAME: {
26862       *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
26863       return SQLITE_OK;
26864     }
26865     case SQLITE_FCNTL_TEMPFILENAME: {
26866       char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
26867       if( zTFile ){
26868         unixGetTempname(pFile->pVfs->mxPathname, zTFile);
26869         *(char**)pArg = zTFile;
26870       }
26871       return SQLITE_OK;
26872     }
26873     case SQLITE_FCNTL_MMAP_SIZE: {
26874       i64 newLimit = *(i64*)pArg;
26875       if( newLimit>sqlite3GlobalConfig.mxMmap ){
26876         newLimit = sqlite3GlobalConfig.mxMmap;
26877       }
26878       *(i64*)pArg = pFile->mmapSizeMax;
26879       if( newLimit>=0 ){
26880         pFile->mmapSizeMax = newLimit;
26881         if( newLimit<pFile->mmapSize ) pFile->mmapSize = newLimit;
26882       }
26883       return SQLITE_OK;
26884     }
26885 #ifdef SQLITE_DEBUG
26886     /* The pager calls this method to signal that it has done
26887     ** a rollback and that the database is therefore unchanged and
26888     ** it hence it is OK for the transaction change counter to be
26889     ** unchanged.
26890     */
26891     case SQLITE_FCNTL_DB_UNCHANGED: {
26892       ((unixFile*)id)->dbUpdate = 0;
26893       return SQLITE_OK;
26894     }
26895 #endif
26896 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
26897     case SQLITE_SET_LOCKPROXYFILE:
26898     case SQLITE_GET_LOCKPROXYFILE: {
26899       return proxyFileControl(id,op,pArg);
26900     }
26901 #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
26902   }
26903   return SQLITE_NOTFOUND;
26904 }
26905
26906 /*
26907 ** Return the sector size in bytes of the underlying block device for
26908 ** the specified file. This is almost always 512 bytes, but may be
26909 ** larger for some devices.
26910 **
26911 ** SQLite code assumes this function cannot fail. It also assumes that
26912 ** if two files are created in the same file-system directory (i.e.
26913 ** a database and its journal file) that the sector size will be the
26914 ** same for both.
26915 */
26916 #ifndef __QNXNTO__ 
26917 static int unixSectorSize(sqlite3_file *NotUsed){
26918   UNUSED_PARAMETER(NotUsed);
26919   return SQLITE_DEFAULT_SECTOR_SIZE;
26920 }
26921 #endif
26922
26923 /*
26924 ** The following version of unixSectorSize() is optimized for QNX.
26925 */
26926 #ifdef __QNXNTO__
26927 #include <sys/dcmd_blk.h>
26928 #include <sys/statvfs.h>
26929 static int unixSectorSize(sqlite3_file *id){
26930   unixFile *pFile = (unixFile*)id;
26931   if( pFile->sectorSize == 0 ){
26932     struct statvfs fsInfo;
26933        
26934     /* Set defaults for non-supported filesystems */
26935     pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
26936     pFile->deviceCharacteristics = 0;
26937     if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
26938       return pFile->sectorSize;
26939     }
26940
26941     if( !strcmp(fsInfo.f_basetype, "tmp") ) {
26942       pFile->sectorSize = fsInfo.f_bsize;
26943       pFile->deviceCharacteristics =
26944         SQLITE_IOCAP_ATOMIC4K |       /* All ram filesystem writes are atomic */
26945         SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
26946                                       ** the write succeeds */
26947         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
26948                                       ** so it is ordered */
26949         0;
26950     }else if( strstr(fsInfo.f_basetype, "etfs") ){
26951       pFile->sectorSize = fsInfo.f_bsize;
26952       pFile->deviceCharacteristics =
26953         /* etfs cluster size writes are atomic */
26954         (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
26955         SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
26956                                       ** the write succeeds */
26957         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
26958                                       ** so it is ordered */
26959         0;
26960     }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
26961       pFile->sectorSize = fsInfo.f_bsize;
26962       pFile->deviceCharacteristics =
26963         SQLITE_IOCAP_ATOMIC |         /* All filesystem writes are atomic */
26964         SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
26965                                       ** the write succeeds */
26966         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
26967                                       ** so it is ordered */
26968         0;
26969     }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
26970       pFile->sectorSize = fsInfo.f_bsize;
26971       pFile->deviceCharacteristics =
26972         /* full bitset of atomics from max sector size and smaller */
26973         ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
26974         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
26975                                       ** so it is ordered */
26976         0;
26977     }else if( strstr(fsInfo.f_basetype, "dos") ){
26978       pFile->sectorSize = fsInfo.f_bsize;
26979       pFile->deviceCharacteristics =
26980         /* full bitset of atomics from max sector size and smaller */
26981         ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
26982         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
26983                                       ** so it is ordered */
26984         0;
26985     }else{
26986       pFile->deviceCharacteristics =
26987         SQLITE_IOCAP_ATOMIC512 |      /* blocks are atomic */
26988         SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
26989                                       ** the write succeeds */
26990         0;
26991     }
26992   }
26993   /* Last chance verification.  If the sector size isn't a multiple of 512
26994   ** then it isn't valid.*/
26995   if( pFile->sectorSize % 512 != 0 ){
26996     pFile->deviceCharacteristics = 0;
26997     pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
26998   }
26999   return pFile->sectorSize;
27000 }
27001 #endif /* __QNXNTO__ */
27002
27003 /*
27004 ** Return the device characteristics for the file.
27005 **
27006 ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
27007 ** However, that choice is contraversial since technically the underlying
27008 ** file system does not always provide powersafe overwrites.  (In other
27009 ** words, after a power-loss event, parts of the file that were never
27010 ** written might end up being altered.)  However, non-PSOW behavior is very,
27011 ** very rare.  And asserting PSOW makes a large reduction in the amount
27012 ** of required I/O for journaling, since a lot of padding is eliminated.
27013 **  Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
27014 ** available to turn it off and URI query parameter available to turn it off.
27015 */
27016 static int unixDeviceCharacteristics(sqlite3_file *id){
27017   unixFile *p = (unixFile*)id;
27018   int rc = 0;
27019 #ifdef __QNXNTO__
27020   if( p->sectorSize==0 ) unixSectorSize(id);
27021   rc = p->deviceCharacteristics;
27022 #endif
27023   if( p->ctrlFlags & UNIXFILE_PSOW ){
27024     rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
27025   }
27026   return rc;
27027 }
27028
27029 #ifndef SQLITE_OMIT_WAL
27030
27031
27032 /*
27033 ** Object used to represent an shared memory buffer.  
27034 **
27035 ** When multiple threads all reference the same wal-index, each thread
27036 ** has its own unixShm object, but they all point to a single instance
27037 ** of this unixShmNode object.  In other words, each wal-index is opened
27038 ** only once per process.
27039 **
27040 ** Each unixShmNode object is connected to a single unixInodeInfo object.
27041 ** We could coalesce this object into unixInodeInfo, but that would mean
27042 ** every open file that does not use shared memory (in other words, most
27043 ** open files) would have to carry around this extra information.  So
27044 ** the unixInodeInfo object contains a pointer to this unixShmNode object
27045 ** and the unixShmNode object is created only when needed.
27046 **
27047 ** unixMutexHeld() must be true when creating or destroying
27048 ** this object or while reading or writing the following fields:
27049 **
27050 **      nRef
27051 **
27052 ** The following fields are read-only after the object is created:
27053 ** 
27054 **      fid
27055 **      zFilename
27056 **
27057 ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
27058 ** unixMutexHeld() is true when reading or writing any other field
27059 ** in this structure.
27060 */
27061 struct unixShmNode {
27062   unixInodeInfo *pInode;     /* unixInodeInfo that owns this SHM node */
27063   sqlite3_mutex *mutex;      /* Mutex to access this object */
27064   char *zFilename;           /* Name of the mmapped file */
27065   int h;                     /* Open file descriptor */
27066   int szRegion;              /* Size of shared-memory regions */
27067   u16 nRegion;               /* Size of array apRegion */
27068   u8 isReadonly;             /* True if read-only */
27069   char **apRegion;           /* Array of mapped shared-memory regions */
27070   int nRef;                  /* Number of unixShm objects pointing to this */
27071   unixShm *pFirst;           /* All unixShm objects pointing to this */
27072 #ifdef SQLITE_DEBUG
27073   u8 exclMask;               /* Mask of exclusive locks held */
27074   u8 sharedMask;             /* Mask of shared locks held */
27075   u8 nextShmId;              /* Next available unixShm.id value */
27076 #endif
27077 };
27078
27079 /*
27080 ** Structure used internally by this VFS to record the state of an
27081 ** open shared memory connection.
27082 **
27083 ** The following fields are initialized when this object is created and
27084 ** are read-only thereafter:
27085 **
27086 **    unixShm.pFile
27087 **    unixShm.id
27088 **
27089 ** All other fields are read/write.  The unixShm.pFile->mutex must be held
27090 ** while accessing any read/write fields.
27091 */
27092 struct unixShm {
27093   unixShmNode *pShmNode;     /* The underlying unixShmNode object */
27094   unixShm *pNext;            /* Next unixShm with the same unixShmNode */
27095   u8 hasMutex;               /* True if holding the unixShmNode mutex */
27096   u8 id;                     /* Id of this connection within its unixShmNode */
27097   u16 sharedMask;            /* Mask of shared locks held */
27098   u16 exclMask;              /* Mask of exclusive locks held */
27099 };
27100
27101 /*
27102 ** Constants used for locking
27103 */
27104 #define UNIX_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)         /* first lock byte */
27105 #define UNIX_SHM_DMS    (UNIX_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
27106
27107 /*
27108 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
27109 **
27110 ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
27111 ** otherwise.
27112 */
27113 static int unixShmSystemLock(
27114   unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
27115   int lockType,          /* F_UNLCK, F_RDLCK, or F_WRLCK */
27116   int ofst,              /* First byte of the locking range */
27117   int n                  /* Number of bytes to lock */
27118 ){
27119   struct flock f;       /* The posix advisory locking structure */
27120   int rc = SQLITE_OK;   /* Result code form fcntl() */
27121
27122   /* Access to the unixShmNode object is serialized by the caller */
27123   assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
27124
27125   /* Shared locks never span more than one byte */
27126   assert( n==1 || lockType!=F_RDLCK );
27127
27128   /* Locks are within range */
27129   assert( n>=1 && n<SQLITE_SHM_NLOCK );
27130
27131   if( pShmNode->h>=0 ){
27132     /* Initialize the locking parameters */
27133     memset(&f, 0, sizeof(f));
27134     f.l_type = lockType;
27135     f.l_whence = SEEK_SET;
27136     f.l_start = ofst;
27137     f.l_len = n;
27138
27139     rc = osFcntl(pShmNode->h, F_SETLK, &f);
27140     rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
27141   }
27142
27143   /* Update the global lock state and do debug tracing */
27144 #ifdef SQLITE_DEBUG
27145   { u16 mask;
27146   OSTRACE(("SHM-LOCK "));
27147   mask = (1<<(ofst+n)) - (1<<ofst);
27148   if( rc==SQLITE_OK ){
27149     if( lockType==F_UNLCK ){
27150       OSTRACE(("unlock %d ok", ofst));
27151       pShmNode->exclMask &= ~mask;
27152       pShmNode->sharedMask &= ~mask;
27153     }else if( lockType==F_RDLCK ){
27154       OSTRACE(("read-lock %d ok", ofst));
27155       pShmNode->exclMask &= ~mask;
27156       pShmNode->sharedMask |= mask;
27157     }else{
27158       assert( lockType==F_WRLCK );
27159       OSTRACE(("write-lock %d ok", ofst));
27160       pShmNode->exclMask |= mask;
27161       pShmNode->sharedMask &= ~mask;
27162     }
27163   }else{
27164     if( lockType==F_UNLCK ){
27165       OSTRACE(("unlock %d failed", ofst));
27166     }else if( lockType==F_RDLCK ){
27167       OSTRACE(("read-lock failed"));
27168     }else{
27169       assert( lockType==F_WRLCK );
27170       OSTRACE(("write-lock %d failed", ofst));
27171     }
27172   }
27173   OSTRACE((" - afterwards %03x,%03x\n",
27174            pShmNode->sharedMask, pShmNode->exclMask));
27175   }
27176 #endif
27177
27178   return rc;        
27179 }
27180
27181
27182 /*
27183 ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
27184 **
27185 ** This is not a VFS shared-memory method; it is a utility function called
27186 ** by VFS shared-memory methods.
27187 */
27188 static void unixShmPurge(unixFile *pFd){
27189   unixShmNode *p = pFd->pInode->pShmNode;
27190   assert( unixMutexHeld() );
27191   if( p && p->nRef==0 ){
27192     int i;
27193     assert( p->pInode==pFd->pInode );
27194     sqlite3_mutex_free(p->mutex);
27195     for(i=0; i<p->nRegion; i++){
27196       if( p->h>=0 ){
27197         osMunmap(p->apRegion[i], p->szRegion);
27198       }else{
27199         sqlite3_free(p->apRegion[i]);
27200       }
27201     }
27202     sqlite3_free(p->apRegion);
27203     if( p->h>=0 ){
27204       robust_close(pFd, p->h, __LINE__);
27205       p->h = -1;
27206     }
27207     p->pInode->pShmNode = 0;
27208     sqlite3_free(p);
27209   }
27210 }
27211
27212 /*
27213 ** Open a shared-memory area associated with open database file pDbFd.  
27214 ** This particular implementation uses mmapped files.
27215 **
27216 ** The file used to implement shared-memory is in the same directory
27217 ** as the open database file and has the same name as the open database
27218 ** file with the "-shm" suffix added.  For example, if the database file
27219 ** is "/home/user1/config.db" then the file that is created and mmapped
27220 ** for shared memory will be called "/home/user1/config.db-shm".  
27221 **
27222 ** Another approach to is to use files in /dev/shm or /dev/tmp or an
27223 ** some other tmpfs mount. But if a file in a different directory
27224 ** from the database file is used, then differing access permissions
27225 ** or a chroot() might cause two different processes on the same
27226 ** database to end up using different files for shared memory - 
27227 ** meaning that their memory would not really be shared - resulting
27228 ** in database corruption.  Nevertheless, this tmpfs file usage
27229 ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
27230 ** or the equivalent.  The use of the SQLITE_SHM_DIRECTORY compile-time
27231 ** option results in an incompatible build of SQLite;  builds of SQLite
27232 ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
27233 ** same database file at the same time, database corruption will likely
27234 ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
27235 ** "unsupported" and may go away in a future SQLite release.
27236 **
27237 ** When opening a new shared-memory file, if no other instances of that
27238 ** file are currently open, in this process or in other processes, then
27239 ** the file must be truncated to zero length or have its header cleared.
27240 **
27241 ** If the original database file (pDbFd) is using the "unix-excl" VFS
27242 ** that means that an exclusive lock is held on the database file and
27243 ** that no other processes are able to read or write the database.  In
27244 ** that case, we do not really need shared memory.  No shared memory
27245 ** file is created.  The shared memory will be simulated with heap memory.
27246 */
27247 static int unixOpenSharedMemory(unixFile *pDbFd){
27248   struct unixShm *p = 0;          /* The connection to be opened */
27249   struct unixShmNode *pShmNode;   /* The underlying mmapped file */
27250   int rc;                         /* Result code */
27251   unixInodeInfo *pInode;          /* The inode of fd */
27252   char *zShmFilename;             /* Name of the file used for SHM */
27253   int nShmFilename;               /* Size of the SHM filename in bytes */
27254
27255   /* Allocate space for the new unixShm object. */
27256   p = sqlite3_malloc( sizeof(*p) );
27257   if( p==0 ) return SQLITE_NOMEM;
27258   memset(p, 0, sizeof(*p));
27259   assert( pDbFd->pShm==0 );
27260
27261   /* Check to see if a unixShmNode object already exists. Reuse an existing
27262   ** one if present. Create a new one if necessary.
27263   */
27264   unixEnterMutex();
27265   pInode = pDbFd->pInode;
27266   pShmNode = pInode->pShmNode;
27267   if( pShmNode==0 ){
27268     struct stat sStat;                 /* fstat() info for database file */
27269
27270     /* Call fstat() to figure out the permissions on the database file. If
27271     ** a new *-shm file is created, an attempt will be made to create it
27272     ** with the same permissions.
27273     */
27274     if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
27275       rc = SQLITE_IOERR_FSTAT;
27276       goto shm_open_err;
27277     }
27278
27279 #ifdef SQLITE_SHM_DIRECTORY
27280     nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
27281 #else
27282     nShmFilename = 6 + (int)strlen(pDbFd->zPath);
27283 #endif
27284     pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
27285     if( pShmNode==0 ){
27286       rc = SQLITE_NOMEM;
27287       goto shm_open_err;
27288     }
27289     memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
27290     zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
27291 #ifdef SQLITE_SHM_DIRECTORY
27292     sqlite3_snprintf(nShmFilename, zShmFilename, 
27293                      SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
27294                      (u32)sStat.st_ino, (u32)sStat.st_dev);
27295 #else
27296     sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
27297     sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
27298 #endif
27299     pShmNode->h = -1;
27300     pDbFd->pInode->pShmNode = pShmNode;
27301     pShmNode->pInode = pDbFd->pInode;
27302     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
27303     if( pShmNode->mutex==0 ){
27304       rc = SQLITE_NOMEM;
27305       goto shm_open_err;
27306     }
27307
27308     if( pInode->bProcessLock==0 ){
27309       int openFlags = O_RDWR | O_CREAT;
27310       if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
27311         openFlags = O_RDONLY;
27312         pShmNode->isReadonly = 1;
27313       }
27314       pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
27315       if( pShmNode->h<0 ){
27316         rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
27317         goto shm_open_err;
27318       }
27319
27320       /* If this process is running as root, make sure that the SHM file
27321       ** is owned by the same user that owns the original database.  Otherwise,
27322       ** the original owner will not be able to connect.
27323       */
27324       osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
27325   
27326       /* Check to see if another process is holding the dead-man switch.
27327       ** If not, truncate the file to zero length. 
27328       */
27329       rc = SQLITE_OK;
27330       if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
27331         if( robust_ftruncate(pShmNode->h, 0) ){
27332           rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
27333         }
27334       }
27335       if( rc==SQLITE_OK ){
27336         rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
27337       }
27338       if( rc ) goto shm_open_err;
27339     }
27340   }
27341
27342   /* Make the new connection a child of the unixShmNode */
27343   p->pShmNode = pShmNode;
27344 #ifdef SQLITE_DEBUG
27345   p->id = pShmNode->nextShmId++;
27346 #endif
27347   pShmNode->nRef++;
27348   pDbFd->pShm = p;
27349   unixLeaveMutex();
27350
27351   /* The reference count on pShmNode has already been incremented under
27352   ** the cover of the unixEnterMutex() mutex and the pointer from the
27353   ** new (struct unixShm) object to the pShmNode has been set. All that is
27354   ** left to do is to link the new object into the linked list starting
27355   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex 
27356   ** mutex.
27357   */
27358   sqlite3_mutex_enter(pShmNode->mutex);
27359   p->pNext = pShmNode->pFirst;
27360   pShmNode->pFirst = p;
27361   sqlite3_mutex_leave(pShmNode->mutex);
27362   return SQLITE_OK;
27363
27364   /* Jump here on any error */
27365 shm_open_err:
27366   unixShmPurge(pDbFd);       /* This call frees pShmNode if required */
27367   sqlite3_free(p);
27368   unixLeaveMutex();
27369   return rc;
27370 }
27371
27372 /*
27373 ** This function is called to obtain a pointer to region iRegion of the 
27374 ** shared-memory associated with the database file fd. Shared-memory regions 
27375 ** are numbered starting from zero. Each shared-memory region is szRegion 
27376 ** bytes in size.
27377 **
27378 ** If an error occurs, an error code is returned and *pp is set to NULL.
27379 **
27380 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
27381 ** region has not been allocated (by any client, including one running in a
27382 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If 
27383 ** bExtend is non-zero and the requested shared-memory region has not yet 
27384 ** been allocated, it is allocated by this function.
27385 **
27386 ** If the shared-memory region has already been allocated or is allocated by
27387 ** this call as described above, then it is mapped into this processes 
27388 ** address space (if it is not already), *pp is set to point to the mapped 
27389 ** memory and SQLITE_OK returned.
27390 */
27391 static int unixShmMap(
27392   sqlite3_file *fd,               /* Handle open on database file */
27393   int iRegion,                    /* Region to retrieve */
27394   int szRegion,                   /* Size of regions */
27395   int bExtend,                    /* True to extend file if necessary */
27396   void volatile **pp              /* OUT: Mapped memory */
27397 ){
27398   unixFile *pDbFd = (unixFile*)fd;
27399   unixShm *p;
27400   unixShmNode *pShmNode;
27401   int rc = SQLITE_OK;
27402
27403   /* If the shared-memory file has not yet been opened, open it now. */
27404   if( pDbFd->pShm==0 ){
27405     rc = unixOpenSharedMemory(pDbFd);
27406     if( rc!=SQLITE_OK ) return rc;
27407   }
27408
27409   p = pDbFd->pShm;
27410   pShmNode = p->pShmNode;
27411   sqlite3_mutex_enter(pShmNode->mutex);
27412   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
27413   assert( pShmNode->pInode==pDbFd->pInode );
27414   assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
27415   assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
27416
27417   if( pShmNode->nRegion<=iRegion ){
27418     char **apNew;                      /* New apRegion[] array */
27419     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
27420     struct stat sStat;                 /* Used by fstat() */
27421
27422     pShmNode->szRegion = szRegion;
27423
27424     if( pShmNode->h>=0 ){
27425       /* The requested region is not mapped into this processes address space.
27426       ** Check to see if it has been allocated (i.e. if the wal-index file is
27427       ** large enough to contain the requested region).
27428       */
27429       if( osFstat(pShmNode->h, &sStat) ){
27430         rc = SQLITE_IOERR_SHMSIZE;
27431         goto shmpage_out;
27432       }
27433   
27434       if( sStat.st_size<nByte ){
27435         /* The requested memory region does not exist. If bExtend is set to
27436         ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
27437         */
27438         if( !bExtend ){
27439           goto shmpage_out;
27440         }
27441
27442         /* Alternatively, if bExtend is true, extend the file. Do this by
27443         ** writing a single byte to the end of each (OS) page being
27444         ** allocated or extended. Technically, we need only write to the
27445         ** last page in order to extend the file. But writing to all new
27446         ** pages forces the OS to allocate them immediately, which reduces
27447         ** the chances of SIGBUS while accessing the mapped region later on.
27448         */
27449         else{
27450           static const int pgsz = 4096;
27451           int iPg;
27452
27453           /* Write to the last byte of each newly allocated or extended page */
27454           assert( (nByte % pgsz)==0 );
27455           for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
27456             if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, 0)!=1 ){
27457               const char *zFile = pShmNode->zFilename;
27458               rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
27459               goto shmpage_out;
27460             }
27461           }
27462         }
27463       }
27464     }
27465
27466     /* Map the requested memory region into this processes address space. */
27467     apNew = (char **)sqlite3_realloc(
27468         pShmNode->apRegion, (iRegion+1)*sizeof(char *)
27469     );
27470     if( !apNew ){
27471       rc = SQLITE_IOERR_NOMEM;
27472       goto shmpage_out;
27473     }
27474     pShmNode->apRegion = apNew;
27475     while(pShmNode->nRegion<=iRegion){
27476       void *pMem;
27477       if( pShmNode->h>=0 ){
27478         pMem = osMmap(0, szRegion,
27479             pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE, 
27480             MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
27481         );
27482         if( pMem==MAP_FAILED ){
27483           rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
27484           goto shmpage_out;
27485         }
27486       }else{
27487         pMem = sqlite3_malloc(szRegion);
27488         if( pMem==0 ){
27489           rc = SQLITE_NOMEM;
27490           goto shmpage_out;
27491         }
27492         memset(pMem, 0, szRegion);
27493       }
27494       pShmNode->apRegion[pShmNode->nRegion] = pMem;
27495       pShmNode->nRegion++;
27496     }
27497   }
27498
27499 shmpage_out:
27500   if( pShmNode->nRegion>iRegion ){
27501     *pp = pShmNode->apRegion[iRegion];
27502   }else{
27503     *pp = 0;
27504   }
27505   if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
27506   sqlite3_mutex_leave(pShmNode->mutex);
27507   return rc;
27508 }
27509
27510 /*
27511 ** Change the lock state for a shared-memory segment.
27512 **
27513 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
27514 ** different here than in posix.  In xShmLock(), one can go from unlocked
27515 ** to shared and back or from unlocked to exclusive and back.  But one may
27516 ** not go from shared to exclusive or from exclusive to shared.
27517 */
27518 static int unixShmLock(
27519   sqlite3_file *fd,          /* Database file holding the shared memory */
27520   int ofst,                  /* First lock to acquire or release */
27521   int n,                     /* Number of locks to acquire or release */
27522   int flags                  /* What to do with the lock */
27523 ){
27524   unixFile *pDbFd = (unixFile*)fd;      /* Connection holding shared memory */
27525   unixShm *p = pDbFd->pShm;             /* The shared memory being locked */
27526   unixShm *pX;                          /* For looping over all siblings */
27527   unixShmNode *pShmNode = p->pShmNode;  /* The underlying file iNode */
27528   int rc = SQLITE_OK;                   /* Result code */
27529   u16 mask;                             /* Mask of locks to take or release */
27530
27531   assert( pShmNode==pDbFd->pInode->pShmNode );
27532   assert( pShmNode->pInode==pDbFd->pInode );
27533   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
27534   assert( n>=1 );
27535   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
27536        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
27537        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
27538        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
27539   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
27540   assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
27541   assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
27542
27543   mask = (1<<(ofst+n)) - (1<<ofst);
27544   assert( n>1 || mask==(1<<ofst) );
27545   sqlite3_mutex_enter(pShmNode->mutex);
27546   if( flags & SQLITE_SHM_UNLOCK ){
27547     u16 allMask = 0; /* Mask of locks held by siblings */
27548
27549     /* See if any siblings hold this same lock */
27550     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
27551       if( pX==p ) continue;
27552       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
27553       allMask |= pX->sharedMask;
27554     }
27555
27556     /* Unlock the system-level locks */
27557     if( (mask & allMask)==0 ){
27558       rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
27559     }else{
27560       rc = SQLITE_OK;
27561     }
27562
27563     /* Undo the local locks */
27564     if( rc==SQLITE_OK ){
27565       p->exclMask &= ~mask;
27566       p->sharedMask &= ~mask;
27567     } 
27568   }else if( flags & SQLITE_SHM_SHARED ){
27569     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
27570
27571     /* Find out which shared locks are already held by sibling connections.
27572     ** If any sibling already holds an exclusive lock, go ahead and return
27573     ** SQLITE_BUSY.
27574     */
27575     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
27576       if( (pX->exclMask & mask)!=0 ){
27577         rc = SQLITE_BUSY;
27578         break;
27579       }
27580       allShared |= pX->sharedMask;
27581     }
27582
27583     /* Get shared locks at the system level, if necessary */
27584     if( rc==SQLITE_OK ){
27585       if( (allShared & mask)==0 ){
27586         rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
27587       }else{
27588         rc = SQLITE_OK;
27589       }
27590     }
27591
27592     /* Get the local shared locks */
27593     if( rc==SQLITE_OK ){
27594       p->sharedMask |= mask;
27595     }
27596   }else{
27597     /* Make sure no sibling connections hold locks that will block this
27598     ** lock.  If any do, return SQLITE_BUSY right away.
27599     */
27600     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
27601       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
27602         rc = SQLITE_BUSY;
27603         break;
27604       }
27605     }
27606   
27607     /* Get the exclusive locks at the system level.  Then if successful
27608     ** also mark the local connection as being locked.
27609     */
27610     if( rc==SQLITE_OK ){
27611       rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
27612       if( rc==SQLITE_OK ){
27613         assert( (p->sharedMask & mask)==0 );
27614         p->exclMask |= mask;
27615       }
27616     }
27617   }
27618   sqlite3_mutex_leave(pShmNode->mutex);
27619   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
27620            p->id, getpid(), p->sharedMask, p->exclMask));
27621   return rc;
27622 }
27623
27624 /*
27625 ** Implement a memory barrier or memory fence on shared memory.  
27626 **
27627 ** All loads and stores begun before the barrier must complete before
27628 ** any load or store begun after the barrier.
27629 */
27630 static void unixShmBarrier(
27631   sqlite3_file *fd                /* Database file holding the shared memory */
27632 ){
27633   UNUSED_PARAMETER(fd);
27634   unixEnterMutex();
27635   unixLeaveMutex();
27636 }
27637
27638 /*
27639 ** Close a connection to shared-memory.  Delete the underlying 
27640 ** storage if deleteFlag is true.
27641 **
27642 ** If there is no shared memory associated with the connection then this
27643 ** routine is a harmless no-op.
27644 */
27645 static int unixShmUnmap(
27646   sqlite3_file *fd,               /* The underlying database file */
27647   int deleteFlag                  /* Delete shared-memory if true */
27648 ){
27649   unixShm *p;                     /* The connection to be closed */
27650   unixShmNode *pShmNode;          /* The underlying shared-memory file */
27651   unixShm **pp;                   /* For looping over sibling connections */
27652   unixFile *pDbFd;                /* The underlying database file */
27653
27654   pDbFd = (unixFile*)fd;
27655   p = pDbFd->pShm;
27656   if( p==0 ) return SQLITE_OK;
27657   pShmNode = p->pShmNode;
27658
27659   assert( pShmNode==pDbFd->pInode->pShmNode );
27660   assert( pShmNode->pInode==pDbFd->pInode );
27661
27662   /* Remove connection p from the set of connections associated
27663   ** with pShmNode */
27664   sqlite3_mutex_enter(pShmNode->mutex);
27665   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
27666   *pp = p->pNext;
27667
27668   /* Free the connection p */
27669   sqlite3_free(p);
27670   pDbFd->pShm = 0;
27671   sqlite3_mutex_leave(pShmNode->mutex);
27672
27673   /* If pShmNode->nRef has reached 0, then close the underlying
27674   ** shared-memory file, too */
27675   unixEnterMutex();
27676   assert( pShmNode->nRef>0 );
27677   pShmNode->nRef--;
27678   if( pShmNode->nRef==0 ){
27679     if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
27680     unixShmPurge(pDbFd);
27681   }
27682   unixLeaveMutex();
27683
27684   return SQLITE_OK;
27685 }
27686
27687
27688 #else
27689 # define unixShmMap     0
27690 # define unixShmLock    0
27691 # define unixShmBarrier 0
27692 # define unixShmUnmap   0
27693 #endif /* #ifndef SQLITE_OMIT_WAL */
27694
27695 /*
27696 ** If it is currently memory mapped, unmap file pFd.
27697 */
27698 static void unixUnmapfile(unixFile *pFd){
27699   assert( pFd->nFetchOut==0 );
27700 #if SQLITE_MAX_MMAP_SIZE>0
27701   if( pFd->pMapRegion ){
27702     osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
27703     pFd->pMapRegion = 0;
27704     pFd->mmapSize = 0;
27705     pFd->mmapSizeActual = 0;
27706   }
27707 #endif
27708 }
27709
27710 #if SQLITE_MAX_MMAP_SIZE>0
27711 /*
27712 ** Return the system page size.
27713 */
27714 static int unixGetPagesize(void){
27715 #if HAVE_MREMAP
27716   return 512;
27717 #elif defined(_BSD_SOURCE)
27718   return getpagesize();
27719 #else
27720   return (int)sysconf(_SC_PAGESIZE);
27721 #endif
27722 }
27723 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
27724
27725 #if SQLITE_MAX_MMAP_SIZE>0
27726 /*
27727 ** Attempt to set the size of the memory mapping maintained by file 
27728 ** descriptor pFd to nNew bytes. Any existing mapping is discarded.
27729 **
27730 ** If successful, this function sets the following variables:
27731 **
27732 **       unixFile.pMapRegion
27733 **       unixFile.mmapSize
27734 **       unixFile.mmapSizeActual
27735 **
27736 ** If unsuccessful, an error message is logged via sqlite3_log() and
27737 ** the three variables above are zeroed. In this case SQLite should
27738 ** continue accessing the database using the xRead() and xWrite()
27739 ** methods.
27740 */
27741 static void unixRemapfile(
27742   unixFile *pFd,                  /* File descriptor object */
27743   i64 nNew                        /* Required mapping size */
27744 ){
27745   const char *zErr = "mmap";
27746   int h = pFd->h;                      /* File descriptor open on db file */
27747   u8 *pOrig = (u8 *)pFd->pMapRegion;   /* Pointer to current file mapping */
27748   i64 nOrig = pFd->mmapSizeActual;     /* Size of pOrig region in bytes */
27749   u8 *pNew = 0;                        /* Location of new mapping */
27750   int flags = PROT_READ;               /* Flags to pass to mmap() */
27751
27752   assert( pFd->nFetchOut==0 );
27753   assert( nNew>pFd->mmapSize );
27754   assert( nNew<=pFd->mmapSizeMax );
27755   assert( nNew>0 );
27756   assert( pFd->mmapSizeActual>=pFd->mmapSize );
27757   assert( MAP_FAILED!=0 );
27758
27759   if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
27760
27761   if( pOrig ){
27762     const int szSyspage = unixGetPagesize();
27763     i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
27764     u8 *pReq = &pOrig[nReuse];
27765
27766     /* Unmap any pages of the existing mapping that cannot be reused. */
27767     if( nReuse!=nOrig ){
27768       osMunmap(pReq, nOrig-nReuse);
27769     }
27770
27771 #if HAVE_MREMAP
27772     pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
27773     zErr = "mremap";
27774 #else
27775     pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
27776     if( pNew!=MAP_FAILED ){
27777       if( pNew!=pReq ){
27778         osMunmap(pNew, nNew - nReuse);
27779         pNew = 0;
27780       }else{
27781         pNew = pOrig;
27782       }
27783     }
27784 #endif
27785
27786     /* The attempt to extend the existing mapping failed. Free it. */
27787     if( pNew==MAP_FAILED || pNew==0 ){
27788       osMunmap(pOrig, nReuse);
27789     }
27790   }
27791
27792   /* If pNew is still NULL, try to create an entirely new mapping. */
27793   if( pNew==0 ){
27794     pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
27795   }
27796
27797   if( pNew==MAP_FAILED ){
27798     pNew = 0;
27799     nNew = 0;
27800     unixLogError(SQLITE_OK, zErr, pFd->zPath);
27801
27802     /* If the mmap() above failed, assume that all subsequent mmap() calls
27803     ** will probably fail too. Fall back to using xRead/xWrite exclusively
27804     ** in this case.  */
27805     pFd->mmapSizeMax = 0;
27806   }
27807   pFd->pMapRegion = (void *)pNew;
27808   pFd->mmapSize = pFd->mmapSizeActual = nNew;
27809 }
27810 #endif
27811
27812 /*
27813 ** Memory map or remap the file opened by file-descriptor pFd (if the file
27814 ** is already mapped, the existing mapping is replaced by the new). Or, if 
27815 ** there already exists a mapping for this file, and there are still 
27816 ** outstanding xFetch() references to it, this function is a no-op.
27817 **
27818 ** If parameter nByte is non-negative, then it is the requested size of 
27819 ** the mapping to create. Otherwise, if nByte is less than zero, then the 
27820 ** requested size is the size of the file on disk. The actual size of the
27821 ** created mapping is either the requested size or the value configured 
27822 ** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
27823 **
27824 ** SQLITE_OK is returned if no error occurs (even if the mapping is not
27825 ** recreated as a result of outstanding references) or an SQLite error
27826 ** code otherwise.
27827 */
27828 static int unixMapfile(unixFile *pFd, i64 nByte){
27829 #if SQLITE_MAX_MMAP_SIZE>0
27830   i64 nMap = nByte;
27831   int rc;
27832
27833   assert( nMap>=0 || pFd->nFetchOut==0 );
27834   if( pFd->nFetchOut>0 ) return SQLITE_OK;
27835
27836   if( nMap<0 ){
27837     struct stat statbuf;          /* Low-level file information */
27838     rc = osFstat(pFd->h, &statbuf);
27839     if( rc!=SQLITE_OK ){
27840       return SQLITE_IOERR_FSTAT;
27841     }
27842     nMap = statbuf.st_size;
27843   }
27844   if( nMap>pFd->mmapSizeMax ){
27845     nMap = pFd->mmapSizeMax;
27846   }
27847
27848   if( nMap!=pFd->mmapSize ){
27849     if( nMap>0 ){
27850       unixRemapfile(pFd, nMap);
27851     }else{
27852       unixUnmapfile(pFd);
27853     }
27854   }
27855 #endif
27856
27857   return SQLITE_OK;
27858 }
27859
27860 /*
27861 ** If possible, return a pointer to a mapping of file fd starting at offset
27862 ** iOff. The mapping must be valid for at least nAmt bytes.
27863 **
27864 ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
27865 ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
27866 ** Finally, if an error does occur, return an SQLite error code. The final
27867 ** value of *pp is undefined in this case.
27868 **
27869 ** If this function does return a pointer, the caller must eventually 
27870 ** release the reference by calling unixUnfetch().
27871 */
27872 static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
27873 #if SQLITE_MAX_MMAP_SIZE>0
27874   unixFile *pFd = (unixFile *)fd;   /* The underlying database file */
27875 #endif
27876   *pp = 0;
27877
27878 #if SQLITE_MAX_MMAP_SIZE>0
27879   if( pFd->mmapSizeMax>0 ){
27880     if( pFd->pMapRegion==0 ){
27881       int rc = unixMapfile(pFd, -1);
27882       if( rc!=SQLITE_OK ) return rc;
27883     }
27884     if( pFd->mmapSize >= iOff+nAmt ){
27885       *pp = &((u8 *)pFd->pMapRegion)[iOff];
27886       pFd->nFetchOut++;
27887     }
27888   }
27889 #endif
27890   return SQLITE_OK;
27891 }
27892
27893 /*
27894 ** If the third argument is non-NULL, then this function releases a 
27895 ** reference obtained by an earlier call to unixFetch(). The second
27896 ** argument passed to this function must be the same as the corresponding
27897 ** argument that was passed to the unixFetch() invocation. 
27898 **
27899 ** Or, if the third argument is NULL, then this function is being called 
27900 ** to inform the VFS layer that, according to POSIX, any existing mapping 
27901 ** may now be invalid and should be unmapped.
27902 */
27903 static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
27904   unixFile *pFd = (unixFile *)fd;   /* The underlying database file */
27905   UNUSED_PARAMETER(iOff);
27906
27907   /* If p==0 (unmap the entire file) then there must be no outstanding 
27908   ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
27909   ** then there must be at least one outstanding.  */
27910   assert( (p==0)==(pFd->nFetchOut==0) );
27911
27912   /* If p!=0, it must match the iOff value. */
27913   assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
27914
27915   if( p ){
27916     pFd->nFetchOut--;
27917   }else{
27918     unixUnmapfile(pFd);
27919   }
27920
27921   assert( pFd->nFetchOut>=0 );
27922   return SQLITE_OK;
27923 }
27924
27925 /*
27926 ** Here ends the implementation of all sqlite3_file methods.
27927 **
27928 ********************** End sqlite3_file Methods *******************************
27929 ******************************************************************************/
27930
27931 /*
27932 ** This division contains definitions of sqlite3_io_methods objects that
27933 ** implement various file locking strategies.  It also contains definitions
27934 ** of "finder" functions.  A finder-function is used to locate the appropriate
27935 ** sqlite3_io_methods object for a particular database file.  The pAppData
27936 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
27937 ** the correct finder-function for that VFS.
27938 **
27939 ** Most finder functions return a pointer to a fixed sqlite3_io_methods
27940 ** object.  The only interesting finder-function is autolockIoFinder, which
27941 ** looks at the filesystem type and tries to guess the best locking
27942 ** strategy from that.
27943 **
27944 ** For finder-funtion F, two objects are created:
27945 **
27946 **    (1) The real finder-function named "FImpt()".
27947 **
27948 **    (2) A constant pointer to this function named just "F".
27949 **
27950 **
27951 ** A pointer to the F pointer is used as the pAppData value for VFS
27952 ** objects.  We have to do this instead of letting pAppData point
27953 ** directly at the finder-function since C90 rules prevent a void*
27954 ** from be cast into a function pointer.
27955 **
27956 **
27957 ** Each instance of this macro generates two objects:
27958 **
27959 **   *  A constant sqlite3_io_methods object call METHOD that has locking
27960 **      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
27961 **
27962 **   *  An I/O method finder function called FINDER that returns a pointer
27963 **      to the METHOD object in the previous bullet.
27964 */
27965 #define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK)      \
27966 static const sqlite3_io_methods METHOD = {                                   \
27967    VERSION,                    /* iVersion */                                \
27968    CLOSE,                      /* xClose */                                  \
27969    unixRead,                   /* xRead */                                   \
27970    unixWrite,                  /* xWrite */                                  \
27971    unixTruncate,               /* xTruncate */                               \
27972    unixSync,                   /* xSync */                                   \
27973    unixFileSize,               /* xFileSize */                               \
27974    LOCK,                       /* xLock */                                   \
27975    UNLOCK,                     /* xUnlock */                                 \
27976    CKLOCK,                     /* xCheckReservedLock */                      \
27977    unixFileControl,            /* xFileControl */                            \
27978    unixSectorSize,             /* xSectorSize */                             \
27979    unixDeviceCharacteristics,  /* xDeviceCapabilities */                     \
27980    unixShmMap,                 /* xShmMap */                                 \
27981    unixShmLock,                /* xShmLock */                                \
27982    unixShmBarrier,             /* xShmBarrier */                             \
27983    unixShmUnmap,               /* xShmUnmap */                               \
27984    unixFetch,                  /* xFetch */                                  \
27985    unixUnfetch,                /* xUnfetch */                                \
27986 };                                                                           \
27987 static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
27988   UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
27989   return &METHOD;                                                            \
27990 }                                                                            \
27991 static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
27992     = FINDER##Impl;
27993
27994 /*
27995 ** Here are all of the sqlite3_io_methods objects for each of the
27996 ** locking strategies.  Functions that return pointers to these methods
27997 ** are also created.
27998 */
27999 IOMETHODS(
28000   posixIoFinder,            /* Finder function name */
28001   posixIoMethods,           /* sqlite3_io_methods object name */
28002   3,                        /* shared memory and mmap are enabled */
28003   unixClose,                /* xClose method */
28004   unixLock,                 /* xLock method */
28005   unixUnlock,               /* xUnlock method */
28006   unixCheckReservedLock     /* xCheckReservedLock method */
28007 )
28008 IOMETHODS(
28009   nolockIoFinder,           /* Finder function name */
28010   nolockIoMethods,          /* sqlite3_io_methods object name */
28011   1,                        /* shared memory is disabled */
28012   nolockClose,              /* xClose method */
28013   nolockLock,               /* xLock method */
28014   nolockUnlock,             /* xUnlock method */
28015   nolockCheckReservedLock   /* xCheckReservedLock method */
28016 )
28017 IOMETHODS(
28018   dotlockIoFinder,          /* Finder function name */
28019   dotlockIoMethods,         /* sqlite3_io_methods object name */
28020   1,                        /* shared memory is disabled */
28021   dotlockClose,             /* xClose method */
28022   dotlockLock,              /* xLock method */
28023   dotlockUnlock,            /* xUnlock method */
28024   dotlockCheckReservedLock  /* xCheckReservedLock method */
28025 )
28026
28027 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
28028 IOMETHODS(
28029   flockIoFinder,            /* Finder function name */
28030   flockIoMethods,           /* sqlite3_io_methods object name */
28031   1,                        /* shared memory is disabled */
28032   flockClose,               /* xClose method */
28033   flockLock,                /* xLock method */
28034   flockUnlock,              /* xUnlock method */
28035   flockCheckReservedLock    /* xCheckReservedLock method */
28036 )
28037 #endif
28038
28039 #if OS_VXWORKS
28040 IOMETHODS(
28041   semIoFinder,              /* Finder function name */
28042   semIoMethods,             /* sqlite3_io_methods object name */
28043   1,                        /* shared memory is disabled */
28044   semClose,                 /* xClose method */
28045   semLock,                  /* xLock method */
28046   semUnlock,                /* xUnlock method */
28047   semCheckReservedLock      /* xCheckReservedLock method */
28048 )
28049 #endif
28050
28051 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28052 IOMETHODS(
28053   afpIoFinder,              /* Finder function name */
28054   afpIoMethods,             /* sqlite3_io_methods object name */
28055   1,                        /* shared memory is disabled */
28056   afpClose,                 /* xClose method */
28057   afpLock,                  /* xLock method */
28058   afpUnlock,                /* xUnlock method */
28059   afpCheckReservedLock      /* xCheckReservedLock method */
28060 )
28061 #endif
28062
28063 /*
28064 ** The proxy locking method is a "super-method" in the sense that it
28065 ** opens secondary file descriptors for the conch and lock files and
28066 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
28067 ** secondary files.  For this reason, the division that implements
28068 ** proxy locking is located much further down in the file.  But we need
28069 ** to go ahead and define the sqlite3_io_methods and finder function
28070 ** for proxy locking here.  So we forward declare the I/O methods.
28071 */
28072 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28073 static int proxyClose(sqlite3_file*);
28074 static int proxyLock(sqlite3_file*, int);
28075 static int proxyUnlock(sqlite3_file*, int);
28076 static int proxyCheckReservedLock(sqlite3_file*, int*);
28077 IOMETHODS(
28078   proxyIoFinder,            /* Finder function name */
28079   proxyIoMethods,           /* sqlite3_io_methods object name */
28080   1,                        /* shared memory is disabled */
28081   proxyClose,               /* xClose method */
28082   proxyLock,                /* xLock method */
28083   proxyUnlock,              /* xUnlock method */
28084   proxyCheckReservedLock    /* xCheckReservedLock method */
28085 )
28086 #endif
28087
28088 /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
28089 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28090 IOMETHODS(
28091   nfsIoFinder,               /* Finder function name */
28092   nfsIoMethods,              /* sqlite3_io_methods object name */
28093   1,                         /* shared memory is disabled */
28094   unixClose,                 /* xClose method */
28095   unixLock,                  /* xLock method */
28096   nfsUnlock,                 /* xUnlock method */
28097   unixCheckReservedLock      /* xCheckReservedLock method */
28098 )
28099 #endif
28100
28101 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28102 /* 
28103 ** This "finder" function attempts to determine the best locking strategy 
28104 ** for the database file "filePath".  It then returns the sqlite3_io_methods
28105 ** object that implements that strategy.
28106 **
28107 ** This is for MacOSX only.
28108 */
28109 static const sqlite3_io_methods *autolockIoFinderImpl(
28110   const char *filePath,    /* name of the database file */
28111   unixFile *pNew           /* open file object for the database file */
28112 ){
28113   static const struct Mapping {
28114     const char *zFilesystem;              /* Filesystem type name */
28115     const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
28116   } aMap[] = {
28117     { "hfs",    &posixIoMethods },
28118     { "ufs",    &posixIoMethods },
28119     { "afpfs",  &afpIoMethods },
28120     { "smbfs",  &afpIoMethods },
28121     { "webdav", &nolockIoMethods },
28122     { 0, 0 }
28123   };
28124   int i;
28125   struct statfs fsInfo;
28126   struct flock lockInfo;
28127
28128   if( !filePath ){
28129     /* If filePath==NULL that means we are dealing with a transient file
28130     ** that does not need to be locked. */
28131     return &nolockIoMethods;
28132   }
28133   if( statfs(filePath, &fsInfo) != -1 ){
28134     if( fsInfo.f_flags & MNT_RDONLY ){
28135       return &nolockIoMethods;
28136     }
28137     for(i=0; aMap[i].zFilesystem; i++){
28138       if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
28139         return aMap[i].pMethods;
28140       }
28141     }
28142   }
28143
28144   /* Default case. Handles, amongst others, "nfs".
28145   ** Test byte-range lock using fcntl(). If the call succeeds, 
28146   ** assume that the file-system supports POSIX style locks. 
28147   */
28148   lockInfo.l_len = 1;
28149   lockInfo.l_start = 0;
28150   lockInfo.l_whence = SEEK_SET;
28151   lockInfo.l_type = F_RDLCK;
28152   if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
28153     if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
28154       return &nfsIoMethods;
28155     } else {
28156       return &posixIoMethods;
28157     }
28158   }else{
28159     return &dotlockIoMethods;
28160   }
28161 }
28162 static const sqlite3_io_methods 
28163   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
28164
28165 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
28166
28167 #if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
28168 /* 
28169 ** This "finder" function attempts to determine the best locking strategy 
28170 ** for the database file "filePath".  It then returns the sqlite3_io_methods
28171 ** object that implements that strategy.
28172 **
28173 ** This is for VXWorks only.
28174 */
28175 static const sqlite3_io_methods *autolockIoFinderImpl(
28176   const char *filePath,    /* name of the database file */
28177   unixFile *pNew           /* the open file object */
28178 ){
28179   struct flock lockInfo;
28180
28181   if( !filePath ){
28182     /* If filePath==NULL that means we are dealing with a transient file
28183     ** that does not need to be locked. */
28184     return &nolockIoMethods;
28185   }
28186
28187   /* Test if fcntl() is supported and use POSIX style locks.
28188   ** Otherwise fall back to the named semaphore method.
28189   */
28190   lockInfo.l_len = 1;
28191   lockInfo.l_start = 0;
28192   lockInfo.l_whence = SEEK_SET;
28193   lockInfo.l_type = F_RDLCK;
28194   if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
28195     return &posixIoMethods;
28196   }else{
28197     return &semIoMethods;
28198   }
28199 }
28200 static const sqlite3_io_methods 
28201   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
28202
28203 #endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
28204
28205 /*
28206 ** An abstract type for a pointer to a IO method finder function:
28207 */
28208 typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
28209
28210
28211 /****************************************************************************
28212 **************************** sqlite3_vfs methods ****************************
28213 **
28214 ** This division contains the implementation of methods on the
28215 ** sqlite3_vfs object.
28216 */
28217
28218 /*
28219 ** Initialize the contents of the unixFile structure pointed to by pId.
28220 */
28221 static int fillInUnixFile(
28222   sqlite3_vfs *pVfs,      /* Pointer to vfs object */
28223   int h,                  /* Open file descriptor of file being opened */
28224   sqlite3_file *pId,      /* Write to the unixFile structure here */
28225   const char *zFilename,  /* Name of the file being opened */
28226   int ctrlFlags           /* Zero or more UNIXFILE_* values */
28227 ){
28228   const sqlite3_io_methods *pLockingStyle;
28229   unixFile *pNew = (unixFile *)pId;
28230   int rc = SQLITE_OK;
28231
28232   assert( pNew->pInode==NULL );
28233
28234   /* Usually the path zFilename should not be a relative pathname. The
28235   ** exception is when opening the proxy "conch" file in builds that
28236   ** include the special Apple locking styles.
28237   */
28238 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28239   assert( zFilename==0 || zFilename[0]=='/' 
28240     || pVfs->pAppData==(void*)&autolockIoFinder );
28241 #else
28242   assert( zFilename==0 || zFilename[0]=='/' );
28243 #endif
28244
28245   /* No locking occurs in temporary files */
28246   assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
28247
28248   OSTRACE(("OPEN    %-3d %s\n", h, zFilename));
28249   pNew->h = h;
28250   pNew->pVfs = pVfs;
28251   pNew->zPath = zFilename;
28252   pNew->ctrlFlags = (u8)ctrlFlags;
28253   pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
28254   if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
28255                            "psow", SQLITE_POWERSAFE_OVERWRITE) ){
28256     pNew->ctrlFlags |= UNIXFILE_PSOW;
28257   }
28258   if( strcmp(pVfs->zName,"unix-excl")==0 ){
28259     pNew->ctrlFlags |= UNIXFILE_EXCL;
28260   }
28261
28262 #if OS_VXWORKS
28263   pNew->pId = vxworksFindFileId(zFilename);
28264   if( pNew->pId==0 ){
28265     ctrlFlags |= UNIXFILE_NOLOCK;
28266     rc = SQLITE_NOMEM;
28267   }
28268 #endif
28269
28270   if( ctrlFlags & UNIXFILE_NOLOCK ){
28271     pLockingStyle = &nolockIoMethods;
28272   }else{
28273     pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
28274 #if SQLITE_ENABLE_LOCKING_STYLE
28275     /* Cache zFilename in the locking context (AFP and dotlock override) for
28276     ** proxyLock activation is possible (remote proxy is based on db name)
28277     ** zFilename remains valid until file is closed, to support */
28278     pNew->lockingContext = (void*)zFilename;
28279 #endif
28280   }
28281
28282   if( pLockingStyle == &posixIoMethods
28283 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28284     || pLockingStyle == &nfsIoMethods
28285 #endif
28286   ){
28287     unixEnterMutex();
28288     rc = findInodeInfo(pNew, &pNew->pInode);
28289     if( rc!=SQLITE_OK ){
28290       /* If an error occurred in findInodeInfo(), close the file descriptor
28291       ** immediately, before releasing the mutex. findInodeInfo() may fail
28292       ** in two scenarios:
28293       **
28294       **   (a) A call to fstat() failed.
28295       **   (b) A malloc failed.
28296       **
28297       ** Scenario (b) may only occur if the process is holding no other
28298       ** file descriptors open on the same file. If there were other file
28299       ** descriptors on this file, then no malloc would be required by
28300       ** findInodeInfo(). If this is the case, it is quite safe to close
28301       ** handle h - as it is guaranteed that no posix locks will be released
28302       ** by doing so.
28303       **
28304       ** If scenario (a) caused the error then things are not so safe. The
28305       ** implicit assumption here is that if fstat() fails, things are in
28306       ** such bad shape that dropping a lock or two doesn't matter much.
28307       */
28308       robust_close(pNew, h, __LINE__);
28309       h = -1;
28310     }
28311     unixLeaveMutex();
28312   }
28313
28314 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
28315   else if( pLockingStyle == &afpIoMethods ){
28316     /* AFP locking uses the file path so it needs to be included in
28317     ** the afpLockingContext.
28318     */
28319     afpLockingContext *pCtx;
28320     pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
28321     if( pCtx==0 ){
28322       rc = SQLITE_NOMEM;
28323     }else{
28324       /* NB: zFilename exists and remains valid until the file is closed
28325       ** according to requirement F11141.  So we do not need to make a
28326       ** copy of the filename. */
28327       pCtx->dbPath = zFilename;
28328       pCtx->reserved = 0;
28329       srandomdev();
28330       unixEnterMutex();
28331       rc = findInodeInfo(pNew, &pNew->pInode);
28332       if( rc!=SQLITE_OK ){
28333         sqlite3_free(pNew->lockingContext);
28334         robust_close(pNew, h, __LINE__);
28335         h = -1;
28336       }
28337       unixLeaveMutex();        
28338     }
28339   }
28340 #endif
28341
28342   else if( pLockingStyle == &dotlockIoMethods ){
28343     /* Dotfile locking uses the file path so it needs to be included in
28344     ** the dotlockLockingContext 
28345     */
28346     char *zLockFile;
28347     int nFilename;
28348     assert( zFilename!=0 );
28349     nFilename = (int)strlen(zFilename) + 6;
28350     zLockFile = (char *)sqlite3_malloc(nFilename);
28351     if( zLockFile==0 ){
28352       rc = SQLITE_NOMEM;
28353     }else{
28354       sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
28355     }
28356     pNew->lockingContext = zLockFile;
28357   }
28358
28359 #if OS_VXWORKS
28360   else if( pLockingStyle == &semIoMethods ){
28361     /* Named semaphore locking uses the file path so it needs to be
28362     ** included in the semLockingContext
28363     */
28364     unixEnterMutex();
28365     rc = findInodeInfo(pNew, &pNew->pInode);
28366     if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
28367       char *zSemName = pNew->pInode->aSemName;
28368       int n;
28369       sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
28370                        pNew->pId->zCanonicalName);
28371       for( n=1; zSemName[n]; n++ )
28372         if( zSemName[n]=='/' ) zSemName[n] = '_';
28373       pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
28374       if( pNew->pInode->pSem == SEM_FAILED ){
28375         rc = SQLITE_NOMEM;
28376         pNew->pInode->aSemName[0] = '\0';
28377       }
28378     }
28379     unixLeaveMutex();
28380   }
28381 #endif
28382   
28383   pNew->lastErrno = 0;
28384 #if OS_VXWORKS
28385   if( rc!=SQLITE_OK ){
28386     if( h>=0 ) robust_close(pNew, h, __LINE__);
28387     h = -1;
28388     osUnlink(zFilename);
28389     pNew->ctrlFlags |= UNIXFILE_DELETE;
28390   }
28391 #endif
28392   if( rc!=SQLITE_OK ){
28393     if( h>=0 ) robust_close(pNew, h, __LINE__);
28394   }else{
28395     pNew->pMethod = pLockingStyle;
28396     OpenCounter(+1);
28397     verifyDbFile(pNew);
28398   }
28399   return rc;
28400 }
28401
28402 /*
28403 ** Return the name of a directory in which to put temporary files.
28404 ** If no suitable temporary file directory can be found, return NULL.
28405 */
28406 static const char *unixTempFileDir(void){
28407   static const char *azDirs[] = {
28408      0,
28409      0,
28410      "/var/tmp",
28411      "/usr/tmp",
28412      "/tmp",
28413      0        /* List terminator */
28414   };
28415   unsigned int i;
28416   struct stat buf;
28417   const char *zDir = 0;
28418
28419   azDirs[0] = sqlite3_temp_directory;
28420   if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
28421   for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
28422     if( zDir==0 ) continue;
28423     if( osStat(zDir, &buf) ) continue;
28424     if( !S_ISDIR(buf.st_mode) ) continue;
28425     if( osAccess(zDir, 07) ) continue;
28426     break;
28427   }
28428   return zDir;
28429 }
28430
28431 /*
28432 ** Create a temporary file name in zBuf.  zBuf must be allocated
28433 ** by the calling process and must be big enough to hold at least
28434 ** pVfs->mxPathname bytes.
28435 */
28436 static int unixGetTempname(int nBuf, char *zBuf){
28437   static const unsigned char zChars[] =
28438     "abcdefghijklmnopqrstuvwxyz"
28439     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
28440     "0123456789";
28441   unsigned int i, j;
28442   const char *zDir;
28443
28444   /* It's odd to simulate an io-error here, but really this is just
28445   ** using the io-error infrastructure to test that SQLite handles this
28446   ** function failing. 
28447   */
28448   SimulateIOError( return SQLITE_IOERR );
28449
28450   zDir = unixTempFileDir();
28451   if( zDir==0 ) zDir = ".";
28452
28453   /* Check that the output buffer is large enough for the temporary file 
28454   ** name. If it is not, return SQLITE_ERROR.
28455   */
28456   if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
28457     return SQLITE_ERROR;
28458   }
28459
28460   do{
28461     sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
28462     j = (int)strlen(zBuf);
28463     sqlite3_randomness(15, &zBuf[j]);
28464     for(i=0; i<15; i++, j++){
28465       zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
28466     }
28467     zBuf[j] = 0;
28468     zBuf[j+1] = 0;
28469   }while( osAccess(zBuf,0)==0 );
28470   return SQLITE_OK;
28471 }
28472
28473 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
28474 /*
28475 ** Routine to transform a unixFile into a proxy-locking unixFile.
28476 ** Implementation in the proxy-lock division, but used by unixOpen()
28477 ** if SQLITE_PREFER_PROXY_LOCKING is defined.
28478 */
28479 static int proxyTransformUnixFile(unixFile*, const char*);
28480 #endif
28481
28482 /*
28483 ** Search for an unused file descriptor that was opened on the database 
28484 ** file (not a journal or master-journal file) identified by pathname
28485 ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
28486 ** argument to this function.
28487 **
28488 ** Such a file descriptor may exist if a database connection was closed
28489 ** but the associated file descriptor could not be closed because some
28490 ** other file descriptor open on the same file is holding a file-lock.
28491 ** Refer to comments in the unixClose() function and the lengthy comment
28492 ** describing "Posix Advisory Locking" at the start of this file for 
28493 ** further details. Also, ticket #4018.
28494 **
28495 ** If a suitable file descriptor is found, then it is returned. If no
28496 ** such file descriptor is located, -1 is returned.
28497 */
28498 static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
28499   UnixUnusedFd *pUnused = 0;
28500
28501   /* Do not search for an unused file descriptor on vxworks. Not because
28502   ** vxworks would not benefit from the change (it might, we're not sure),
28503   ** but because no way to test it is currently available. It is better 
28504   ** not to risk breaking vxworks support for the sake of such an obscure 
28505   ** feature.  */
28506 #if !OS_VXWORKS
28507   struct stat sStat;                   /* Results of stat() call */
28508
28509   /* A stat() call may fail for various reasons. If this happens, it is
28510   ** almost certain that an open() call on the same path will also fail.
28511   ** For this reason, if an error occurs in the stat() call here, it is
28512   ** ignored and -1 is returned. The caller will try to open a new file
28513   ** descriptor on the same path, fail, and return an error to SQLite.
28514   **
28515   ** Even if a subsequent open() call does succeed, the consequences of
28516   ** not searching for a resusable file descriptor are not dire.  */
28517   if( 0==osStat(zPath, &sStat) ){
28518     unixInodeInfo *pInode;
28519
28520     unixEnterMutex();
28521     pInode = inodeList;
28522     while( pInode && (pInode->fileId.dev!=sStat.st_dev
28523                      || pInode->fileId.ino!=sStat.st_ino) ){
28524        pInode = pInode->pNext;
28525     }
28526     if( pInode ){
28527       UnixUnusedFd **pp;
28528       for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
28529       pUnused = *pp;
28530       if( pUnused ){
28531         *pp = pUnused->pNext;
28532       }
28533     }
28534     unixLeaveMutex();
28535   }
28536 #endif    /* if !OS_VXWORKS */
28537   return pUnused;
28538 }
28539
28540 /*
28541 ** This function is called by unixOpen() to determine the unix permissions
28542 ** to create new files with. If no error occurs, then SQLITE_OK is returned
28543 ** and a value suitable for passing as the third argument to open(2) is
28544 ** written to *pMode. If an IO error occurs, an SQLite error code is 
28545 ** returned and the value of *pMode is not modified.
28546 **
28547 ** In most cases cases, this routine sets *pMode to 0, which will become
28548 ** an indication to robust_open() to create the file using
28549 ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
28550 ** But if the file being opened is a WAL or regular journal file, then 
28551 ** this function queries the file-system for the permissions on the 
28552 ** corresponding database file and sets *pMode to this value. Whenever 
28553 ** possible, WAL and journal files are created using the same permissions 
28554 ** as the associated database file.
28555 **
28556 ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
28557 ** original filename is unavailable.  But 8_3_NAMES is only used for
28558 ** FAT filesystems and permissions do not matter there, so just use
28559 ** the default permissions.
28560 */
28561 static int findCreateFileMode(
28562   const char *zPath,              /* Path of file (possibly) being created */
28563   int flags,                      /* Flags passed as 4th argument to xOpen() */
28564   mode_t *pMode,                  /* OUT: Permissions to open file with */
28565   uid_t *pUid,                    /* OUT: uid to set on the file */
28566   gid_t *pGid                     /* OUT: gid to set on the file */
28567 ){
28568   int rc = SQLITE_OK;             /* Return Code */
28569   *pMode = 0;
28570   *pUid = 0;
28571   *pGid = 0;
28572   if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
28573     char zDb[MAX_PATHNAME+1];     /* Database file path */
28574     int nDb;                      /* Number of valid bytes in zDb */
28575     struct stat sStat;            /* Output of stat() on database file */
28576
28577     /* zPath is a path to a WAL or journal file. The following block derives
28578     ** the path to the associated database file from zPath. This block handles
28579     ** the following naming conventions:
28580     **
28581     **   "<path to db>-journal"
28582     **   "<path to db>-wal"
28583     **   "<path to db>-journalNN"
28584     **   "<path to db>-walNN"
28585     **
28586     ** where NN is a decimal number. The NN naming schemes are 
28587     ** used by the test_multiplex.c module.
28588     */
28589     nDb = sqlite3Strlen30(zPath) - 1; 
28590 #ifdef SQLITE_ENABLE_8_3_NAMES
28591     while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
28592     if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
28593 #else
28594     while( zPath[nDb]!='-' ){
28595       assert( nDb>0 );
28596       assert( zPath[nDb]!='\n' );
28597       nDb--;
28598     }
28599 #endif
28600     memcpy(zDb, zPath, nDb);
28601     zDb[nDb] = '\0';
28602
28603     if( 0==osStat(zDb, &sStat) ){
28604       *pMode = sStat.st_mode & 0777;
28605       *pUid = sStat.st_uid;
28606       *pGid = sStat.st_gid;
28607     }else{
28608       rc = SQLITE_IOERR_FSTAT;
28609     }
28610   }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
28611     *pMode = 0600;
28612   }
28613   return rc;
28614 }
28615
28616 /*
28617 ** Open the file zPath.
28618 ** 
28619 ** Previously, the SQLite OS layer used three functions in place of this
28620 ** one:
28621 **
28622 **     sqlite3OsOpenReadWrite();
28623 **     sqlite3OsOpenReadOnly();
28624 **     sqlite3OsOpenExclusive();
28625 **
28626 ** These calls correspond to the following combinations of flags:
28627 **
28628 **     ReadWrite() ->     (READWRITE | CREATE)
28629 **     ReadOnly()  ->     (READONLY) 
28630 **     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
28631 **
28632 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
28633 ** true, the file was configured to be automatically deleted when the
28634 ** file handle closed. To achieve the same effect using this new 
28635 ** interface, add the DELETEONCLOSE flag to those specified above for 
28636 ** OpenExclusive().
28637 */
28638 static int unixOpen(
28639   sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
28640   const char *zPath,           /* Pathname of file to be opened */
28641   sqlite3_file *pFile,         /* The file descriptor to be filled in */
28642   int flags,                   /* Input flags to control the opening */
28643   int *pOutFlags               /* Output flags returned to SQLite core */
28644 ){
28645   unixFile *p = (unixFile *)pFile;
28646   int fd = -1;                   /* File descriptor returned by open() */
28647   int openFlags = 0;             /* Flags to pass to open() */
28648   int eType = flags&0xFFFFFF00;  /* Type of file to open */
28649   int noLock;                    /* True to omit locking primitives */
28650   int rc = SQLITE_OK;            /* Function Return Code */
28651   int ctrlFlags = 0;             /* UNIXFILE_* flags */
28652
28653   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
28654   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
28655   int isCreate     = (flags & SQLITE_OPEN_CREATE);
28656   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
28657   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
28658 #if SQLITE_ENABLE_LOCKING_STYLE
28659   int isAutoProxy  = (flags & SQLITE_OPEN_AUTOPROXY);
28660 #endif
28661 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
28662   struct statfs fsInfo;
28663 #endif
28664
28665   /* If creating a master or main-file journal, this function will open
28666   ** a file-descriptor on the directory too. The first time unixSync()
28667   ** is called the directory file descriptor will be fsync()ed and close()d.
28668   */
28669   int syncDir = (isCreate && (
28670         eType==SQLITE_OPEN_MASTER_JOURNAL 
28671      || eType==SQLITE_OPEN_MAIN_JOURNAL 
28672      || eType==SQLITE_OPEN_WAL
28673   ));
28674
28675   /* If argument zPath is a NULL pointer, this function is required to open
28676   ** a temporary file. Use this buffer to store the file name in.
28677   */
28678   char zTmpname[MAX_PATHNAME+2];
28679   const char *zName = zPath;
28680
28681   /* Check the following statements are true: 
28682   **
28683   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
28684   **   (b) if CREATE is set, then READWRITE must also be set, and
28685   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
28686   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
28687   */
28688   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
28689   assert(isCreate==0 || isReadWrite);
28690   assert(isExclusive==0 || isCreate);
28691   assert(isDelete==0 || isCreate);
28692
28693   /* The main DB, main journal, WAL file and master journal are never 
28694   ** automatically deleted. Nor are they ever temporary files.  */
28695   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
28696   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
28697   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
28698   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
28699
28700   /* Assert that the upper layer has set one of the "file-type" flags. */
28701   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
28702        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
28703        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
28704        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
28705   );
28706
28707   memset(p, 0, sizeof(unixFile));
28708
28709   if( eType==SQLITE_OPEN_MAIN_DB ){
28710     UnixUnusedFd *pUnused;
28711     pUnused = findReusableFd(zName, flags);
28712     if( pUnused ){
28713       fd = pUnused->fd;
28714     }else{
28715       pUnused = sqlite3_malloc(sizeof(*pUnused));
28716       if( !pUnused ){
28717         return SQLITE_NOMEM;
28718       }
28719     }
28720     p->pUnused = pUnused;
28721
28722     /* Database filenames are double-zero terminated if they are not
28723     ** URIs with parameters.  Hence, they can always be passed into
28724     ** sqlite3_uri_parameter(). */
28725     assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
28726
28727   }else if( !zName ){
28728     /* If zName is NULL, the upper layer is requesting a temp file. */
28729     assert(isDelete && !syncDir);
28730     rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
28731     if( rc!=SQLITE_OK ){
28732       return rc;
28733     }
28734     zName = zTmpname;
28735
28736     /* Generated temporary filenames are always double-zero terminated
28737     ** for use by sqlite3_uri_parameter(). */
28738     assert( zName[strlen(zName)+1]==0 );
28739   }
28740
28741   /* Determine the value of the flags parameter passed to POSIX function
28742   ** open(). These must be calculated even if open() is not called, as
28743   ** they may be stored as part of the file handle and used by the 
28744   ** 'conch file' locking functions later on.  */
28745   if( isReadonly )  openFlags |= O_RDONLY;
28746   if( isReadWrite ) openFlags |= O_RDWR;
28747   if( isCreate )    openFlags |= O_CREAT;
28748   if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
28749   openFlags |= (O_LARGEFILE|O_BINARY);
28750
28751   if( fd<0 ){
28752     mode_t openMode;              /* Permissions to create file with */
28753     uid_t uid;                    /* Userid for the file */
28754     gid_t gid;                    /* Groupid for the file */
28755     rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
28756     if( rc!=SQLITE_OK ){
28757       assert( !p->pUnused );
28758       assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
28759       return rc;
28760     }
28761     fd = robust_open(zName, openFlags, openMode);
28762     OSTRACE(("OPENX   %-3d %s 0%o\n", fd, zName, openFlags));
28763     if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
28764       /* Failed to open the file for read/write access. Try read-only. */
28765       flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
28766       openFlags &= ~(O_RDWR|O_CREAT);
28767       flags |= SQLITE_OPEN_READONLY;
28768       openFlags |= O_RDONLY;
28769       isReadonly = 1;
28770       fd = robust_open(zName, openFlags, openMode);
28771     }
28772     if( fd<0 ){
28773       rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
28774       goto open_finished;
28775     }
28776
28777     /* If this process is running as root and if creating a new rollback
28778     ** journal or WAL file, set the ownership of the journal or WAL to be
28779     ** the same as the original database.
28780     */
28781     if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
28782       osFchown(fd, uid, gid);
28783     }
28784   }
28785   assert( fd>=0 );
28786   if( pOutFlags ){
28787     *pOutFlags = flags;
28788   }
28789
28790   if( p->pUnused ){
28791     p->pUnused->fd = fd;
28792     p->pUnused->flags = flags;
28793   }
28794
28795   if( isDelete ){
28796 #if OS_VXWORKS
28797     zPath = zName;
28798 #else
28799     osUnlink(zName);
28800 #endif
28801   }
28802 #if SQLITE_ENABLE_LOCKING_STYLE
28803   else{
28804     p->openFlags = openFlags;
28805   }
28806 #endif
28807
28808   noLock = eType!=SQLITE_OPEN_MAIN_DB;
28809
28810   
28811 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
28812   if( fstatfs(fd, &fsInfo) == -1 ){
28813     ((unixFile*)pFile)->lastErrno = errno;
28814     robust_close(p, fd, __LINE__);
28815     return SQLITE_IOERR_ACCESS;
28816   }
28817   if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
28818     ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
28819   }
28820 #endif
28821
28822   /* Set up appropriate ctrlFlags */
28823   if( isDelete )                ctrlFlags |= UNIXFILE_DELETE;
28824   if( isReadonly )              ctrlFlags |= UNIXFILE_RDONLY;
28825   if( noLock )                  ctrlFlags |= UNIXFILE_NOLOCK;
28826   if( syncDir )                 ctrlFlags |= UNIXFILE_DIRSYNC;
28827   if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
28828
28829 #if SQLITE_ENABLE_LOCKING_STYLE
28830 #if SQLITE_PREFER_PROXY_LOCKING
28831   isAutoProxy = 1;
28832 #endif
28833   if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
28834     char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
28835     int useProxy = 0;
28836
28837     /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means 
28838     ** never use proxy, NULL means use proxy for non-local files only.  */
28839     if( envforce!=NULL ){
28840       useProxy = atoi(envforce)>0;
28841     }else{
28842       if( statfs(zPath, &fsInfo) == -1 ){
28843         /* In theory, the close(fd) call is sub-optimal. If the file opened
28844         ** with fd is a database file, and there are other connections open
28845         ** on that file that are currently holding advisory locks on it,
28846         ** then the call to close() will cancel those locks. In practice,
28847         ** we're assuming that statfs() doesn't fail very often. At least
28848         ** not while other file descriptors opened by the same process on
28849         ** the same file are working.  */
28850         p->lastErrno = errno;
28851         robust_close(p, fd, __LINE__);
28852         rc = SQLITE_IOERR_ACCESS;
28853         goto open_finished;
28854       }
28855       useProxy = !(fsInfo.f_flags&MNT_LOCAL);
28856     }
28857     if( useProxy ){
28858       rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
28859       if( rc==SQLITE_OK ){
28860         rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
28861         if( rc!=SQLITE_OK ){
28862           /* Use unixClose to clean up the resources added in fillInUnixFile 
28863           ** and clear all the structure's references.  Specifically, 
28864           ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op 
28865           */
28866           unixClose(pFile);
28867           return rc;
28868         }
28869       }
28870       goto open_finished;
28871     }
28872   }
28873 #endif
28874   
28875   rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
28876
28877 open_finished:
28878   if( rc!=SQLITE_OK ){
28879     sqlite3_free(p->pUnused);
28880   }
28881   return rc;
28882 }
28883
28884
28885 /*
28886 ** Delete the file at zPath. If the dirSync argument is true, fsync()
28887 ** the directory after deleting the file.
28888 */
28889 static int unixDelete(
28890   sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
28891   const char *zPath,        /* Name of file to be deleted */
28892   int dirSync               /* If true, fsync() directory after deleting file */
28893 ){
28894   int rc = SQLITE_OK;
28895   UNUSED_PARAMETER(NotUsed);
28896   SimulateIOError(return SQLITE_IOERR_DELETE);
28897   if( osUnlink(zPath)==(-1) ){
28898     if( errno==ENOENT ){
28899       rc = SQLITE_IOERR_DELETE_NOENT;
28900     }else{
28901       rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
28902     }
28903     return rc;
28904   }
28905 #ifndef SQLITE_DISABLE_DIRSYNC
28906   if( (dirSync & 1)!=0 ){
28907     int fd;
28908     rc = osOpenDirectory(zPath, &fd);
28909     if( rc==SQLITE_OK ){
28910 #if OS_VXWORKS
28911       if( fsync(fd)==-1 )
28912 #else
28913       if( fsync(fd) )
28914 #endif
28915       {
28916         rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
28917       }
28918       robust_close(0, fd, __LINE__);
28919     }else if( rc==SQLITE_CANTOPEN ){
28920       rc = SQLITE_OK;
28921     }
28922   }
28923 #endif
28924   return rc;
28925 }
28926
28927 /*
28928 ** Test the existence of or access permissions of file zPath. The
28929 ** test performed depends on the value of flags:
28930 **
28931 **     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
28932 **     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
28933 **     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
28934 **
28935 ** Otherwise return 0.
28936 */
28937 static int unixAccess(
28938   sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
28939   const char *zPath,      /* Path of the file to examine */
28940   int flags,              /* What do we want to learn about the zPath file? */
28941   int *pResOut            /* Write result boolean here */
28942 ){
28943   int amode = 0;
28944   UNUSED_PARAMETER(NotUsed);
28945   SimulateIOError( return SQLITE_IOERR_ACCESS; );
28946   switch( flags ){
28947     case SQLITE_ACCESS_EXISTS:
28948       amode = F_OK;
28949       break;
28950     case SQLITE_ACCESS_READWRITE:
28951       amode = W_OK|R_OK;
28952       break;
28953     case SQLITE_ACCESS_READ:
28954       amode = R_OK;
28955       break;
28956
28957     default:
28958       assert(!"Invalid flags argument");
28959   }
28960   *pResOut = (osAccess(zPath, amode)==0);
28961   if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
28962     struct stat buf;
28963     if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
28964       *pResOut = 0;
28965     }
28966   }
28967   return SQLITE_OK;
28968 }
28969
28970
28971 /*
28972 ** Turn a relative pathname into a full pathname. The relative path
28973 ** is stored as a nul-terminated string in the buffer pointed to by
28974 ** zPath. 
28975 **
28976 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes 
28977 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
28978 ** this buffer before returning.
28979 */
28980 static int unixFullPathname(
28981   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
28982   const char *zPath,            /* Possibly relative input path */
28983   int nOut,                     /* Size of output buffer in bytes */
28984   char *zOut                    /* Output buffer */
28985 ){
28986
28987   /* It's odd to simulate an io-error here, but really this is just
28988   ** using the io-error infrastructure to test that SQLite handles this
28989   ** function failing. This function could fail if, for example, the
28990   ** current working directory has been unlinked.
28991   */
28992   SimulateIOError( return SQLITE_ERROR );
28993
28994   assert( pVfs->mxPathname==MAX_PATHNAME );
28995   UNUSED_PARAMETER(pVfs);
28996
28997   zOut[nOut-1] = '\0';
28998   if( zPath[0]=='/' ){
28999     sqlite3_snprintf(nOut, zOut, "%s", zPath);
29000   }else{
29001     int nCwd;
29002     if( osGetcwd(zOut, nOut-1)==0 ){
29003       return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
29004     }
29005     nCwd = (int)strlen(zOut);
29006     sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
29007   }
29008   return SQLITE_OK;
29009 }
29010
29011
29012 #ifndef SQLITE_OMIT_LOAD_EXTENSION
29013 /*
29014 ** Interfaces for opening a shared library, finding entry points
29015 ** within the shared library, and closing the shared library.
29016 */
29017 #include <dlfcn.h>
29018 static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
29019   UNUSED_PARAMETER(NotUsed);
29020   return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
29021 }
29022
29023 /*
29024 ** SQLite calls this function immediately after a call to unixDlSym() or
29025 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
29026 ** message is available, it is written to zBufOut. If no error message
29027 ** is available, zBufOut is left unmodified and SQLite uses a default
29028 ** error message.
29029 */
29030 static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
29031   const char *zErr;
29032   UNUSED_PARAMETER(NotUsed);
29033   unixEnterMutex();
29034   zErr = dlerror();
29035   if( zErr ){
29036     sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
29037   }
29038   unixLeaveMutex();
29039 }
29040 static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
29041   /* 
29042   ** GCC with -pedantic-errors says that C90 does not allow a void* to be
29043   ** cast into a pointer to a function.  And yet the library dlsym() routine
29044   ** returns a void* which is really a pointer to a function.  So how do we
29045   ** use dlsym() with -pedantic-errors?
29046   **
29047   ** Variable x below is defined to be a pointer to a function taking
29048   ** parameters void* and const char* and returning a pointer to a function.
29049   ** We initialize x by assigning it a pointer to the dlsym() function.
29050   ** (That assignment requires a cast.)  Then we call the function that
29051   ** x points to.  
29052   **
29053   ** This work-around is unlikely to work correctly on any system where
29054   ** you really cannot cast a function pointer into void*.  But then, on the
29055   ** other hand, dlsym() will not work on such a system either, so we have
29056   ** not really lost anything.
29057   */
29058   void (*(*x)(void*,const char*))(void);
29059   UNUSED_PARAMETER(NotUsed);
29060   x = (void(*(*)(void*,const char*))(void))dlsym;
29061   return (*x)(p, zSym);
29062 }
29063 static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
29064   UNUSED_PARAMETER(NotUsed);
29065   dlclose(pHandle);
29066 }
29067 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
29068   #define unixDlOpen  0
29069   #define unixDlError 0
29070   #define unixDlSym   0
29071   #define unixDlClose 0
29072 #endif
29073
29074 /*
29075 ** Write nBuf bytes of random data to the supplied buffer zBuf.
29076 */
29077 static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
29078   UNUSED_PARAMETER(NotUsed);
29079   assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
29080
29081   /* We have to initialize zBuf to prevent valgrind from reporting
29082   ** errors.  The reports issued by valgrind are incorrect - we would
29083   ** prefer that the randomness be increased by making use of the
29084   ** uninitialized space in zBuf - but valgrind errors tend to worry
29085   ** some users.  Rather than argue, it seems easier just to initialize
29086   ** the whole array and silence valgrind, even if that means less randomness
29087   ** in the random seed.
29088   **
29089   ** When testing, initializing zBuf[] to zero is all we do.  That means
29090   ** that we always use the same random number sequence.  This makes the
29091   ** tests repeatable.
29092   */
29093   memset(zBuf, 0, nBuf);
29094 #if !defined(SQLITE_TEST)
29095   {
29096     int pid, fd, got;
29097     fd = robust_open("/dev/urandom", O_RDONLY, 0);
29098     if( fd<0 ){
29099       time_t t;
29100       time(&t);
29101       memcpy(zBuf, &t, sizeof(t));
29102       pid = getpid();
29103       memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
29104       assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
29105       nBuf = sizeof(t) + sizeof(pid);
29106     }else{
29107       do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
29108       robust_close(0, fd, __LINE__);
29109     }
29110   }
29111 #endif
29112   return nBuf;
29113 }
29114
29115
29116 /*
29117 ** Sleep for a little while.  Return the amount of time slept.
29118 ** The argument is the number of microseconds we want to sleep.
29119 ** The return value is the number of microseconds of sleep actually
29120 ** requested from the underlying operating system, a number which
29121 ** might be greater than or equal to the argument, but not less
29122 ** than the argument.
29123 */
29124 static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
29125 #if OS_VXWORKS
29126   struct timespec sp;
29127
29128   sp.tv_sec = microseconds / 1000000;
29129   sp.tv_nsec = (microseconds % 1000000) * 1000;
29130   nanosleep(&sp, NULL);
29131   UNUSED_PARAMETER(NotUsed);
29132   return microseconds;
29133 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
29134   usleep(microseconds);
29135   UNUSED_PARAMETER(NotUsed);
29136   return microseconds;
29137 #else
29138   int seconds = (microseconds+999999)/1000000;
29139   sleep(seconds);
29140   UNUSED_PARAMETER(NotUsed);
29141   return seconds*1000000;
29142 #endif
29143 }
29144
29145 /*
29146 ** The following variable, if set to a non-zero value, is interpreted as
29147 ** the number of seconds since 1970 and is used to set the result of
29148 ** sqlite3OsCurrentTime() during testing.
29149 */
29150 #ifdef SQLITE_TEST
29151 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
29152 #endif
29153
29154 /*
29155 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
29156 ** the current time and date as a Julian Day number times 86_400_000.  In
29157 ** other words, write into *piNow the number of milliseconds since the Julian
29158 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
29159 ** proleptic Gregorian calendar.
29160 **
29161 ** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date 
29162 ** cannot be found.
29163 */
29164 static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
29165   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
29166   int rc = SQLITE_OK;
29167 #if defined(NO_GETTOD)
29168   time_t t;
29169   time(&t);
29170   *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
29171 #elif OS_VXWORKS
29172   struct timespec sNow;
29173   clock_gettime(CLOCK_REALTIME, &sNow);
29174   *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
29175 #else
29176   struct timeval sNow;
29177   if( gettimeofday(&sNow, 0)==0 ){
29178     *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
29179   }else{
29180     rc = SQLITE_ERROR;
29181   }
29182 #endif
29183
29184 #ifdef SQLITE_TEST
29185   if( sqlite3_current_time ){
29186     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
29187   }
29188 #endif
29189   UNUSED_PARAMETER(NotUsed);
29190   return rc;
29191 }
29192
29193 /*
29194 ** Find the current time (in Universal Coordinated Time).  Write the
29195 ** current time and date as a Julian Day number into *prNow and
29196 ** return 0.  Return 1 if the time and date cannot be found.
29197 */
29198 static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
29199   sqlite3_int64 i = 0;
29200   int rc;
29201   UNUSED_PARAMETER(NotUsed);
29202   rc = unixCurrentTimeInt64(0, &i);
29203   *prNow = i/86400000.0;
29204   return rc;
29205 }
29206
29207 /*
29208 ** We added the xGetLastError() method with the intention of providing
29209 ** better low-level error messages when operating-system problems come up
29210 ** during SQLite operation.  But so far, none of that has been implemented
29211 ** in the core.  So this routine is never called.  For now, it is merely
29212 ** a place-holder.
29213 */
29214 static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
29215   UNUSED_PARAMETER(NotUsed);
29216   UNUSED_PARAMETER(NotUsed2);
29217   UNUSED_PARAMETER(NotUsed3);
29218   return 0;
29219 }
29220
29221
29222 /*
29223 ************************ End of sqlite3_vfs methods ***************************
29224 ******************************************************************************/
29225
29226 /******************************************************************************
29227 ************************** Begin Proxy Locking ********************************
29228 **
29229 ** Proxy locking is a "uber-locking-method" in this sense:  It uses the
29230 ** other locking methods on secondary lock files.  Proxy locking is a
29231 ** meta-layer over top of the primitive locking implemented above.  For
29232 ** this reason, the division that implements of proxy locking is deferred
29233 ** until late in the file (here) after all of the other I/O methods have
29234 ** been defined - so that the primitive locking methods are available
29235 ** as services to help with the implementation of proxy locking.
29236 **
29237 ****
29238 **
29239 ** The default locking schemes in SQLite use byte-range locks on the
29240 ** database file to coordinate safe, concurrent access by multiple readers
29241 ** and writers [http://sqlite.org/lockingv3.html].  The five file locking
29242 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
29243 ** as POSIX read & write locks over fixed set of locations (via fsctl),
29244 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
29245 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
29246 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
29247 ** address in the shared range is taken for a SHARED lock, the entire
29248 ** shared range is taken for an EXCLUSIVE lock):
29249 **
29250 **      PENDING_BYTE        0x40000000
29251 **      RESERVED_BYTE       0x40000001
29252 **      SHARED_RANGE        0x40000002 -> 0x40000200
29253 **
29254 ** This works well on the local file system, but shows a nearly 100x
29255 ** slowdown in read performance on AFP because the AFP client disables
29256 ** the read cache when byte-range locks are present.  Enabling the read
29257 ** cache exposes a cache coherency problem that is present on all OS X
29258 ** supported network file systems.  NFS and AFP both observe the
29259 ** close-to-open semantics for ensuring cache coherency
29260 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
29261 ** address the requirements for concurrent database access by multiple
29262 ** readers and writers
29263 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
29264 **
29265 ** To address the performance and cache coherency issues, proxy file locking
29266 ** changes the way database access is controlled by limiting access to a
29267 ** single host at a time and moving file locks off of the database file
29268 ** and onto a proxy file on the local file system.  
29269 **
29270 **
29271 ** Using proxy locks
29272 ** -----------------
29273 **
29274 ** C APIs
29275 **
29276 **  sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
29277 **                       <proxy_path> | ":auto:");
29278 **  sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
29279 **
29280 **
29281 ** SQL pragmas
29282 **
29283 **  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
29284 **  PRAGMA [database.]lock_proxy_file
29285 **
29286 ** Specifying ":auto:" means that if there is a conch file with a matching
29287 ** host ID in it, the proxy path in the conch file will be used, otherwise
29288 ** a proxy path based on the user's temp dir
29289 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
29290 ** actual proxy file name is generated from the name and path of the
29291 ** database file.  For example:
29292 **
29293 **       For database path "/Users/me/foo.db" 
29294 **       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
29295 **
29296 ** Once a lock proxy is configured for a database connection, it can not
29297 ** be removed, however it may be switched to a different proxy path via
29298 ** the above APIs (assuming the conch file is not being held by another
29299 ** connection or process). 
29300 **
29301 **
29302 ** How proxy locking works
29303 ** -----------------------
29304 **
29305 ** Proxy file locking relies primarily on two new supporting files: 
29306 **
29307 **   *  conch file to limit access to the database file to a single host
29308 **      at a time
29309 **
29310 **   *  proxy file to act as a proxy for the advisory locks normally
29311 **      taken on the database
29312 **
29313 ** The conch file - to use a proxy file, sqlite must first "hold the conch"
29314 ** by taking an sqlite-style shared lock on the conch file, reading the
29315 ** contents and comparing the host's unique host ID (see below) and lock
29316 ** proxy path against the values stored in the conch.  The conch file is
29317 ** stored in the same directory as the database file and the file name
29318 ** is patterned after the database file name as ".<databasename>-conch".
29319 ** If the conch file does not exist, or it's contents do not match the
29320 ** host ID and/or proxy path, then the lock is escalated to an exclusive
29321 ** lock and the conch file contents is updated with the host ID and proxy
29322 ** path and the lock is downgraded to a shared lock again.  If the conch
29323 ** is held by another process (with a shared lock), the exclusive lock
29324 ** will fail and SQLITE_BUSY is returned.
29325 **
29326 ** The proxy file - a single-byte file used for all advisory file locks
29327 ** normally taken on the database file.   This allows for safe sharing
29328 ** of the database file for multiple readers and writers on the same
29329 ** host (the conch ensures that they all use the same local lock file).
29330 **
29331 ** Requesting the lock proxy does not immediately take the conch, it is
29332 ** only taken when the first request to lock database file is made.  
29333 ** This matches the semantics of the traditional locking behavior, where
29334 ** opening a connection to a database file does not take a lock on it.
29335 ** The shared lock and an open file descriptor are maintained until 
29336 ** the connection to the database is closed. 
29337 **
29338 ** The proxy file and the lock file are never deleted so they only need
29339 ** to be created the first time they are used.
29340 **
29341 ** Configuration options
29342 ** ---------------------
29343 **
29344 **  SQLITE_PREFER_PROXY_LOCKING
29345 **
29346 **       Database files accessed on non-local file systems are
29347 **       automatically configured for proxy locking, lock files are
29348 **       named automatically using the same logic as
29349 **       PRAGMA lock_proxy_file=":auto:"
29350 **    
29351 **  SQLITE_PROXY_DEBUG
29352 **
29353 **       Enables the logging of error messages during host id file
29354 **       retrieval and creation
29355 **
29356 **  LOCKPROXYDIR
29357 **
29358 **       Overrides the default directory used for lock proxy files that
29359 **       are named automatically via the ":auto:" setting
29360 **
29361 **  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
29362 **
29363 **       Permissions to use when creating a directory for storing the
29364 **       lock proxy files, only used when LOCKPROXYDIR is not set.
29365 **    
29366 **    
29367 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
29368 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
29369 ** force proxy locking to be used for every database file opened, and 0
29370 ** will force automatic proxy locking to be disabled for all database
29371 ** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
29372 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
29373 */
29374
29375 /*
29376 ** Proxy locking is only available on MacOSX 
29377 */
29378 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
29379
29380 /*
29381 ** The proxyLockingContext has the path and file structures for the remote 
29382 ** and local proxy files in it
29383 */
29384 typedef struct proxyLockingContext proxyLockingContext;
29385 struct proxyLockingContext {
29386   unixFile *conchFile;         /* Open conch file */
29387   char *conchFilePath;         /* Name of the conch file */
29388   unixFile *lockProxy;         /* Open proxy lock file */
29389   char *lockProxyPath;         /* Name of the proxy lock file */
29390   char *dbPath;                /* Name of the open file */
29391   int conchHeld;               /* 1 if the conch is held, -1 if lockless */
29392   void *oldLockingContext;     /* Original lockingcontext to restore on close */
29393   sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
29394 };
29395
29396 /* 
29397 ** The proxy lock file path for the database at dbPath is written into lPath, 
29398 ** which must point to valid, writable memory large enough for a maxLen length
29399 ** file path. 
29400 */
29401 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
29402   int len;
29403   int dbLen;
29404   int i;
29405
29406 #ifdef LOCKPROXYDIR
29407   len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
29408 #else
29409 # ifdef _CS_DARWIN_USER_TEMP_DIR
29410   {
29411     if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
29412       OSTRACE(("GETLOCKPATH  failed %s errno=%d pid=%d\n",
29413                lPath, errno, getpid()));
29414       return SQLITE_IOERR_LOCK;
29415     }
29416     len = strlcat(lPath, "sqliteplocks", maxLen);    
29417   }
29418 # else
29419   len = strlcpy(lPath, "/tmp/", maxLen);
29420 # endif
29421 #endif
29422
29423   if( lPath[len-1]!='/' ){
29424     len = strlcat(lPath, "/", maxLen);
29425   }
29426   
29427   /* transform the db path to a unique cache name */
29428   dbLen = (int)strlen(dbPath);
29429   for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
29430     char c = dbPath[i];
29431     lPath[i+len] = (c=='/')?'_':c;
29432   }
29433   lPath[i+len]='\0';
29434   strlcat(lPath, ":auto:", maxLen);
29435   OSTRACE(("GETLOCKPATH  proxy lock path=%s pid=%d\n", lPath, getpid()));
29436   return SQLITE_OK;
29437 }
29438
29439 /* 
29440  ** Creates the lock file and any missing directories in lockPath
29441  */
29442 static int proxyCreateLockPath(const char *lockPath){
29443   int i, len;
29444   char buf[MAXPATHLEN];
29445   int start = 0;
29446   
29447   assert(lockPath!=NULL);
29448   /* try to create all the intermediate directories */
29449   len = (int)strlen(lockPath);
29450   buf[0] = lockPath[0];
29451   for( i=1; i<len; i++ ){
29452     if( lockPath[i] == '/' && (i - start > 0) ){
29453       /* only mkdir if leaf dir != "." or "/" or ".." */
29454       if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/') 
29455          || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
29456         buf[i]='\0';
29457         if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
29458           int err=errno;
29459           if( err!=EEXIST ) {
29460             OSTRACE(("CREATELOCKPATH  FAILED creating %s, "
29461                      "'%s' proxy lock path=%s pid=%d\n",
29462                      buf, strerror(err), lockPath, getpid()));
29463             return err;
29464           }
29465         }
29466       }
29467       start=i+1;
29468     }
29469     buf[i] = lockPath[i];
29470   }
29471   OSTRACE(("CREATELOCKPATH  proxy lock path=%s pid=%d\n", lockPath, getpid()));
29472   return 0;
29473 }
29474
29475 /*
29476 ** Create a new VFS file descriptor (stored in memory obtained from
29477 ** sqlite3_malloc) and open the file named "path" in the file descriptor.
29478 **
29479 ** The caller is responsible not only for closing the file descriptor
29480 ** but also for freeing the memory associated with the file descriptor.
29481 */
29482 static int proxyCreateUnixFile(
29483     const char *path,        /* path for the new unixFile */
29484     unixFile **ppFile,       /* unixFile created and returned by ref */
29485     int islockfile           /* if non zero missing dirs will be created */
29486 ) {
29487   int fd = -1;
29488   unixFile *pNew;
29489   int rc = SQLITE_OK;
29490   int openFlags = O_RDWR | O_CREAT;
29491   sqlite3_vfs dummyVfs;
29492   int terrno = 0;
29493   UnixUnusedFd *pUnused = NULL;
29494
29495   /* 1. first try to open/create the file
29496   ** 2. if that fails, and this is a lock file (not-conch), try creating
29497   ** the parent directories and then try again.
29498   ** 3. if that fails, try to open the file read-only
29499   ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
29500   */
29501   pUnused = findReusableFd(path, openFlags);
29502   if( pUnused ){
29503     fd = pUnused->fd;
29504   }else{
29505     pUnused = sqlite3_malloc(sizeof(*pUnused));
29506     if( !pUnused ){
29507       return SQLITE_NOMEM;
29508     }
29509   }
29510   if( fd<0 ){
29511     fd = robust_open(path, openFlags, 0);
29512     terrno = errno;
29513     if( fd<0 && errno==ENOENT && islockfile ){
29514       if( proxyCreateLockPath(path) == SQLITE_OK ){
29515         fd = robust_open(path, openFlags, 0);
29516       }
29517     }
29518   }
29519   if( fd<0 ){
29520     openFlags = O_RDONLY;
29521     fd = robust_open(path, openFlags, 0);
29522     terrno = errno;
29523   }
29524   if( fd<0 ){
29525     if( islockfile ){
29526       return SQLITE_BUSY;
29527     }
29528     switch (terrno) {
29529       case EACCES:
29530         return SQLITE_PERM;
29531       case EIO: 
29532         return SQLITE_IOERR_LOCK; /* even though it is the conch */
29533       default:
29534         return SQLITE_CANTOPEN_BKPT;
29535     }
29536   }
29537   
29538   pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
29539   if( pNew==NULL ){
29540     rc = SQLITE_NOMEM;
29541     goto end_create_proxy;
29542   }
29543   memset(pNew, 0, sizeof(unixFile));
29544   pNew->openFlags = openFlags;
29545   memset(&dummyVfs, 0, sizeof(dummyVfs));
29546   dummyVfs.pAppData = (void*)&autolockIoFinder;
29547   dummyVfs.zName = "dummy";
29548   pUnused->fd = fd;
29549   pUnused->flags = openFlags;
29550   pNew->pUnused = pUnused;
29551   
29552   rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
29553   if( rc==SQLITE_OK ){
29554     *ppFile = pNew;
29555     return SQLITE_OK;
29556   }
29557 end_create_proxy:    
29558   robust_close(pNew, fd, __LINE__);
29559   sqlite3_free(pNew);
29560   sqlite3_free(pUnused);
29561   return rc;
29562 }
29563
29564 #ifdef SQLITE_TEST
29565 /* simulate multiple hosts by creating unique hostid file paths */
29566 SQLITE_API int sqlite3_hostid_num = 0;
29567 #endif
29568
29569 #define PROXY_HOSTIDLEN    16  /* conch file host id length */
29570
29571 /* Not always defined in the headers as it ought to be */
29572 extern int gethostuuid(uuid_t id, const struct timespec *wait);
29573
29574 /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN 
29575 ** bytes of writable memory.
29576 */
29577 static int proxyGetHostID(unsigned char *pHostID, int *pError){
29578   assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
29579   memset(pHostID, 0, PROXY_HOSTIDLEN);
29580 #if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
29581                && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
29582   {
29583     static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
29584     if( gethostuuid(pHostID, &timeout) ){
29585       int err = errno;
29586       if( pError ){
29587         *pError = err;
29588       }
29589       return SQLITE_IOERR;
29590     }
29591   }
29592 #else
29593   UNUSED_PARAMETER(pError);
29594 #endif
29595 #ifdef SQLITE_TEST
29596   /* simulate multiple hosts by creating unique hostid file paths */
29597   if( sqlite3_hostid_num != 0){
29598     pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
29599   }
29600 #endif
29601   
29602   return SQLITE_OK;
29603 }
29604
29605 /* The conch file contains the header, host id and lock file path
29606  */
29607 #define PROXY_CONCHVERSION 2   /* 1-byte header, 16-byte host id, path */
29608 #define PROXY_HEADERLEN    1   /* conch file header length */
29609 #define PROXY_PATHINDEX    (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
29610 #define PROXY_MAXCONCHLEN  (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
29611
29612 /* 
29613 ** Takes an open conch file, copies the contents to a new path and then moves 
29614 ** it back.  The newly created file's file descriptor is assigned to the
29615 ** conch file structure and finally the original conch file descriptor is 
29616 ** closed.  Returns zero if successful.
29617 */
29618 static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
29619   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
29620   unixFile *conchFile = pCtx->conchFile;
29621   char tPath[MAXPATHLEN];
29622   char buf[PROXY_MAXCONCHLEN];
29623   char *cPath = pCtx->conchFilePath;
29624   size_t readLen = 0;
29625   size_t pathLen = 0;
29626   char errmsg[64] = "";
29627   int fd = -1;
29628   int rc = -1;
29629   UNUSED_PARAMETER(myHostID);
29630
29631   /* create a new path by replace the trailing '-conch' with '-break' */
29632   pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
29633   if( pathLen>MAXPATHLEN || pathLen<6 || 
29634      (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
29635     sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
29636     goto end_breaklock;
29637   }
29638   /* read the conch content */
29639   readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
29640   if( readLen<PROXY_PATHINDEX ){
29641     sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
29642     goto end_breaklock;
29643   }
29644   /* write it out to the temporary break file */
29645   fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
29646   if( fd<0 ){
29647     sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
29648     goto end_breaklock;
29649   }
29650   if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
29651     sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
29652     goto end_breaklock;
29653   }
29654   if( rename(tPath, cPath) ){
29655     sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
29656     goto end_breaklock;
29657   }
29658   rc = 0;
29659   fprintf(stderr, "broke stale lock on %s\n", cPath);
29660   robust_close(pFile, conchFile->h, __LINE__);
29661   conchFile->h = fd;
29662   conchFile->openFlags = O_RDWR | O_CREAT;
29663
29664 end_breaklock:
29665   if( rc ){
29666     if( fd>=0 ){
29667       osUnlink(tPath);
29668       robust_close(pFile, fd, __LINE__);
29669     }
29670     fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
29671   }
29672   return rc;
29673 }
29674
29675 /* Take the requested lock on the conch file and break a stale lock if the 
29676 ** host id matches.
29677 */
29678 static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
29679   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
29680   unixFile *conchFile = pCtx->conchFile;
29681   int rc = SQLITE_OK;
29682   int nTries = 0;
29683   struct timespec conchModTime;
29684   
29685   memset(&conchModTime, 0, sizeof(conchModTime));
29686   do {
29687     rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
29688     nTries ++;
29689     if( rc==SQLITE_BUSY ){
29690       /* If the lock failed (busy):
29691        * 1st try: get the mod time of the conch, wait 0.5s and try again. 
29692        * 2nd try: fail if the mod time changed or host id is different, wait 
29693        *           10 sec and try again
29694        * 3rd try: break the lock unless the mod time has changed.
29695        */
29696       struct stat buf;
29697       if( osFstat(conchFile->h, &buf) ){
29698         pFile->lastErrno = errno;
29699         return SQLITE_IOERR_LOCK;
29700       }
29701       
29702       if( nTries==1 ){
29703         conchModTime = buf.st_mtimespec;
29704         usleep(500000); /* wait 0.5 sec and try the lock again*/
29705         continue;  
29706       }
29707
29708       assert( nTries>1 );
29709       if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec || 
29710          conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
29711         return SQLITE_BUSY;
29712       }
29713       
29714       if( nTries==2 ){  
29715         char tBuf[PROXY_MAXCONCHLEN];
29716         int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
29717         if( len<0 ){
29718           pFile->lastErrno = errno;
29719           return SQLITE_IOERR_LOCK;
29720         }
29721         if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
29722           /* don't break the lock if the host id doesn't match */
29723           if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
29724             return SQLITE_BUSY;
29725           }
29726         }else{
29727           /* don't break the lock on short read or a version mismatch */
29728           return SQLITE_BUSY;
29729         }
29730         usleep(10000000); /* wait 10 sec and try the lock again */
29731         continue; 
29732       }
29733       
29734       assert( nTries==3 );
29735       if( 0==proxyBreakConchLock(pFile, myHostID) ){
29736         rc = SQLITE_OK;
29737         if( lockType==EXCLUSIVE_LOCK ){
29738           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);          
29739         }
29740         if( !rc ){
29741           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
29742         }
29743       }
29744     }
29745   } while( rc==SQLITE_BUSY && nTries<3 );
29746   
29747   return rc;
29748 }
29749
29750 /* Takes the conch by taking a shared lock and read the contents conch, if 
29751 ** lockPath is non-NULL, the host ID and lock file path must match.  A NULL 
29752 ** lockPath means that the lockPath in the conch file will be used if the 
29753 ** host IDs match, or a new lock path will be generated automatically 
29754 ** and written to the conch file.
29755 */
29756 static int proxyTakeConch(unixFile *pFile){
29757   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
29758   
29759   if( pCtx->conchHeld!=0 ){
29760     return SQLITE_OK;
29761   }else{
29762     unixFile *conchFile = pCtx->conchFile;
29763     uuid_t myHostID;
29764     int pError = 0;
29765     char readBuf[PROXY_MAXCONCHLEN];
29766     char lockPath[MAXPATHLEN];
29767     char *tempLockPath = NULL;
29768     int rc = SQLITE_OK;
29769     int createConch = 0;
29770     int hostIdMatch = 0;
29771     int readLen = 0;
29772     int tryOldLockPath = 0;
29773     int forceNewLockPath = 0;
29774     
29775     OSTRACE(("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
29776              (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
29777
29778     rc = proxyGetHostID(myHostID, &pError);
29779     if( (rc&0xff)==SQLITE_IOERR ){
29780       pFile->lastErrno = pError;
29781       goto end_takeconch;
29782     }
29783     rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
29784     if( rc!=SQLITE_OK ){
29785       goto end_takeconch;
29786     }
29787     /* read the existing conch file */
29788     readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
29789     if( readLen<0 ){
29790       /* I/O error: lastErrno set by seekAndRead */
29791       pFile->lastErrno = conchFile->lastErrno;
29792       rc = SQLITE_IOERR_READ;
29793       goto end_takeconch;
29794     }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) || 
29795              readBuf[0]!=(char)PROXY_CONCHVERSION ){
29796       /* a short read or version format mismatch means we need to create a new 
29797       ** conch file. 
29798       */
29799       createConch = 1;
29800     }
29801     /* if the host id matches and the lock path already exists in the conch
29802     ** we'll try to use the path there, if we can't open that path, we'll 
29803     ** retry with a new auto-generated path 
29804     */
29805     do { /* in case we need to try again for an :auto: named lock file */
29806
29807       if( !createConch && !forceNewLockPath ){
29808         hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID, 
29809                                   PROXY_HOSTIDLEN);
29810         /* if the conch has data compare the contents */
29811         if( !pCtx->lockProxyPath ){
29812           /* for auto-named local lock file, just check the host ID and we'll
29813            ** use the local lock file path that's already in there
29814            */
29815           if( hostIdMatch ){
29816             size_t pathLen = (readLen - PROXY_PATHINDEX);
29817             
29818             if( pathLen>=MAXPATHLEN ){
29819               pathLen=MAXPATHLEN-1;
29820             }
29821             memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
29822             lockPath[pathLen] = 0;
29823             tempLockPath = lockPath;
29824             tryOldLockPath = 1;
29825             /* create a copy of the lock path if the conch is taken */
29826             goto end_takeconch;
29827           }
29828         }else if( hostIdMatch
29829                && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
29830                            readLen-PROXY_PATHINDEX)
29831         ){
29832           /* conch host and lock path match */
29833           goto end_takeconch; 
29834         }
29835       }
29836       
29837       /* if the conch isn't writable and doesn't match, we can't take it */
29838       if( (conchFile->openFlags&O_RDWR) == 0 ){
29839         rc = SQLITE_BUSY;
29840         goto end_takeconch;
29841       }
29842       
29843       /* either the conch didn't match or we need to create a new one */
29844       if( !pCtx->lockProxyPath ){
29845         proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
29846         tempLockPath = lockPath;
29847         /* create a copy of the lock path _only_ if the conch is taken */
29848       }
29849       
29850       /* update conch with host and path (this will fail if other process
29851       ** has a shared lock already), if the host id matches, use the big
29852       ** stick.
29853       */
29854       futimes(conchFile->h, NULL);
29855       if( hostIdMatch && !createConch ){
29856         if( conchFile->pInode && conchFile->pInode->nShared>1 ){
29857           /* We are trying for an exclusive lock but another thread in this
29858            ** same process is still holding a shared lock. */
29859           rc = SQLITE_BUSY;
29860         } else {          
29861           rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
29862         }
29863       }else{
29864         rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
29865       }
29866       if( rc==SQLITE_OK ){
29867         char writeBuffer[PROXY_MAXCONCHLEN];
29868         int writeSize = 0;
29869         
29870         writeBuffer[0] = (char)PROXY_CONCHVERSION;
29871         memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
29872         if( pCtx->lockProxyPath!=NULL ){
29873           strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
29874         }else{
29875           strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
29876         }
29877         writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
29878         robust_ftruncate(conchFile->h, writeSize);
29879         rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
29880         fsync(conchFile->h);
29881         /* If we created a new conch file (not just updated the contents of a 
29882          ** valid conch file), try to match the permissions of the database 
29883          */
29884         if( rc==SQLITE_OK && createConch ){
29885           struct stat buf;
29886           int err = osFstat(pFile->h, &buf);
29887           if( err==0 ){
29888             mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
29889                                         S_IROTH|S_IWOTH);
29890             /* try to match the database file R/W permissions, ignore failure */
29891 #ifndef SQLITE_PROXY_DEBUG
29892             osFchmod(conchFile->h, cmode);
29893 #else
29894             do{
29895               rc = osFchmod(conchFile->h, cmode);
29896             }while( rc==(-1) && errno==EINTR );
29897             if( rc!=0 ){
29898               int code = errno;
29899               fprintf(stderr, "fchmod %o FAILED with %d %s\n",
29900                       cmode, code, strerror(code));
29901             } else {
29902               fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
29903             }
29904           }else{
29905             int code = errno;
29906             fprintf(stderr, "STAT FAILED[%d] with %d %s\n", 
29907                     err, code, strerror(code));
29908 #endif
29909           }
29910         }
29911       }
29912       conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
29913       
29914     end_takeconch:
29915       OSTRACE(("TRANSPROXY: CLOSE  %d\n", pFile->h));
29916       if( rc==SQLITE_OK && pFile->openFlags ){
29917         int fd;
29918         if( pFile->h>=0 ){
29919           robust_close(pFile, pFile->h, __LINE__);
29920         }
29921         pFile->h = -1;
29922         fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
29923         OSTRACE(("TRANSPROXY: OPEN  %d\n", fd));
29924         if( fd>=0 ){
29925           pFile->h = fd;
29926         }else{
29927           rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
29928            during locking */
29929         }
29930       }
29931       if( rc==SQLITE_OK && !pCtx->lockProxy ){
29932         char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
29933         rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
29934         if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
29935           /* we couldn't create the proxy lock file with the old lock file path
29936            ** so try again via auto-naming 
29937            */
29938           forceNewLockPath = 1;
29939           tryOldLockPath = 0;
29940           continue; /* go back to the do {} while start point, try again */
29941         }
29942       }
29943       if( rc==SQLITE_OK ){
29944         /* Need to make a copy of path if we extracted the value
29945          ** from the conch file or the path was allocated on the stack
29946          */
29947         if( tempLockPath ){
29948           pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
29949           if( !pCtx->lockProxyPath ){
29950             rc = SQLITE_NOMEM;
29951           }
29952         }
29953       }
29954       if( rc==SQLITE_OK ){
29955         pCtx->conchHeld = 1;
29956         
29957         if( pCtx->lockProxy->pMethod == &afpIoMethods ){
29958           afpLockingContext *afpCtx;
29959           afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
29960           afpCtx->dbPath = pCtx->lockProxyPath;
29961         }
29962       } else {
29963         conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
29964       }
29965       OSTRACE(("TAKECONCH  %d %s\n", conchFile->h,
29966                rc==SQLITE_OK?"ok":"failed"));
29967       return rc;
29968     } while (1); /* in case we need to retry the :auto: lock file - 
29969                  ** we should never get here except via the 'continue' call. */
29970   }
29971 }
29972
29973 /*
29974 ** If pFile holds a lock on a conch file, then release that lock.
29975 */
29976 static int proxyReleaseConch(unixFile *pFile){
29977   int rc = SQLITE_OK;         /* Subroutine return code */
29978   proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
29979   unixFile *conchFile;        /* Name of the conch file */
29980
29981   pCtx = (proxyLockingContext *)pFile->lockingContext;
29982   conchFile = pCtx->conchFile;
29983   OSTRACE(("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
29984            (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), 
29985            getpid()));
29986   if( pCtx->conchHeld>0 ){
29987     rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
29988   }
29989   pCtx->conchHeld = 0;
29990   OSTRACE(("RELEASECONCH  %d %s\n", conchFile->h,
29991            (rc==SQLITE_OK ? "ok" : "failed")));
29992   return rc;
29993 }
29994
29995 /*
29996 ** Given the name of a database file, compute the name of its conch file.
29997 ** Store the conch filename in memory obtained from sqlite3_malloc().
29998 ** Make *pConchPath point to the new name.  Return SQLITE_OK on success
29999 ** or SQLITE_NOMEM if unable to obtain memory.
30000 **
30001 ** The caller is responsible for ensuring that the allocated memory
30002 ** space is eventually freed.
30003 **
30004 ** *pConchPath is set to NULL if a memory allocation error occurs.
30005 */
30006 static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
30007   int i;                        /* Loop counter */
30008   int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
30009   char *conchPath;              /* buffer in which to construct conch name */
30010
30011   /* Allocate space for the conch filename and initialize the name to
30012   ** the name of the original database file. */  
30013   *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
30014   if( conchPath==0 ){
30015     return SQLITE_NOMEM;
30016   }
30017   memcpy(conchPath, dbPath, len+1);
30018   
30019   /* now insert a "." before the last / character */
30020   for( i=(len-1); i>=0; i-- ){
30021     if( conchPath[i]=='/' ){
30022       i++;
30023       break;
30024     }
30025   }
30026   conchPath[i]='.';
30027   while ( i<len ){
30028     conchPath[i+1]=dbPath[i];
30029     i++;
30030   }
30031
30032   /* append the "-conch" suffix to the file */
30033   memcpy(&conchPath[i+1], "-conch", 7);
30034   assert( (int)strlen(conchPath) == len+7 );
30035
30036   return SQLITE_OK;
30037 }
30038
30039
30040 /* Takes a fully configured proxy locking-style unix file and switches
30041 ** the local lock file path 
30042 */
30043 static int switchLockProxyPath(unixFile *pFile, const char *path) {
30044   proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
30045   char *oldPath = pCtx->lockProxyPath;
30046   int rc = SQLITE_OK;
30047
30048   if( pFile->eFileLock!=NO_LOCK ){
30049     return SQLITE_BUSY;
30050   }  
30051
30052   /* nothing to do if the path is NULL, :auto: or matches the existing path */
30053   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
30054     (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
30055     return SQLITE_OK;
30056   }else{
30057     unixFile *lockProxy = pCtx->lockProxy;
30058     pCtx->lockProxy=NULL;
30059     pCtx->conchHeld = 0;
30060     if( lockProxy!=NULL ){
30061       rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
30062       if( rc ) return rc;
30063       sqlite3_free(lockProxy);
30064     }
30065     sqlite3_free(oldPath);
30066     pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
30067   }
30068   
30069   return rc;
30070 }
30071
30072 /*
30073 ** pFile is a file that has been opened by a prior xOpen call.  dbPath
30074 ** is a string buffer at least MAXPATHLEN+1 characters in size.
30075 **
30076 ** This routine find the filename associated with pFile and writes it
30077 ** int dbPath.
30078 */
30079 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
30080 #if defined(__APPLE__)
30081   if( pFile->pMethod == &afpIoMethods ){
30082     /* afp style keeps a reference to the db path in the filePath field 
30083     ** of the struct */
30084     assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
30085     strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
30086   } else
30087 #endif
30088   if( pFile->pMethod == &dotlockIoMethods ){
30089     /* dot lock style uses the locking context to store the dot lock
30090     ** file path */
30091     int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
30092     memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
30093   }else{
30094     /* all other styles use the locking context to store the db file path */
30095     assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
30096     strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
30097   }
30098   return SQLITE_OK;
30099 }
30100
30101 /*
30102 ** Takes an already filled in unix file and alters it so all file locking 
30103 ** will be performed on the local proxy lock file.  The following fields
30104 ** are preserved in the locking context so that they can be restored and 
30105 ** the unix structure properly cleaned up at close time:
30106 **  ->lockingContext
30107 **  ->pMethod
30108 */
30109 static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
30110   proxyLockingContext *pCtx;
30111   char dbPath[MAXPATHLEN+1];       /* Name of the database file */
30112   char *lockPath=NULL;
30113   int rc = SQLITE_OK;
30114   
30115   if( pFile->eFileLock!=NO_LOCK ){
30116     return SQLITE_BUSY;
30117   }
30118   proxyGetDbPathForUnixFile(pFile, dbPath);
30119   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
30120     lockPath=NULL;
30121   }else{
30122     lockPath=(char *)path;
30123   }
30124   
30125   OSTRACE(("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
30126            (lockPath ? lockPath : ":auto:"), getpid()));
30127
30128   pCtx = sqlite3_malloc( sizeof(*pCtx) );
30129   if( pCtx==0 ){
30130     return SQLITE_NOMEM;
30131   }
30132   memset(pCtx, 0, sizeof(*pCtx));
30133
30134   rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
30135   if( rc==SQLITE_OK ){
30136     rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
30137     if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
30138       /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
30139       ** (c) the file system is read-only, then enable no-locking access.
30140       ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
30141       ** that openFlags will have only one of O_RDONLY or O_RDWR.
30142       */
30143       struct statfs fsInfo;
30144       struct stat conchInfo;
30145       int goLockless = 0;
30146
30147       if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
30148         int err = errno;
30149         if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
30150           goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
30151         }
30152       }
30153       if( goLockless ){
30154         pCtx->conchHeld = -1; /* read only FS/ lockless */
30155         rc = SQLITE_OK;
30156       }
30157     }
30158   }  
30159   if( rc==SQLITE_OK && lockPath ){
30160     pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
30161   }
30162
30163   if( rc==SQLITE_OK ){
30164     pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
30165     if( pCtx->dbPath==NULL ){
30166       rc = SQLITE_NOMEM;
30167     }
30168   }
30169   if( rc==SQLITE_OK ){
30170     /* all memory is allocated, proxys are created and assigned, 
30171     ** switch the locking context and pMethod then return.
30172     */
30173     pCtx->oldLockingContext = pFile->lockingContext;
30174     pFile->lockingContext = pCtx;
30175     pCtx->pOldMethod = pFile->pMethod;
30176     pFile->pMethod = &proxyIoMethods;
30177   }else{
30178     if( pCtx->conchFile ){ 
30179       pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
30180       sqlite3_free(pCtx->conchFile);
30181     }
30182     sqlite3DbFree(0, pCtx->lockProxyPath);
30183     sqlite3_free(pCtx->conchFilePath); 
30184     sqlite3_free(pCtx);
30185   }
30186   OSTRACE(("TRANSPROXY  %d %s\n", pFile->h,
30187            (rc==SQLITE_OK ? "ok" : "failed")));
30188   return rc;
30189 }
30190
30191
30192 /*
30193 ** This routine handles sqlite3_file_control() calls that are specific
30194 ** to proxy locking.
30195 */
30196 static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
30197   switch( op ){
30198     case SQLITE_GET_LOCKPROXYFILE: {
30199       unixFile *pFile = (unixFile*)id;
30200       if( pFile->pMethod == &proxyIoMethods ){
30201         proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
30202         proxyTakeConch(pFile);
30203         if( pCtx->lockProxyPath ){
30204           *(const char **)pArg = pCtx->lockProxyPath;
30205         }else{
30206           *(const char **)pArg = ":auto: (not held)";
30207         }
30208       } else {
30209         *(const char **)pArg = NULL;
30210       }
30211       return SQLITE_OK;
30212     }
30213     case SQLITE_SET_LOCKPROXYFILE: {
30214       unixFile *pFile = (unixFile*)id;
30215       int rc = SQLITE_OK;
30216       int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
30217       if( pArg==NULL || (const char *)pArg==0 ){
30218         if( isProxyStyle ){
30219           /* turn off proxy locking - not supported */
30220           rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
30221         }else{
30222           /* turn off proxy locking - already off - NOOP */
30223           rc = SQLITE_OK;
30224         }
30225       }else{
30226         const char *proxyPath = (const char *)pArg;
30227         if( isProxyStyle ){
30228           proxyLockingContext *pCtx = 
30229             (proxyLockingContext*)pFile->lockingContext;
30230           if( !strcmp(pArg, ":auto:") 
30231            || (pCtx->lockProxyPath &&
30232                !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
30233           ){
30234             rc = SQLITE_OK;
30235           }else{
30236             rc = switchLockProxyPath(pFile, proxyPath);
30237           }
30238         }else{
30239           /* turn on proxy file locking */
30240           rc = proxyTransformUnixFile(pFile, proxyPath);
30241         }
30242       }
30243       return rc;
30244     }
30245     default: {
30246       assert( 0 );  /* The call assures that only valid opcodes are sent */
30247     }
30248   }
30249   /*NOTREACHED*/
30250   return SQLITE_ERROR;
30251 }
30252
30253 /*
30254 ** Within this division (the proxying locking implementation) the procedures
30255 ** above this point are all utilities.  The lock-related methods of the
30256 ** proxy-locking sqlite3_io_method object follow.
30257 */
30258
30259
30260 /*
30261 ** This routine checks if there is a RESERVED lock held on the specified
30262 ** file by this or any other process. If such a lock is held, set *pResOut
30263 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
30264 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
30265 */
30266 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
30267   unixFile *pFile = (unixFile*)id;
30268   int rc = proxyTakeConch(pFile);
30269   if( rc==SQLITE_OK ){
30270     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30271     if( pCtx->conchHeld>0 ){
30272       unixFile *proxy = pCtx->lockProxy;
30273       return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
30274     }else{ /* conchHeld < 0 is lockless */
30275       pResOut=0;
30276     }
30277   }
30278   return rc;
30279 }
30280
30281 /*
30282 ** Lock the file with the lock specified by parameter eFileLock - one
30283 ** of the following:
30284 **
30285 **     (1) SHARED_LOCK
30286 **     (2) RESERVED_LOCK
30287 **     (3) PENDING_LOCK
30288 **     (4) EXCLUSIVE_LOCK
30289 **
30290 ** Sometimes when requesting one lock state, additional lock states
30291 ** are inserted in between.  The locking might fail on one of the later
30292 ** transitions leaving the lock state different from what it started but
30293 ** still short of its goal.  The following chart shows the allowed
30294 ** transitions and the inserted intermediate states:
30295 **
30296 **    UNLOCKED -> SHARED
30297 **    SHARED -> RESERVED
30298 **    SHARED -> (PENDING) -> EXCLUSIVE
30299 **    RESERVED -> (PENDING) -> EXCLUSIVE
30300 **    PENDING -> EXCLUSIVE
30301 **
30302 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
30303 ** routine to lower a locking level.
30304 */
30305 static int proxyLock(sqlite3_file *id, int eFileLock) {
30306   unixFile *pFile = (unixFile*)id;
30307   int rc = proxyTakeConch(pFile);
30308   if( rc==SQLITE_OK ){
30309     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30310     if( pCtx->conchHeld>0 ){
30311       unixFile *proxy = pCtx->lockProxy;
30312       rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
30313       pFile->eFileLock = proxy->eFileLock;
30314     }else{
30315       /* conchHeld < 0 is lockless */
30316     }
30317   }
30318   return rc;
30319 }
30320
30321
30322 /*
30323 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
30324 ** must be either NO_LOCK or SHARED_LOCK.
30325 **
30326 ** If the locking level of the file descriptor is already at or below
30327 ** the requested locking level, this routine is a no-op.
30328 */
30329 static int proxyUnlock(sqlite3_file *id, int eFileLock) {
30330   unixFile *pFile = (unixFile*)id;
30331   int rc = proxyTakeConch(pFile);
30332   if( rc==SQLITE_OK ){
30333     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30334     if( pCtx->conchHeld>0 ){
30335       unixFile *proxy = pCtx->lockProxy;
30336       rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
30337       pFile->eFileLock = proxy->eFileLock;
30338     }else{
30339       /* conchHeld < 0 is lockless */
30340     }
30341   }
30342   return rc;
30343 }
30344
30345 /*
30346 ** Close a file that uses proxy locks.
30347 */
30348 static int proxyClose(sqlite3_file *id) {
30349   if( id ){
30350     unixFile *pFile = (unixFile*)id;
30351     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
30352     unixFile *lockProxy = pCtx->lockProxy;
30353     unixFile *conchFile = pCtx->conchFile;
30354     int rc = SQLITE_OK;
30355     
30356     if( lockProxy ){
30357       rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
30358       if( rc ) return rc;
30359       rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
30360       if( rc ) return rc;
30361       sqlite3_free(lockProxy);
30362       pCtx->lockProxy = 0;
30363     }
30364     if( conchFile ){
30365       if( pCtx->conchHeld ){
30366         rc = proxyReleaseConch(pFile);
30367         if( rc ) return rc;
30368       }
30369       rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
30370       if( rc ) return rc;
30371       sqlite3_free(conchFile);
30372     }
30373     sqlite3DbFree(0, pCtx->lockProxyPath);
30374     sqlite3_free(pCtx->conchFilePath);
30375     sqlite3DbFree(0, pCtx->dbPath);
30376     /* restore the original locking context and pMethod then close it */
30377     pFile->lockingContext = pCtx->oldLockingContext;
30378     pFile->pMethod = pCtx->pOldMethod;
30379     sqlite3_free(pCtx);
30380     return pFile->pMethod->xClose(id);
30381   }
30382   return SQLITE_OK;
30383 }
30384
30385
30386
30387 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
30388 /*
30389 ** The proxy locking style is intended for use with AFP filesystems.
30390 ** And since AFP is only supported on MacOSX, the proxy locking is also
30391 ** restricted to MacOSX.
30392 ** 
30393 **
30394 ******************* End of the proxy lock implementation **********************
30395 ******************************************************************************/
30396
30397 /*
30398 ** Initialize the operating system interface.
30399 **
30400 ** This routine registers all VFS implementations for unix-like operating
30401 ** systems.  This routine, and the sqlite3_os_end() routine that follows,
30402 ** should be the only routines in this file that are visible from other
30403 ** files.
30404 **
30405 ** This routine is called once during SQLite initialization and by a
30406 ** single thread.  The memory allocation and mutex subsystems have not
30407 ** necessarily been initialized when this routine is called, and so they
30408 ** should not be used.
30409 */
30410 SQLITE_API int sqlite3_os_init(void){ 
30411   /* 
30412   ** The following macro defines an initializer for an sqlite3_vfs object.
30413   ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
30414   ** to the "finder" function.  (pAppData is a pointer to a pointer because
30415   ** silly C90 rules prohibit a void* from being cast to a function pointer
30416   ** and so we have to go through the intermediate pointer to avoid problems
30417   ** when compiling with -pedantic-errors on GCC.)
30418   **
30419   ** The FINDER parameter to this macro is the name of the pointer to the
30420   ** finder-function.  The finder-function returns a pointer to the
30421   ** sqlite_io_methods object that implements the desired locking
30422   ** behaviors.  See the division above that contains the IOMETHODS
30423   ** macro for addition information on finder-functions.
30424   **
30425   ** Most finders simply return a pointer to a fixed sqlite3_io_methods
30426   ** object.  But the "autolockIoFinder" available on MacOSX does a little
30427   ** more than that; it looks at the filesystem type that hosts the 
30428   ** database file and tries to choose an locking method appropriate for
30429   ** that filesystem time.
30430   */
30431   #define UNIXVFS(VFSNAME, FINDER) {                        \
30432     3,                    /* iVersion */                    \
30433     sizeof(unixFile),     /* szOsFile */                    \
30434     MAX_PATHNAME,         /* mxPathname */                  \
30435     0,                    /* pNext */                       \
30436     VFSNAME,              /* zName */                       \
30437     (void*)&FINDER,       /* pAppData */                    \
30438     unixOpen,             /* xOpen */                       \
30439     unixDelete,           /* xDelete */                     \
30440     unixAccess,           /* xAccess */                     \
30441     unixFullPathname,     /* xFullPathname */               \
30442     unixDlOpen,           /* xDlOpen */                     \
30443     unixDlError,          /* xDlError */                    \
30444     unixDlSym,            /* xDlSym */                      \
30445     unixDlClose,          /* xDlClose */                    \
30446     unixRandomness,       /* xRandomness */                 \
30447     unixSleep,            /* xSleep */                      \
30448     unixCurrentTime,      /* xCurrentTime */                \
30449     unixGetLastError,     /* xGetLastError */               \
30450     unixCurrentTimeInt64, /* xCurrentTimeInt64 */           \
30451     unixSetSystemCall,    /* xSetSystemCall */              \
30452     unixGetSystemCall,    /* xGetSystemCall */              \
30453     unixNextSystemCall,   /* xNextSystemCall */             \
30454   }
30455
30456   /*
30457   ** All default VFSes for unix are contained in the following array.
30458   **
30459   ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
30460   ** by the SQLite core when the VFS is registered.  So the following
30461   ** array cannot be const.
30462   */
30463   static sqlite3_vfs aVfs[] = {
30464 #if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
30465     UNIXVFS("unix",          autolockIoFinder ),
30466 #else
30467     UNIXVFS("unix",          posixIoFinder ),
30468 #endif
30469     UNIXVFS("unix-none",     nolockIoFinder ),
30470     UNIXVFS("unix-dotfile",  dotlockIoFinder ),
30471     UNIXVFS("unix-excl",     posixIoFinder ),
30472 #if OS_VXWORKS
30473     UNIXVFS("unix-namedsem", semIoFinder ),
30474 #endif
30475 #if SQLITE_ENABLE_LOCKING_STYLE
30476     UNIXVFS("unix-posix",    posixIoFinder ),
30477 #if !OS_VXWORKS
30478     UNIXVFS("unix-flock",    flockIoFinder ),
30479 #endif
30480 #endif
30481 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
30482     UNIXVFS("unix-afp",      afpIoFinder ),
30483     UNIXVFS("unix-nfs",      nfsIoFinder ),
30484     UNIXVFS("unix-proxy",    proxyIoFinder ),
30485 #endif
30486   };
30487   unsigned int i;          /* Loop counter */
30488
30489   /* Double-check that the aSyscall[] array has been constructed
30490   ** correctly.  See ticket [bb3a86e890c8e96ab] */
30491   assert( ArraySize(aSyscall)==24 );
30492
30493   /* Register all VFSes defined in the aVfs[] array */
30494   for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
30495     sqlite3_vfs_register(&aVfs[i], i==0);
30496   }
30497   return SQLITE_OK; 
30498 }
30499
30500 /*
30501 ** Shutdown the operating system interface.
30502 **
30503 ** Some operating systems might need to do some cleanup in this routine,
30504 ** to release dynamically allocated objects.  But not on unix.
30505 ** This routine is a no-op for unix.
30506 */
30507 SQLITE_API int sqlite3_os_end(void){ 
30508   return SQLITE_OK; 
30509 }
30510  
30511 #endif /* SQLITE_OS_UNIX */
30512
30513 /************** End of os_unix.c *********************************************/
30514 /************** Begin file os_win.c ******************************************/
30515 /*
30516 ** 2004 May 22
30517 **
30518 ** The author disclaims copyright to this source code.  In place of
30519 ** a legal notice, here is a blessing:
30520 **
30521 **    May you do good and not evil.
30522 **    May you find forgiveness for yourself and forgive others.
30523 **    May you share freely, never taking more than you give.
30524 **
30525 ******************************************************************************
30526 **
30527 ** This file contains code that is specific to Windows.
30528 */
30529 #if SQLITE_OS_WIN               /* This file is used for Windows only */
30530
30531 #ifdef __CYGWIN__
30532 # include <sys/cygwin.h>
30533 #endif
30534
30535 /*
30536 ** Include code that is common to all os_*.c files
30537 */
30538 /************** Include os_common.h in the middle of os_win.c ****************/
30539 /************** Begin file os_common.h ***************************************/
30540 /*
30541 ** 2004 May 22
30542 **
30543 ** The author disclaims copyright to this source code.  In place of
30544 ** a legal notice, here is a blessing:
30545 **
30546 **    May you do good and not evil.
30547 **    May you find forgiveness for yourself and forgive others.
30548 **    May you share freely, never taking more than you give.
30549 **
30550 ******************************************************************************
30551 **
30552 ** This file contains macros and a little bit of code that is common to
30553 ** all of the platform-specific files (os_*.c) and is #included into those
30554 ** files.
30555 **
30556 ** This file should be #included by the os_*.c files only.  It is not a
30557 ** general purpose header file.
30558 */
30559 #ifndef _OS_COMMON_H_
30560 #define _OS_COMMON_H_
30561
30562 /*
30563 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
30564 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
30565 ** switch.  The following code should catch this problem at compile-time.
30566 */
30567 #ifdef MEMORY_DEBUG
30568 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
30569 #endif
30570
30571 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
30572 # ifndef SQLITE_DEBUG_OS_TRACE
30573 #   define SQLITE_DEBUG_OS_TRACE 0
30574 # endif
30575   int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
30576 # define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
30577 #else
30578 # define OSTRACE(X)
30579 #endif
30580
30581 /*
30582 ** Macros for performance tracing.  Normally turned off.  Only works
30583 ** on i486 hardware.
30584 */
30585 #ifdef SQLITE_PERFORMANCE_TRACE
30586
30587 /* 
30588 ** hwtime.h contains inline assembler code for implementing 
30589 ** high-performance timing routines.
30590 */
30591 /************** Include hwtime.h in the middle of os_common.h ****************/
30592 /************** Begin file hwtime.h ******************************************/
30593 /*
30594 ** 2008 May 27
30595 **
30596 ** The author disclaims copyright to this source code.  In place of
30597 ** a legal notice, here is a blessing:
30598 **
30599 **    May you do good and not evil.
30600 **    May you find forgiveness for yourself and forgive others.
30601 **    May you share freely, never taking more than you give.
30602 **
30603 ******************************************************************************
30604 **
30605 ** This file contains inline asm code for retrieving "high-performance"
30606 ** counters for x86 class CPUs.
30607 */
30608 #ifndef _HWTIME_H_
30609 #define _HWTIME_H_
30610
30611 /*
30612 ** The following routine only works on pentium-class (or newer) processors.
30613 ** It uses the RDTSC opcode to read the cycle count value out of the
30614 ** processor and returns that value.  This can be used for high-res
30615 ** profiling.
30616 */
30617 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
30618       (defined(i386) || defined(__i386__) || defined(_M_IX86))
30619
30620   #if defined(__GNUC__)
30621
30622   __inline__ sqlite_uint64 sqlite3Hwtime(void){
30623      unsigned int lo, hi;
30624      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
30625      return (sqlite_uint64)hi << 32 | lo;
30626   }
30627
30628   #elif defined(_MSC_VER)
30629
30630   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
30631      __asm {
30632         rdtsc
30633         ret       ; return value at EDX:EAX
30634      }
30635   }
30636
30637   #endif
30638
30639 #elif (defined(__GNUC__) && defined(__x86_64__))
30640
30641   __inline__ sqlite_uint64 sqlite3Hwtime(void){
30642       unsigned long val;
30643       __asm__ __volatile__ ("rdtsc" : "=A" (val));
30644       return val;
30645   }
30646  
30647 #elif (defined(__GNUC__) && defined(__ppc__))
30648
30649   __inline__ sqlite_uint64 sqlite3Hwtime(void){
30650       unsigned long long retval;
30651       unsigned long junk;
30652       __asm__ __volatile__ ("\n\
30653           1:      mftbu   %1\n\
30654                   mftb    %L0\n\
30655                   mftbu   %0\n\
30656                   cmpw    %0,%1\n\
30657                   bne     1b"
30658                   : "=r" (retval), "=r" (junk));
30659       return retval;
30660   }
30661
30662 #else
30663
30664   #error Need implementation of sqlite3Hwtime() for your platform.
30665
30666   /*
30667   ** To compile without implementing sqlite3Hwtime() for your platform,
30668   ** you can remove the above #error and use the following
30669   ** stub function.  You will lose timing support for many
30670   ** of the debugging and testing utilities, but it should at
30671   ** least compile and run.
30672   */
30673 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
30674
30675 #endif
30676
30677 #endif /* !defined(_HWTIME_H_) */
30678
30679 /************** End of hwtime.h **********************************************/
30680 /************** Continuing where we left off in os_common.h ******************/
30681
30682 static sqlite_uint64 g_start;
30683 static sqlite_uint64 g_elapsed;
30684 #define TIMER_START       g_start=sqlite3Hwtime()
30685 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
30686 #define TIMER_ELAPSED     g_elapsed
30687 #else
30688 #define TIMER_START
30689 #define TIMER_END
30690 #define TIMER_ELAPSED     ((sqlite_uint64)0)
30691 #endif
30692
30693 /*
30694 ** If we compile with the SQLITE_TEST macro set, then the following block
30695 ** of code will give us the ability to simulate a disk I/O error.  This
30696 ** is used for testing the I/O recovery logic.
30697 */
30698 #ifdef SQLITE_TEST
30699 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
30700 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
30701 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
30702 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
30703 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
30704 SQLITE_API int sqlite3_diskfull_pending = 0;
30705 SQLITE_API int sqlite3_diskfull = 0;
30706 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
30707 #define SimulateIOError(CODE)  \
30708   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
30709        || sqlite3_io_error_pending-- == 1 )  \
30710               { local_ioerr(); CODE; }
30711 static void local_ioerr(){
30712   IOTRACE(("IOERR\n"));
30713   sqlite3_io_error_hit++;
30714   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
30715 }
30716 #define SimulateDiskfullError(CODE) \
30717    if( sqlite3_diskfull_pending ){ \
30718      if( sqlite3_diskfull_pending == 1 ){ \
30719        local_ioerr(); \
30720        sqlite3_diskfull = 1; \
30721        sqlite3_io_error_hit = 1; \
30722        CODE; \
30723      }else{ \
30724        sqlite3_diskfull_pending--; \
30725      } \
30726    }
30727 #else
30728 #define SimulateIOErrorBenign(X)
30729 #define SimulateIOError(A)
30730 #define SimulateDiskfullError(A)
30731 #endif
30732
30733 /*
30734 ** When testing, keep a count of the number of open files.
30735 */
30736 #ifdef SQLITE_TEST
30737 SQLITE_API int sqlite3_open_file_count = 0;
30738 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
30739 #else
30740 #define OpenCounter(X)
30741 #endif
30742
30743 #endif /* !defined(_OS_COMMON_H_) */
30744
30745 /************** End of os_common.h *******************************************/
30746 /************** Continuing where we left off in os_win.c *********************/
30747
30748 /*
30749 ** Compiling and using WAL mode requires several APIs that are only
30750 ** available in Windows platforms based on the NT kernel.
30751 */
30752 #if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
30753 # error "WAL mode requires support from the Windows NT kernel, compile\
30754  with SQLITE_OMIT_WAL."
30755 #endif
30756
30757 /*
30758 ** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
30759 ** based on the sub-platform)?
30760 */
30761 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
30762 #  define SQLITE_WIN32_HAS_ANSI
30763 #endif
30764
30765 /*
30766 ** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
30767 ** based on the sub-platform)?
30768 */
30769 #if SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT
30770 #  define SQLITE_WIN32_HAS_WIDE
30771 #endif
30772
30773 /*
30774 ** Do we need to manually define the Win32 file mapping APIs for use with WAL
30775 ** mode (e.g. these APIs are available in the Windows CE SDK; however, they
30776 ** are not present in the header file)?
30777 */
30778 #if SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL)
30779 /*
30780 ** Two of the file mapping APIs are different under WinRT.  Figure out which
30781 ** set we need.
30782 */
30783 #if SQLITE_OS_WINRT
30784 WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
30785         LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
30786
30787 WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
30788 #else
30789 #if defined(SQLITE_WIN32_HAS_ANSI)
30790 WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
30791         DWORD, DWORD, DWORD, LPCSTR);
30792 #endif /* defined(SQLITE_WIN32_HAS_ANSI) */
30793
30794 #if defined(SQLITE_WIN32_HAS_WIDE)
30795 WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
30796         DWORD, DWORD, DWORD, LPCWSTR);
30797 #endif /* defined(SQLITE_WIN32_HAS_WIDE) */
30798
30799 WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
30800 #endif /* SQLITE_OS_WINRT */
30801
30802 /*
30803 ** This file mapping API is common to both Win32 and WinRT.
30804 */
30805 WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
30806 #endif /* SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL) */
30807
30808 /*
30809 ** Macro to find the minimum of two numeric values.
30810 */
30811 #ifndef MIN
30812 # define MIN(x,y) ((x)<(y)?(x):(y))
30813 #endif
30814
30815 /*
30816 ** Some Microsoft compilers lack this definition.
30817 */
30818 #ifndef INVALID_FILE_ATTRIBUTES
30819 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1) 
30820 #endif
30821
30822 #ifndef FILE_FLAG_MASK
30823 # define FILE_FLAG_MASK          (0xFF3C0000)
30824 #endif
30825
30826 #ifndef FILE_ATTRIBUTE_MASK
30827 # define FILE_ATTRIBUTE_MASK     (0x0003FFF7)
30828 #endif
30829
30830 #ifndef SQLITE_OMIT_WAL
30831 /* Forward references */
30832 typedef struct winShm winShm;           /* A connection to shared-memory */
30833 typedef struct winShmNode winShmNode;   /* A region of shared-memory */
30834 #endif
30835
30836 /*
30837 ** WinCE lacks native support for file locking so we have to fake it
30838 ** with some code of our own.
30839 */
30840 #if SQLITE_OS_WINCE
30841 typedef struct winceLock {
30842   int nReaders;       /* Number of reader locks obtained */
30843   BOOL bPending;      /* Indicates a pending lock has been obtained */
30844   BOOL bReserved;     /* Indicates a reserved lock has been obtained */
30845   BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
30846 } winceLock;
30847 #endif
30848
30849 /*
30850 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
30851 ** portability layer.
30852 */
30853 typedef struct winFile winFile;
30854 struct winFile {
30855   const sqlite3_io_methods *pMethod; /*** Must be first ***/
30856   sqlite3_vfs *pVfs;      /* The VFS used to open this file */
30857   HANDLE h;               /* Handle for accessing the file */
30858   u8 locktype;            /* Type of lock currently held on this file */
30859   short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
30860   u8 ctrlFlags;           /* Flags.  See WINFILE_* below */
30861   DWORD lastErrno;        /* The Windows errno from the last I/O error */
30862 #ifndef SQLITE_OMIT_WAL
30863   winShm *pShm;           /* Instance of shared memory on this file */
30864 #endif
30865   const char *zPath;      /* Full pathname of this file */
30866   int szChunk;            /* Chunk size configured by FCNTL_CHUNK_SIZE */
30867 #if SQLITE_OS_WINCE
30868   LPWSTR zDeleteOnClose;  /* Name of file to delete when closing */
30869   HANDLE hMutex;          /* Mutex used to control access to shared lock */  
30870   HANDLE hShared;         /* Shared memory segment used for locking */
30871   winceLock local;        /* Locks obtained by this instance of winFile */
30872   winceLock *shared;      /* Global shared lock memory for the file  */
30873 #endif
30874 #if SQLITE_MAX_MMAP_SIZE>0
30875   int nFetchOut;                /* Number of outstanding xFetch references */
30876   HANDLE hMap;                  /* Handle for accessing memory mapping */
30877   void *pMapRegion;             /* Area memory mapped */
30878   sqlite3_int64 mmapSize;       /* Usable size of mapped region */
30879   sqlite3_int64 mmapSizeActual; /* Actual size of mapped region */
30880   sqlite3_int64 mmapSizeMax;    /* Configured FCNTL_MMAP_SIZE value */
30881 #endif
30882 };
30883
30884 /*
30885 ** Allowed values for winFile.ctrlFlags
30886 */
30887 #define WINFILE_RDONLY          0x02   /* Connection is read only */
30888 #define WINFILE_PERSIST_WAL     0x04   /* Persistent WAL mode */
30889 #define WINFILE_PSOW            0x10   /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
30890
30891 /*
30892  * The size of the buffer used by sqlite3_win32_write_debug().
30893  */
30894 #ifndef SQLITE_WIN32_DBG_BUF_SIZE
30895 #  define SQLITE_WIN32_DBG_BUF_SIZE   ((int)(4096-sizeof(DWORD)))
30896 #endif
30897
30898 /*
30899  * The value used with sqlite3_win32_set_directory() to specify that
30900  * the data directory should be changed.
30901  */
30902 #ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE
30903 #  define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)
30904 #endif
30905
30906 /*
30907  * The value used with sqlite3_win32_set_directory() to specify that
30908  * the temporary directory should be changed.
30909  */
30910 #ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE
30911 #  define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)
30912 #endif
30913
30914 /*
30915  * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
30916  * various Win32 API heap functions instead of our own.
30917  */
30918 #ifdef SQLITE_WIN32_MALLOC
30919
30920 /*
30921  * If this is non-zero, an isolated heap will be created by the native Win32
30922  * allocator subsystem; otherwise, the default process heap will be used.  This
30923  * setting has no effect when compiling for WinRT.  By default, this is enabled
30924  * and an isolated heap will be created to store all allocated data.
30925  *
30926  ******************************************************************************
30927  * WARNING: It is important to note that when this setting is non-zero and the
30928  *          winMemShutdown function is called (e.g. by the sqlite3_shutdown
30929  *          function), all data that was allocated using the isolated heap will
30930  *          be freed immediately and any attempt to access any of that freed
30931  *          data will almost certainly result in an immediate access violation.
30932  ******************************************************************************
30933  */
30934 #ifndef SQLITE_WIN32_HEAP_CREATE
30935 #  define SQLITE_WIN32_HEAP_CREATE    (TRUE)
30936 #endif
30937
30938 /*
30939  * The initial size of the Win32-specific heap.  This value may be zero.
30940  */
30941 #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
30942 #  define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_DEFAULT_CACHE_SIZE) * \
30943                                        (SQLITE_DEFAULT_PAGE_SIZE) + 4194304)
30944 #endif
30945
30946 /*
30947  * The maximum size of the Win32-specific heap.  This value may be zero.
30948  */
30949 #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
30950 #  define SQLITE_WIN32_HEAP_MAX_SIZE  (0)
30951 #endif
30952
30953 /*
30954  * The extra flags to use in calls to the Win32 heap APIs.  This value may be
30955  * zero for the default behavior.
30956  */
30957 #ifndef SQLITE_WIN32_HEAP_FLAGS
30958 #  define SQLITE_WIN32_HEAP_FLAGS     (0)
30959 #endif
30960
30961 /*
30962 ** The winMemData structure stores information required by the Win32-specific
30963 ** sqlite3_mem_methods implementation.
30964 */
30965 typedef struct winMemData winMemData;
30966 struct winMemData {
30967 #ifndef NDEBUG
30968   u32 magic;    /* Magic number to detect structure corruption. */
30969 #endif
30970   HANDLE hHeap; /* The handle to our heap. */
30971   BOOL bOwned;  /* Do we own the heap (i.e. destroy it on shutdown)? */
30972 };
30973
30974 #ifndef NDEBUG
30975 #define WINMEM_MAGIC     0x42b2830b
30976 #endif
30977
30978 static struct winMemData win_mem_data = {
30979 #ifndef NDEBUG
30980   WINMEM_MAGIC,
30981 #endif
30982   NULL, FALSE
30983 };
30984
30985 #ifndef NDEBUG
30986 #define winMemAssertMagic() assert( win_mem_data.magic==WINMEM_MAGIC )
30987 #else
30988 #define winMemAssertMagic()
30989 #endif
30990
30991 #define winMemGetHeap() win_mem_data.hHeap
30992
30993 static void *winMemMalloc(int nBytes);
30994 static void winMemFree(void *pPrior);
30995 static void *winMemRealloc(void *pPrior, int nBytes);
30996 static int winMemSize(void *p);
30997 static int winMemRoundup(int n);
30998 static int winMemInit(void *pAppData);
30999 static void winMemShutdown(void *pAppData);
31000
31001 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
31002 #endif /* SQLITE_WIN32_MALLOC */
31003
31004 /*
31005 ** The following variable is (normally) set once and never changes
31006 ** thereafter.  It records whether the operating system is Win9x
31007 ** or WinNT.
31008 **
31009 ** 0:   Operating system unknown.
31010 ** 1:   Operating system is Win9x.
31011 ** 2:   Operating system is WinNT.
31012 **
31013 ** In order to facilitate testing on a WinNT system, the test fixture
31014 ** can manually set this value to 1 to emulate Win98 behavior.
31015 */
31016 #ifdef SQLITE_TEST
31017 SQLITE_API int sqlite3_os_type = 0;
31018 #else
31019 static int sqlite3_os_type = 0;
31020 #endif
31021
31022 #ifndef SYSCALL
31023 #  define SYSCALL sqlite3_syscall_ptr
31024 #endif
31025
31026 /*
31027 ** This function is not available on Windows CE or WinRT.
31028  */
31029
31030 #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
31031 #  define osAreFileApisANSI()       1
31032 #endif
31033
31034 /*
31035 ** Many system calls are accessed through pointer-to-functions so that
31036 ** they may be overridden at runtime to facilitate fault injection during
31037 ** testing and sandboxing.  The following array holds the names and pointers
31038 ** to all overrideable system calls.
31039 */
31040 static struct win_syscall {
31041   const char *zName;            /* Name of the system call */
31042   sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
31043   sqlite3_syscall_ptr pDefault; /* Default value */
31044 } aSyscall[] = {
31045 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
31046   { "AreFileApisANSI",         (SYSCALL)AreFileApisANSI,         0 },
31047 #else
31048   { "AreFileApisANSI",         (SYSCALL)0,                       0 },
31049 #endif
31050
31051 #ifndef osAreFileApisANSI
31052 #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
31053 #endif
31054
31055 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
31056   { "CharLowerW",              (SYSCALL)CharLowerW,              0 },
31057 #else
31058   { "CharLowerW",              (SYSCALL)0,                       0 },
31059 #endif
31060
31061 #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
31062
31063 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
31064   { "CharUpperW",              (SYSCALL)CharUpperW,              0 },
31065 #else
31066   { "CharUpperW",              (SYSCALL)0,                       0 },
31067 #endif
31068
31069 #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
31070
31071   { "CloseHandle",             (SYSCALL)CloseHandle,             0 },
31072
31073 #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
31074
31075 #if defined(SQLITE_WIN32_HAS_ANSI)
31076   { "CreateFileA",             (SYSCALL)CreateFileA,             0 },
31077 #else
31078   { "CreateFileA",             (SYSCALL)0,                       0 },
31079 #endif
31080
31081 #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
31082         LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
31083
31084 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
31085   { "CreateFileW",             (SYSCALL)CreateFileW,             0 },
31086 #else
31087   { "CreateFileW",             (SYSCALL)0,                       0 },
31088 #endif
31089
31090 #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
31091         LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
31092
31093 #if (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
31094         !defined(SQLITE_OMIT_WAL))
31095   { "CreateFileMappingA",      (SYSCALL)CreateFileMappingA,      0 },
31096 #else
31097   { "CreateFileMappingA",      (SYSCALL)0,                       0 },
31098 #endif
31099
31100 #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
31101         DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
31102
31103 #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
31104         !defined(SQLITE_OMIT_WAL))
31105   { "CreateFileMappingW",      (SYSCALL)CreateFileMappingW,      0 },
31106 #else
31107   { "CreateFileMappingW",      (SYSCALL)0,                       0 },
31108 #endif
31109
31110 #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
31111         DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
31112
31113 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
31114   { "CreateMutexW",            (SYSCALL)CreateMutexW,            0 },
31115 #else
31116   { "CreateMutexW",            (SYSCALL)0,                       0 },
31117 #endif
31118
31119 #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
31120         LPCWSTR))aSyscall[8].pCurrent)
31121
31122 #if defined(SQLITE_WIN32_HAS_ANSI)
31123   { "DeleteFileA",             (SYSCALL)DeleteFileA,             0 },
31124 #else
31125   { "DeleteFileA",             (SYSCALL)0,                       0 },
31126 #endif
31127
31128 #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
31129
31130 #if defined(SQLITE_WIN32_HAS_WIDE)
31131   { "DeleteFileW",             (SYSCALL)DeleteFileW,             0 },
31132 #else
31133   { "DeleteFileW",             (SYSCALL)0,                       0 },
31134 #endif
31135
31136 #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
31137
31138 #if SQLITE_OS_WINCE
31139   { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
31140 #else
31141   { "FileTimeToLocalFileTime", (SYSCALL)0,                       0 },
31142 #endif
31143
31144 #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
31145         LPFILETIME))aSyscall[11].pCurrent)
31146
31147 #if SQLITE_OS_WINCE
31148   { "FileTimeToSystemTime",    (SYSCALL)FileTimeToSystemTime,    0 },
31149 #else
31150   { "FileTimeToSystemTime",    (SYSCALL)0,                       0 },
31151 #endif
31152
31153 #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
31154         LPSYSTEMTIME))aSyscall[12].pCurrent)
31155
31156   { "FlushFileBuffers",        (SYSCALL)FlushFileBuffers,        0 },
31157
31158 #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
31159
31160 #if defined(SQLITE_WIN32_HAS_ANSI)
31161   { "FormatMessageA",          (SYSCALL)FormatMessageA,          0 },
31162 #else
31163   { "FormatMessageA",          (SYSCALL)0,                       0 },
31164 #endif
31165
31166 #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
31167         DWORD,va_list*))aSyscall[14].pCurrent)
31168
31169 #if defined(SQLITE_WIN32_HAS_WIDE)
31170   { "FormatMessageW",          (SYSCALL)FormatMessageW,          0 },
31171 #else
31172   { "FormatMessageW",          (SYSCALL)0,                       0 },
31173 #endif
31174
31175 #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
31176         DWORD,va_list*))aSyscall[15].pCurrent)
31177
31178 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
31179   { "FreeLibrary",             (SYSCALL)FreeLibrary,             0 },
31180 #else
31181   { "FreeLibrary",             (SYSCALL)0,                       0 },
31182 #endif
31183
31184 #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
31185
31186   { "GetCurrentProcessId",     (SYSCALL)GetCurrentProcessId,     0 },
31187
31188 #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
31189
31190 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
31191   { "GetDiskFreeSpaceA",       (SYSCALL)GetDiskFreeSpaceA,       0 },
31192 #else
31193   { "GetDiskFreeSpaceA",       (SYSCALL)0,                       0 },
31194 #endif
31195
31196 #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
31197         LPDWORD))aSyscall[18].pCurrent)
31198
31199 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
31200   { "GetDiskFreeSpaceW",       (SYSCALL)GetDiskFreeSpaceW,       0 },
31201 #else
31202   { "GetDiskFreeSpaceW",       (SYSCALL)0,                       0 },
31203 #endif
31204
31205 #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
31206         LPDWORD))aSyscall[19].pCurrent)
31207
31208 #if defined(SQLITE_WIN32_HAS_ANSI)
31209   { "GetFileAttributesA",      (SYSCALL)GetFileAttributesA,      0 },
31210 #else
31211   { "GetFileAttributesA",      (SYSCALL)0,                       0 },
31212 #endif
31213
31214 #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
31215
31216 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
31217   { "GetFileAttributesW",      (SYSCALL)GetFileAttributesW,      0 },
31218 #else
31219   { "GetFileAttributesW",      (SYSCALL)0,                       0 },
31220 #endif
31221
31222 #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
31223
31224 #if defined(SQLITE_WIN32_HAS_WIDE)
31225   { "GetFileAttributesExW",    (SYSCALL)GetFileAttributesExW,    0 },
31226 #else
31227   { "GetFileAttributesExW",    (SYSCALL)0,                       0 },
31228 #endif
31229
31230 #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
31231         LPVOID))aSyscall[22].pCurrent)
31232
31233 #if !SQLITE_OS_WINRT
31234   { "GetFileSize",             (SYSCALL)GetFileSize,             0 },
31235 #else
31236   { "GetFileSize",             (SYSCALL)0,                       0 },
31237 #endif
31238
31239 #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
31240
31241 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
31242   { "GetFullPathNameA",        (SYSCALL)GetFullPathNameA,        0 },
31243 #else
31244   { "GetFullPathNameA",        (SYSCALL)0,                       0 },
31245 #endif
31246
31247 #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
31248         LPSTR*))aSyscall[24].pCurrent)
31249
31250 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
31251   { "GetFullPathNameW",        (SYSCALL)GetFullPathNameW,        0 },
31252 #else
31253   { "GetFullPathNameW",        (SYSCALL)0,                       0 },
31254 #endif
31255
31256 #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
31257         LPWSTR*))aSyscall[25].pCurrent)
31258
31259   { "GetLastError",            (SYSCALL)GetLastError,            0 },
31260
31261 #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
31262
31263 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
31264 #if SQLITE_OS_WINCE
31265   /* The GetProcAddressA() routine is only available on Windows CE. */
31266   { "GetProcAddressA",         (SYSCALL)GetProcAddressA,         0 },
31267 #else
31268   /* All other Windows platforms expect GetProcAddress() to take
31269   ** an ANSI string regardless of the _UNICODE setting */
31270   { "GetProcAddressA",         (SYSCALL)GetProcAddress,          0 },
31271 #endif
31272 #else
31273   { "GetProcAddressA",         (SYSCALL)0,                       0 },
31274 #endif
31275
31276 #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
31277         LPCSTR))aSyscall[27].pCurrent)
31278
31279 #if !SQLITE_OS_WINRT
31280   { "GetSystemInfo",           (SYSCALL)GetSystemInfo,           0 },
31281 #else
31282   { "GetSystemInfo",           (SYSCALL)0,                       0 },
31283 #endif
31284
31285 #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
31286
31287   { "GetSystemTime",           (SYSCALL)GetSystemTime,           0 },
31288
31289 #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
31290
31291 #if !SQLITE_OS_WINCE
31292   { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
31293 #else
31294   { "GetSystemTimeAsFileTime", (SYSCALL)0,                       0 },
31295 #endif
31296
31297 #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
31298         LPFILETIME))aSyscall[30].pCurrent)
31299
31300 #if defined(SQLITE_WIN32_HAS_ANSI)
31301   { "GetTempPathA",            (SYSCALL)GetTempPathA,            0 },
31302 #else
31303   { "GetTempPathA",            (SYSCALL)0,                       0 },
31304 #endif
31305
31306 #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
31307
31308 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
31309   { "GetTempPathW",            (SYSCALL)GetTempPathW,            0 },
31310 #else
31311   { "GetTempPathW",            (SYSCALL)0,                       0 },
31312 #endif
31313
31314 #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
31315
31316 #if !SQLITE_OS_WINRT
31317   { "GetTickCount",            (SYSCALL)GetTickCount,            0 },
31318 #else
31319   { "GetTickCount",            (SYSCALL)0,                       0 },
31320 #endif
31321
31322 #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
31323
31324 #if defined(SQLITE_WIN32_HAS_ANSI)
31325   { "GetVersionExA",           (SYSCALL)GetVersionExA,           0 },
31326 #else
31327   { "GetVersionExA",           (SYSCALL)0,                       0 },
31328 #endif
31329
31330 #define osGetVersionExA ((BOOL(WINAPI*)( \
31331         LPOSVERSIONINFOA))aSyscall[34].pCurrent)
31332
31333   { "HeapAlloc",               (SYSCALL)HeapAlloc,               0 },
31334
31335 #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
31336         SIZE_T))aSyscall[35].pCurrent)
31337
31338 #if !SQLITE_OS_WINRT
31339   { "HeapCreate",              (SYSCALL)HeapCreate,              0 },
31340 #else
31341   { "HeapCreate",              (SYSCALL)0,                       0 },
31342 #endif
31343
31344 #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
31345         SIZE_T))aSyscall[36].pCurrent)
31346
31347 #if !SQLITE_OS_WINRT
31348   { "HeapDestroy",             (SYSCALL)HeapDestroy,             0 },
31349 #else
31350   { "HeapDestroy",             (SYSCALL)0,                       0 },
31351 #endif
31352
31353 #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[37].pCurrent)
31354
31355   { "HeapFree",                (SYSCALL)HeapFree,                0 },
31356
31357 #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[38].pCurrent)
31358
31359   { "HeapReAlloc",             (SYSCALL)HeapReAlloc,             0 },
31360
31361 #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
31362         SIZE_T))aSyscall[39].pCurrent)
31363
31364   { "HeapSize",                (SYSCALL)HeapSize,                0 },
31365
31366 #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
31367         LPCVOID))aSyscall[40].pCurrent)
31368
31369 #if !SQLITE_OS_WINRT
31370   { "HeapValidate",            (SYSCALL)HeapValidate,            0 },
31371 #else
31372   { "HeapValidate",            (SYSCALL)0,                       0 },
31373 #endif
31374
31375 #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
31376         LPCVOID))aSyscall[41].pCurrent)
31377
31378 #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
31379   { "LoadLibraryA",            (SYSCALL)LoadLibraryA,            0 },
31380 #else
31381   { "LoadLibraryA",            (SYSCALL)0,                       0 },
31382 #endif
31383
31384 #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[42].pCurrent)
31385
31386 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
31387         !defined(SQLITE_OMIT_LOAD_EXTENSION)
31388   { "LoadLibraryW",            (SYSCALL)LoadLibraryW,            0 },
31389 #else
31390   { "LoadLibraryW",            (SYSCALL)0,                       0 },
31391 #endif
31392
31393 #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[43].pCurrent)
31394
31395 #if !SQLITE_OS_WINRT
31396   { "LocalFree",               (SYSCALL)LocalFree,               0 },
31397 #else
31398   { "LocalFree",               (SYSCALL)0,                       0 },
31399 #endif
31400
31401 #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[44].pCurrent)
31402
31403 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
31404   { "LockFile",                (SYSCALL)LockFile,                0 },
31405 #else
31406   { "LockFile",                (SYSCALL)0,                       0 },
31407 #endif
31408
31409 #ifndef osLockFile
31410 #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
31411         DWORD))aSyscall[45].pCurrent)
31412 #endif
31413
31414 #if !SQLITE_OS_WINCE
31415   { "LockFileEx",              (SYSCALL)LockFileEx,              0 },
31416 #else
31417   { "LockFileEx",              (SYSCALL)0,                       0 },
31418 #endif
31419
31420 #ifndef osLockFileEx
31421 #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
31422         LPOVERLAPPED))aSyscall[46].pCurrent)
31423 #endif
31424
31425 #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL))
31426   { "MapViewOfFile",           (SYSCALL)MapViewOfFile,           0 },
31427 #else
31428   { "MapViewOfFile",           (SYSCALL)0,                       0 },
31429 #endif
31430
31431 #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
31432         SIZE_T))aSyscall[47].pCurrent)
31433
31434   { "MultiByteToWideChar",     (SYSCALL)MultiByteToWideChar,     0 },
31435
31436 #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
31437         int))aSyscall[48].pCurrent)
31438
31439   { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
31440
31441 #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
31442         LARGE_INTEGER*))aSyscall[49].pCurrent)
31443
31444   { "ReadFile",                (SYSCALL)ReadFile,                0 },
31445
31446 #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
31447         LPOVERLAPPED))aSyscall[50].pCurrent)
31448
31449   { "SetEndOfFile",            (SYSCALL)SetEndOfFile,            0 },
31450
31451 #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[51].pCurrent)
31452
31453 #if !SQLITE_OS_WINRT
31454   { "SetFilePointer",          (SYSCALL)SetFilePointer,          0 },
31455 #else
31456   { "SetFilePointer",          (SYSCALL)0,                       0 },
31457 #endif
31458
31459 #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
31460         DWORD))aSyscall[52].pCurrent)
31461
31462 #if !SQLITE_OS_WINRT
31463   { "Sleep",                   (SYSCALL)Sleep,                   0 },
31464 #else
31465   { "Sleep",                   (SYSCALL)0,                       0 },
31466 #endif
31467
31468 #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[53].pCurrent)
31469
31470   { "SystemTimeToFileTime",    (SYSCALL)SystemTimeToFileTime,    0 },
31471
31472 #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
31473         LPFILETIME))aSyscall[54].pCurrent)
31474
31475 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
31476   { "UnlockFile",              (SYSCALL)UnlockFile,              0 },
31477 #else
31478   { "UnlockFile",              (SYSCALL)0,                       0 },
31479 #endif
31480
31481 #ifndef osUnlockFile
31482 #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
31483         DWORD))aSyscall[55].pCurrent)
31484 #endif
31485
31486 #if !SQLITE_OS_WINCE
31487   { "UnlockFileEx",            (SYSCALL)UnlockFileEx,            0 },
31488 #else
31489   { "UnlockFileEx",            (SYSCALL)0,                       0 },
31490 #endif
31491
31492 #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
31493         LPOVERLAPPED))aSyscall[56].pCurrent)
31494
31495 #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL)
31496   { "UnmapViewOfFile",         (SYSCALL)UnmapViewOfFile,         0 },
31497 #else
31498   { "UnmapViewOfFile",         (SYSCALL)0,                       0 },
31499 #endif
31500
31501 #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[57].pCurrent)
31502
31503   { "WideCharToMultiByte",     (SYSCALL)WideCharToMultiByte,     0 },
31504
31505 #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
31506         LPCSTR,LPBOOL))aSyscall[58].pCurrent)
31507
31508   { "WriteFile",               (SYSCALL)WriteFile,               0 },
31509
31510 #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
31511         LPOVERLAPPED))aSyscall[59].pCurrent)
31512
31513 #if SQLITE_OS_WINRT
31514   { "CreateEventExW",          (SYSCALL)CreateEventExW,          0 },
31515 #else
31516   { "CreateEventExW",          (SYSCALL)0,                       0 },
31517 #endif
31518
31519 #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
31520         DWORD,DWORD))aSyscall[60].pCurrent)
31521
31522 #if !SQLITE_OS_WINRT
31523   { "WaitForSingleObject",     (SYSCALL)WaitForSingleObject,     0 },
31524 #else
31525   { "WaitForSingleObject",     (SYSCALL)0,                       0 },
31526 #endif
31527
31528 #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
31529         DWORD))aSyscall[61].pCurrent)
31530
31531 #if SQLITE_OS_WINRT
31532   { "WaitForSingleObjectEx",   (SYSCALL)WaitForSingleObjectEx,   0 },
31533 #else
31534   { "WaitForSingleObjectEx",   (SYSCALL)0,                       0 },
31535 #endif
31536
31537 #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
31538         BOOL))aSyscall[62].pCurrent)
31539
31540 #if SQLITE_OS_WINRT
31541   { "SetFilePointerEx",        (SYSCALL)SetFilePointerEx,        0 },
31542 #else
31543   { "SetFilePointerEx",        (SYSCALL)0,                       0 },
31544 #endif
31545
31546 #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
31547         PLARGE_INTEGER,DWORD))aSyscall[63].pCurrent)
31548
31549 #if SQLITE_OS_WINRT
31550   { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
31551 #else
31552   { "GetFileInformationByHandleEx", (SYSCALL)0,                  0 },
31553 #endif
31554
31555 #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
31556         FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[64].pCurrent)
31557
31558 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
31559   { "MapViewOfFileFromApp",    (SYSCALL)MapViewOfFileFromApp,    0 },
31560 #else
31561   { "MapViewOfFileFromApp",    (SYSCALL)0,                       0 },
31562 #endif
31563
31564 #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
31565         SIZE_T))aSyscall[65].pCurrent)
31566
31567 #if SQLITE_OS_WINRT
31568   { "CreateFile2",             (SYSCALL)CreateFile2,             0 },
31569 #else
31570   { "CreateFile2",             (SYSCALL)0,                       0 },
31571 #endif
31572
31573 #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
31574         LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[66].pCurrent)
31575
31576 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
31577   { "LoadPackagedLibrary",     (SYSCALL)LoadPackagedLibrary,     0 },
31578 #else
31579   { "LoadPackagedLibrary",     (SYSCALL)0,                       0 },
31580 #endif
31581
31582 #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
31583         DWORD))aSyscall[67].pCurrent)
31584
31585 #if SQLITE_OS_WINRT
31586   { "GetTickCount64",          (SYSCALL)GetTickCount64,          0 },
31587 #else
31588   { "GetTickCount64",          (SYSCALL)0,                       0 },
31589 #endif
31590
31591 #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[68].pCurrent)
31592
31593 #if SQLITE_OS_WINRT
31594   { "GetNativeSystemInfo",     (SYSCALL)GetNativeSystemInfo,     0 },
31595 #else
31596   { "GetNativeSystemInfo",     (SYSCALL)0,                       0 },
31597 #endif
31598
31599 #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
31600         LPSYSTEM_INFO))aSyscall[69].pCurrent)
31601
31602 #if defined(SQLITE_WIN32_HAS_ANSI)
31603   { "OutputDebugStringA",      (SYSCALL)OutputDebugStringA,      0 },
31604 #else
31605   { "OutputDebugStringA",      (SYSCALL)0,                       0 },
31606 #endif
31607
31608 #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[70].pCurrent)
31609
31610 #if defined(SQLITE_WIN32_HAS_WIDE)
31611   { "OutputDebugStringW",      (SYSCALL)OutputDebugStringW,      0 },
31612 #else
31613   { "OutputDebugStringW",      (SYSCALL)0,                       0 },
31614 #endif
31615
31616 #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[71].pCurrent)
31617
31618   { "GetProcessHeap",          (SYSCALL)GetProcessHeap,          0 },
31619
31620 #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[72].pCurrent)
31621
31622 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
31623   { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
31624 #else
31625   { "CreateFileMappingFromApp", (SYSCALL)0,                      0 },
31626 #endif
31627
31628 #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
31629         LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[73].pCurrent)
31630
31631 }; /* End of the overrideable system calls */
31632
31633 /*
31634 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
31635 ** "win32" VFSes.  Return SQLITE_OK opon successfully updating the
31636 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
31637 ** system call named zName.
31638 */
31639 static int winSetSystemCall(
31640   sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
31641   const char *zName,            /* Name of system call to override */
31642   sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
31643 ){
31644   unsigned int i;
31645   int rc = SQLITE_NOTFOUND;
31646
31647   UNUSED_PARAMETER(pNotUsed);
31648   if( zName==0 ){
31649     /* If no zName is given, restore all system calls to their default
31650     ** settings and return NULL
31651     */
31652     rc = SQLITE_OK;
31653     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
31654       if( aSyscall[i].pDefault ){
31655         aSyscall[i].pCurrent = aSyscall[i].pDefault;
31656       }
31657     }
31658   }else{
31659     /* If zName is specified, operate on only the one system call
31660     ** specified.
31661     */
31662     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
31663       if( strcmp(zName, aSyscall[i].zName)==0 ){
31664         if( aSyscall[i].pDefault==0 ){
31665           aSyscall[i].pDefault = aSyscall[i].pCurrent;
31666         }
31667         rc = SQLITE_OK;
31668         if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
31669         aSyscall[i].pCurrent = pNewFunc;
31670         break;
31671       }
31672     }
31673   }
31674   return rc;
31675 }
31676
31677 /*
31678 ** Return the value of a system call.  Return NULL if zName is not a
31679 ** recognized system call name.  NULL is also returned if the system call
31680 ** is currently undefined.
31681 */
31682 static sqlite3_syscall_ptr winGetSystemCall(
31683   sqlite3_vfs *pNotUsed,
31684   const char *zName
31685 ){
31686   unsigned int i;
31687
31688   UNUSED_PARAMETER(pNotUsed);
31689   for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
31690     if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
31691   }
31692   return 0;
31693 }
31694
31695 /*
31696 ** Return the name of the first system call after zName.  If zName==NULL
31697 ** then return the name of the first system call.  Return NULL if zName
31698 ** is the last system call or if zName is not the name of a valid
31699 ** system call.
31700 */
31701 static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
31702   int i = -1;
31703
31704   UNUSED_PARAMETER(p);
31705   if( zName ){
31706     for(i=0; i<ArraySize(aSyscall)-1; i++){
31707       if( strcmp(zName, aSyscall[i].zName)==0 ) break;
31708     }
31709   }
31710   for(i++; i<ArraySize(aSyscall); i++){
31711     if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
31712   }
31713   return 0;
31714 }
31715
31716 /*
31717 ** This function outputs the specified (ANSI) string to the Win32 debugger
31718 ** (if available).
31719 */
31720
31721 SQLITE_API void sqlite3_win32_write_debug(const char *zBuf, int nBuf){
31722   char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
31723   int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
31724   if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
31725   assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
31726 #if defined(SQLITE_WIN32_HAS_ANSI)
31727   if( nMin>0 ){
31728     memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
31729     memcpy(zDbgBuf, zBuf, nMin);
31730     osOutputDebugStringA(zDbgBuf);
31731   }else{
31732     osOutputDebugStringA(zBuf);
31733   }
31734 #elif defined(SQLITE_WIN32_HAS_WIDE)
31735   memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
31736   if ( osMultiByteToWideChar(
31737           osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
31738           nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
31739     return;
31740   }
31741   osOutputDebugStringW((LPCWSTR)zDbgBuf);
31742 #else
31743   if( nMin>0 ){
31744     memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
31745     memcpy(zDbgBuf, zBuf, nMin);
31746     fprintf(stderr, "%s", zDbgBuf);
31747   }else{
31748     fprintf(stderr, "%s", zBuf);
31749   }
31750 #endif
31751 }
31752
31753 /*
31754 ** The following routine suspends the current thread for at least ms
31755 ** milliseconds.  This is equivalent to the Win32 Sleep() interface.
31756 */
31757 #if SQLITE_OS_WINRT
31758 static HANDLE sleepObj = NULL;
31759 #endif
31760
31761 SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){
31762 #if SQLITE_OS_WINRT
31763   if ( sleepObj==NULL ){
31764     sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
31765                                 SYNCHRONIZE);
31766   }
31767   assert( sleepObj!=NULL );
31768   osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
31769 #else
31770   osSleep(milliseconds);
31771 #endif
31772 }
31773
31774 /*
31775 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
31776 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
31777 **
31778 ** Here is an interesting observation:  Win95, Win98, and WinME lack
31779 ** the LockFileEx() API.  But we can still statically link against that
31780 ** API as long as we don't call it when running Win95/98/ME.  A call to
31781 ** this routine is used to determine if the host is Win95/98/ME or
31782 ** WinNT/2K/XP so that we will know whether or not we can safely call
31783 ** the LockFileEx() API.
31784 */
31785 #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
31786 # define isNT()  (1)
31787 #elif !defined(SQLITE_WIN32_HAS_WIDE)
31788 # define isNT()  (0)
31789 #else
31790   static int isNT(void){
31791     if( sqlite3_os_type==0 ){
31792       OSVERSIONINFOA sInfo;
31793       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
31794       osGetVersionExA(&sInfo);
31795       sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
31796     }
31797     return sqlite3_os_type==2;
31798   }
31799 #endif
31800
31801 #ifdef SQLITE_WIN32_MALLOC
31802 /*
31803 ** Allocate nBytes of memory.
31804 */
31805 static void *winMemMalloc(int nBytes){
31806   HANDLE hHeap;
31807   void *p;
31808
31809   winMemAssertMagic();
31810   hHeap = winMemGetHeap();
31811   assert( hHeap!=0 );
31812   assert( hHeap!=INVALID_HANDLE_VALUE );
31813 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
31814   assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
31815 #endif
31816   assert( nBytes>=0 );
31817   p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
31818   if( !p ){
31819     sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%d), heap=%p",
31820                 nBytes, osGetLastError(), (void*)hHeap);
31821   }
31822   return p;
31823 }
31824
31825 /*
31826 ** Free memory.
31827 */
31828 static void winMemFree(void *pPrior){
31829   HANDLE hHeap;
31830
31831   winMemAssertMagic();
31832   hHeap = winMemGetHeap();
31833   assert( hHeap!=0 );
31834   assert( hHeap!=INVALID_HANDLE_VALUE );
31835 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
31836   assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
31837 #endif
31838   if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
31839   if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
31840     sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%d), heap=%p",
31841                 pPrior, osGetLastError(), (void*)hHeap);
31842   }
31843 }
31844
31845 /*
31846 ** Change the size of an existing memory allocation
31847 */
31848 static void *winMemRealloc(void *pPrior, int nBytes){
31849   HANDLE hHeap;
31850   void *p;
31851
31852   winMemAssertMagic();
31853   hHeap = winMemGetHeap();
31854   assert( hHeap!=0 );
31855   assert( hHeap!=INVALID_HANDLE_VALUE );
31856 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
31857   assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
31858 #endif
31859   assert( nBytes>=0 );
31860   if( !pPrior ){
31861     p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
31862   }else{
31863     p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
31864   }
31865   if( !p ){
31866     sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%d), heap=%p",
31867                 pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
31868                 (void*)hHeap);
31869   }
31870   return p;
31871 }
31872
31873 /*
31874 ** Return the size of an outstanding allocation, in bytes.
31875 */
31876 static int winMemSize(void *p){
31877   HANDLE hHeap;
31878   SIZE_T n;
31879
31880   winMemAssertMagic();
31881   hHeap = winMemGetHeap();
31882   assert( hHeap!=0 );
31883   assert( hHeap!=INVALID_HANDLE_VALUE );
31884 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
31885   assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
31886 #endif
31887   if( !p ) return 0;
31888   n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
31889   if( n==(SIZE_T)-1 ){
31890     sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%d), heap=%p",
31891                 p, osGetLastError(), (void*)hHeap);
31892     return 0;
31893   }
31894   return (int)n;
31895 }
31896
31897 /*
31898 ** Round up a request size to the next valid allocation size.
31899 */
31900 static int winMemRoundup(int n){
31901   return n;
31902 }
31903
31904 /*
31905 ** Initialize this module.
31906 */
31907 static int winMemInit(void *pAppData){
31908   winMemData *pWinMemData = (winMemData *)pAppData;
31909
31910   if( !pWinMemData ) return SQLITE_ERROR;
31911   assert( pWinMemData->magic==WINMEM_MAGIC );
31912
31913 #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
31914   if( !pWinMemData->hHeap ){
31915     pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
31916                                       SQLITE_WIN32_HEAP_INIT_SIZE,
31917                                       SQLITE_WIN32_HEAP_MAX_SIZE);
31918     if( !pWinMemData->hHeap ){
31919       sqlite3_log(SQLITE_NOMEM,
31920           "failed to HeapCreate (%d), flags=%u, initSize=%u, maxSize=%u",
31921           osGetLastError(), SQLITE_WIN32_HEAP_FLAGS,
31922           SQLITE_WIN32_HEAP_INIT_SIZE, SQLITE_WIN32_HEAP_MAX_SIZE);
31923       return SQLITE_NOMEM;
31924     }
31925     pWinMemData->bOwned = TRUE;
31926     assert( pWinMemData->bOwned );
31927   }
31928 #else
31929   pWinMemData->hHeap = osGetProcessHeap();
31930   if( !pWinMemData->hHeap ){
31931     sqlite3_log(SQLITE_NOMEM,
31932         "failed to GetProcessHeap (%d)", osGetLastError());
31933     return SQLITE_NOMEM;
31934   }
31935   pWinMemData->bOwned = FALSE;
31936   assert( !pWinMemData->bOwned );
31937 #endif
31938   assert( pWinMemData->hHeap!=0 );
31939   assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
31940 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
31941   assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
31942 #endif
31943   return SQLITE_OK;
31944 }
31945
31946 /*
31947 ** Deinitialize this module.
31948 */
31949 static void winMemShutdown(void *pAppData){
31950   winMemData *pWinMemData = (winMemData *)pAppData;
31951
31952   if( !pWinMemData ) return;
31953   if( pWinMemData->hHeap ){
31954     assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
31955 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
31956     assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
31957 #endif
31958     if( pWinMemData->bOwned ){
31959       if( !osHeapDestroy(pWinMemData->hHeap) ){
31960         sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%d), heap=%p",
31961                     osGetLastError(), (void*)pWinMemData->hHeap);
31962       }
31963       pWinMemData->bOwned = FALSE;
31964     }
31965     pWinMemData->hHeap = NULL;
31966   }
31967 }
31968
31969 /*
31970 ** Populate the low-level memory allocation function pointers in
31971 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
31972 ** arguments specify the block of memory to manage.
31973 **
31974 ** This routine is only called by sqlite3_config(), and therefore
31975 ** is not required to be threadsafe (it is not).
31976 */
31977 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
31978   static const sqlite3_mem_methods winMemMethods = {
31979     winMemMalloc,
31980     winMemFree,
31981     winMemRealloc,
31982     winMemSize,
31983     winMemRoundup,
31984     winMemInit,
31985     winMemShutdown,
31986     &win_mem_data
31987   };
31988   return &winMemMethods;
31989 }
31990
31991 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
31992   sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
31993 }
31994 #endif /* SQLITE_WIN32_MALLOC */
31995
31996 /*
31997 ** Convert a UTF-8 string to Microsoft Unicode (UTF-16?). 
31998 **
31999 ** Space to hold the returned string is obtained from malloc.
32000 */
32001 static LPWSTR utf8ToUnicode(const char *zFilename){
32002   int nChar;
32003   LPWSTR zWideFilename;
32004
32005   nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
32006   if( nChar==0 ){
32007     return 0;
32008   }
32009   zWideFilename = sqlite3MallocZero( nChar*sizeof(zWideFilename[0]) );
32010   if( zWideFilename==0 ){
32011     return 0;
32012   }
32013   nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
32014                                 nChar);
32015   if( nChar==0 ){
32016     sqlite3_free(zWideFilename);
32017     zWideFilename = 0;
32018   }
32019   return zWideFilename;
32020 }
32021
32022 /*
32023 ** Convert Microsoft Unicode to UTF-8.  Space to hold the returned string is
32024 ** obtained from sqlite3_malloc().
32025 */
32026 static char *unicodeToUtf8(LPCWSTR zWideFilename){
32027   int nByte;
32028   char *zFilename;
32029
32030   nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
32031   if( nByte == 0 ){
32032     return 0;
32033   }
32034   zFilename = sqlite3MallocZero( nByte );
32035   if( zFilename==0 ){
32036     return 0;
32037   }
32038   nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
32039                                 0, 0);
32040   if( nByte == 0 ){
32041     sqlite3_free(zFilename);
32042     zFilename = 0;
32043   }
32044   return zFilename;
32045 }
32046
32047 /*
32048 ** Convert an ANSI string to Microsoft Unicode, based on the
32049 ** current codepage settings for file apis.
32050 ** 
32051 ** Space to hold the returned string is obtained
32052 ** from sqlite3_malloc.
32053 */
32054 static LPWSTR mbcsToUnicode(const char *zFilename){
32055   int nByte;
32056   LPWSTR zMbcsFilename;
32057   int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
32058
32059   nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, NULL,
32060                                 0)*sizeof(WCHAR);
32061   if( nByte==0 ){
32062     return 0;
32063   }
32064   zMbcsFilename = sqlite3MallocZero( nByte*sizeof(zMbcsFilename[0]) );
32065   if( zMbcsFilename==0 ){
32066     return 0;
32067   }
32068   nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename,
32069                                 nByte);
32070   if( nByte==0 ){
32071     sqlite3_free(zMbcsFilename);
32072     zMbcsFilename = 0;
32073   }
32074   return zMbcsFilename;
32075 }
32076
32077 /*
32078 ** Convert Microsoft Unicode to multi-byte character string, based on the
32079 ** user's ANSI codepage.
32080 **
32081 ** Space to hold the returned string is obtained from
32082 ** sqlite3_malloc().
32083 */
32084 static char *unicodeToMbcs(LPCWSTR zWideFilename){
32085   int nByte;
32086   char *zFilename;
32087   int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
32088
32089   nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
32090   if( nByte == 0 ){
32091     return 0;
32092   }
32093   zFilename = sqlite3MallocZero( nByte );
32094   if( zFilename==0 ){
32095     return 0;
32096   }
32097   nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename,
32098                                 nByte, 0, 0);
32099   if( nByte == 0 ){
32100     sqlite3_free(zFilename);
32101     zFilename = 0;
32102   }
32103   return zFilename;
32104 }
32105
32106 /*
32107 ** Convert multibyte character string to UTF-8.  Space to hold the
32108 ** returned string is obtained from sqlite3_malloc().
32109 */
32110 SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
32111   char *zFilenameUtf8;
32112   LPWSTR zTmpWide;
32113
32114   zTmpWide = mbcsToUnicode(zFilename);
32115   if( zTmpWide==0 ){
32116     return 0;
32117   }
32118   zFilenameUtf8 = unicodeToUtf8(zTmpWide);
32119   sqlite3_free(zTmpWide);
32120   return zFilenameUtf8;
32121 }
32122
32123 /*
32124 ** Convert UTF-8 to multibyte character string.  Space to hold the 
32125 ** returned string is obtained from sqlite3_malloc().
32126 */
32127 SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zFilename){
32128   char *zFilenameMbcs;
32129   LPWSTR zTmpWide;
32130
32131   zTmpWide = utf8ToUnicode(zFilename);
32132   if( zTmpWide==0 ){
32133     return 0;
32134   }
32135   zFilenameMbcs = unicodeToMbcs(zTmpWide);
32136   sqlite3_free(zTmpWide);
32137   return zFilenameMbcs;
32138 }
32139
32140 /*
32141 ** This function sets the data directory or the temporary directory based on
32142 ** the provided arguments.  The type argument must be 1 in order to set the
32143 ** data directory or 2 in order to set the temporary directory.  The zValue
32144 ** argument is the name of the directory to use.  The return value will be
32145 ** SQLITE_OK if successful.
32146 */
32147 SQLITE_API int sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){
32148   char **ppDirectory = 0;
32149 #ifndef SQLITE_OMIT_AUTOINIT
32150   int rc = sqlite3_initialize();
32151   if( rc ) return rc;
32152 #endif
32153   if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
32154     ppDirectory = &sqlite3_data_directory;
32155   }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
32156     ppDirectory = &sqlite3_temp_directory;
32157   }
32158   assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
32159           || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
32160   );
32161   assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
32162   if( ppDirectory ){
32163     char *zValueUtf8 = 0;
32164     if( zValue && zValue[0] ){
32165       zValueUtf8 = unicodeToUtf8(zValue);
32166       if ( zValueUtf8==0 ){
32167         return SQLITE_NOMEM;
32168       }
32169     }
32170     sqlite3_free(*ppDirectory);
32171     *ppDirectory = zValueUtf8;
32172     return SQLITE_OK;
32173   }
32174   return SQLITE_ERROR;
32175 }
32176
32177 /*
32178 ** The return value of getLastErrorMsg
32179 ** is zero if the error message fits in the buffer, or non-zero
32180 ** otherwise (if the message was truncated).
32181 */
32182 static int getLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
32183   /* FormatMessage returns 0 on failure.  Otherwise it
32184   ** returns the number of TCHARs written to the output
32185   ** buffer, excluding the terminating null char.
32186   */
32187   DWORD dwLen = 0;
32188   char *zOut = 0;
32189
32190   if( isNT() ){
32191 #if SQLITE_OS_WINRT
32192     WCHAR zTempWide[MAX_PATH+1]; /* NOTE: Somewhat arbitrary. */
32193     dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
32194                              FORMAT_MESSAGE_IGNORE_INSERTS,
32195                              NULL,
32196                              lastErrno,
32197                              0,
32198                              zTempWide,
32199                              MAX_PATH,
32200                              0);
32201 #else
32202     LPWSTR zTempWide = NULL;
32203     dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
32204                              FORMAT_MESSAGE_FROM_SYSTEM |
32205                              FORMAT_MESSAGE_IGNORE_INSERTS,
32206                              NULL,
32207                              lastErrno,
32208                              0,
32209                              (LPWSTR) &zTempWide,
32210                              0,
32211                              0);
32212 #endif
32213     if( dwLen > 0 ){
32214       /* allocate a buffer and convert to UTF8 */
32215       sqlite3BeginBenignMalloc();
32216       zOut = unicodeToUtf8(zTempWide);
32217       sqlite3EndBenignMalloc();
32218 #if !SQLITE_OS_WINRT
32219       /* free the system buffer allocated by FormatMessage */
32220       osLocalFree(zTempWide);
32221 #endif
32222     }
32223   }
32224 #ifdef SQLITE_WIN32_HAS_ANSI
32225   else{
32226     char *zTemp = NULL;
32227     dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
32228                              FORMAT_MESSAGE_FROM_SYSTEM |
32229                              FORMAT_MESSAGE_IGNORE_INSERTS,
32230                              NULL,
32231                              lastErrno,
32232                              0,
32233                              (LPSTR) &zTemp,
32234                              0,
32235                              0);
32236     if( dwLen > 0 ){
32237       /* allocate a buffer and convert to UTF8 */
32238       sqlite3BeginBenignMalloc();
32239       zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
32240       sqlite3EndBenignMalloc();
32241       /* free the system buffer allocated by FormatMessage */
32242       osLocalFree(zTemp);
32243     }
32244   }
32245 #endif
32246   if( 0 == dwLen ){
32247     sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
32248   }else{
32249     /* copy a maximum of nBuf chars to output buffer */
32250     sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
32251     /* free the UTF8 buffer */
32252     sqlite3_free(zOut);
32253   }
32254   return 0;
32255 }
32256
32257 /*
32258 **
32259 ** This function - winLogErrorAtLine() - is only ever called via the macro
32260 ** winLogError().
32261 **
32262 ** This routine is invoked after an error occurs in an OS function.
32263 ** It logs a message using sqlite3_log() containing the current value of
32264 ** error code and, if possible, the human-readable equivalent from 
32265 ** FormatMessage.
32266 **
32267 ** The first argument passed to the macro should be the error code that
32268 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN). 
32269 ** The two subsequent arguments should be the name of the OS function that
32270 ** failed and the associated file-system path, if any.
32271 */
32272 #define winLogError(a,b,c,d)   winLogErrorAtLine(a,b,c,d,__LINE__)
32273 static int winLogErrorAtLine(
32274   int errcode,                    /* SQLite error code */
32275   DWORD lastErrno,                /* Win32 last error */
32276   const char *zFunc,              /* Name of OS function that failed */
32277   const char *zPath,              /* File path associated with error */
32278   int iLine                       /* Source line number where error occurred */
32279 ){
32280   char zMsg[500];                 /* Human readable error text */
32281   int i;                          /* Loop counter */
32282
32283   zMsg[0] = 0;
32284   getLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
32285   assert( errcode!=SQLITE_OK );
32286   if( zPath==0 ) zPath = "";
32287   for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
32288   zMsg[i] = 0;
32289   sqlite3_log(errcode,
32290       "os_win.c:%d: (%lu) %s(%s) - %s",
32291       iLine, lastErrno, zFunc, zPath, zMsg
32292   );
32293
32294   return errcode;
32295 }
32296
32297 /*
32298 ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
32299 ** will be retried following a locking error - probably caused by 
32300 ** antivirus software.  Also the initial delay before the first retry.
32301 ** The delay increases linearly with each retry.
32302 */
32303 #ifndef SQLITE_WIN32_IOERR_RETRY
32304 # define SQLITE_WIN32_IOERR_RETRY 10
32305 #endif
32306 #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
32307 # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
32308 #endif
32309 static int win32IoerrRetry = SQLITE_WIN32_IOERR_RETRY;
32310 static int win32IoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
32311
32312 /*
32313 ** If a ReadFile() or WriteFile() error occurs, invoke this routine
32314 ** to see if it should be retried.  Return TRUE to retry.  Return FALSE
32315 ** to give up with an error.
32316 */
32317 static int retryIoerr(int *pnRetry, DWORD *pError){
32318   DWORD e = osGetLastError();
32319   if( *pnRetry>=win32IoerrRetry ){
32320     if( pError ){
32321       *pError = e;
32322     }
32323     return 0;
32324   }
32325   if( e==ERROR_ACCESS_DENIED ||
32326       e==ERROR_LOCK_VIOLATION ||
32327       e==ERROR_SHARING_VIOLATION ){
32328     sqlite3_win32_sleep(win32IoerrRetryDelay*(1+*pnRetry));
32329     ++*pnRetry;
32330     return 1;
32331   }
32332   if( pError ){
32333     *pError = e;
32334   }
32335   return 0;
32336 }
32337
32338 /*
32339 ** Log a I/O error retry episode.
32340 */
32341 static void logIoerr(int nRetry){
32342   if( nRetry ){
32343     sqlite3_log(SQLITE_IOERR, 
32344       "delayed %dms for lock/sharing conflict",
32345       win32IoerrRetryDelay*nRetry*(nRetry+1)/2
32346     );
32347   }
32348 }
32349
32350 #if SQLITE_OS_WINCE
32351 /*************************************************************************
32352 ** This section contains code for WinCE only.
32353 */
32354 #if !defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API
32355 /*
32356 ** The MSVC CRT on Windows CE may not have a localtime() function.  So
32357 ** create a substitute.
32358 */
32359 /* #include <time.h> */
32360 struct tm *__cdecl localtime(const time_t *t)
32361 {
32362   static struct tm y;
32363   FILETIME uTm, lTm;
32364   SYSTEMTIME pTm;
32365   sqlite3_int64 t64;
32366   t64 = *t;
32367   t64 = (t64 + 11644473600)*10000000;
32368   uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
32369   uTm.dwHighDateTime= (DWORD)(t64 >> 32);
32370   osFileTimeToLocalFileTime(&uTm,&lTm);
32371   osFileTimeToSystemTime(&lTm,&pTm);
32372   y.tm_year = pTm.wYear - 1900;
32373   y.tm_mon = pTm.wMonth - 1;
32374   y.tm_wday = pTm.wDayOfWeek;
32375   y.tm_mday = pTm.wDay;
32376   y.tm_hour = pTm.wHour;
32377   y.tm_min = pTm.wMinute;
32378   y.tm_sec = pTm.wSecond;
32379   return &y;
32380 }
32381 #endif
32382
32383 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
32384
32385 /*
32386 ** Acquire a lock on the handle h
32387 */
32388 static void winceMutexAcquire(HANDLE h){
32389    DWORD dwErr;
32390    do {
32391      dwErr = osWaitForSingleObject(h, INFINITE);
32392    } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
32393 }
32394 /*
32395 ** Release a lock acquired by winceMutexAcquire()
32396 */
32397 #define winceMutexRelease(h) ReleaseMutex(h)
32398
32399 /*
32400 ** Create the mutex and shared memory used for locking in the file
32401 ** descriptor pFile
32402 */
32403 static int winceCreateLock(const char *zFilename, winFile *pFile){
32404   LPWSTR zTok;
32405   LPWSTR zName;
32406   DWORD lastErrno;
32407   BOOL bLogged = FALSE;
32408   BOOL bInit = TRUE;
32409
32410   zName = utf8ToUnicode(zFilename);
32411   if( zName==0 ){
32412     /* out of memory */
32413     return SQLITE_IOERR_NOMEM;
32414   }
32415
32416   /* Initialize the local lockdata */
32417   memset(&pFile->local, 0, sizeof(pFile->local));
32418
32419   /* Replace the backslashes from the filename and lowercase it
32420   ** to derive a mutex name. */
32421   zTok = osCharLowerW(zName);
32422   for (;*zTok;zTok++){
32423     if (*zTok == '\\') *zTok = '_';
32424   }
32425
32426   /* Create/open the named mutex */
32427   pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
32428   if (!pFile->hMutex){
32429     pFile->lastErrno = osGetLastError();
32430     winLogError(SQLITE_IOERR, pFile->lastErrno,
32431                 "winceCreateLock1", zFilename);
32432     sqlite3_free(zName);
32433     return SQLITE_IOERR;
32434   }
32435
32436   /* Acquire the mutex before continuing */
32437   winceMutexAcquire(pFile->hMutex);
32438   
32439   /* Since the names of named mutexes, semaphores, file mappings etc are 
32440   ** case-sensitive, take advantage of that by uppercasing the mutex name
32441   ** and using that as the shared filemapping name.
32442   */
32443   osCharUpperW(zName);
32444   pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
32445                                         PAGE_READWRITE, 0, sizeof(winceLock),
32446                                         zName);  
32447
32448   /* Set a flag that indicates we're the first to create the memory so it 
32449   ** must be zero-initialized */
32450   lastErrno = osGetLastError();
32451   if (lastErrno == ERROR_ALREADY_EXISTS){
32452     bInit = FALSE;
32453   }
32454
32455   sqlite3_free(zName);
32456
32457   /* If we succeeded in making the shared memory handle, map it. */
32458   if( pFile->hShared ){
32459     pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared, 
32460              FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
32461     /* If mapping failed, close the shared memory handle and erase it */
32462     if( !pFile->shared ){
32463       pFile->lastErrno = osGetLastError();
32464       winLogError(SQLITE_IOERR, pFile->lastErrno,
32465                   "winceCreateLock2", zFilename);
32466       bLogged = TRUE;
32467       osCloseHandle(pFile->hShared);
32468       pFile->hShared = NULL;
32469     }
32470   }
32471
32472   /* If shared memory could not be created, then close the mutex and fail */
32473   if( pFile->hShared==NULL ){
32474     if( !bLogged ){
32475       pFile->lastErrno = lastErrno;
32476       winLogError(SQLITE_IOERR, pFile->lastErrno,
32477                   "winceCreateLock3", zFilename);
32478       bLogged = TRUE;
32479     }
32480     winceMutexRelease(pFile->hMutex);
32481     osCloseHandle(pFile->hMutex);
32482     pFile->hMutex = NULL;
32483     return SQLITE_IOERR;
32484   }
32485   
32486   /* Initialize the shared memory if we're supposed to */
32487   if( bInit ){
32488     memset(pFile->shared, 0, sizeof(winceLock));
32489   }
32490
32491   winceMutexRelease(pFile->hMutex);
32492   return SQLITE_OK;
32493 }
32494
32495 /*
32496 ** Destroy the part of winFile that deals with wince locks
32497 */
32498 static void winceDestroyLock(winFile *pFile){
32499   if (pFile->hMutex){
32500     /* Acquire the mutex */
32501     winceMutexAcquire(pFile->hMutex);
32502
32503     /* The following blocks should probably assert in debug mode, but they
32504        are to cleanup in case any locks remained open */
32505     if (pFile->local.nReaders){
32506       pFile->shared->nReaders --;
32507     }
32508     if (pFile->local.bReserved){
32509       pFile->shared->bReserved = FALSE;
32510     }
32511     if (pFile->local.bPending){
32512       pFile->shared->bPending = FALSE;
32513     }
32514     if (pFile->local.bExclusive){
32515       pFile->shared->bExclusive = FALSE;
32516     }
32517
32518     /* De-reference and close our copy of the shared memory handle */
32519     osUnmapViewOfFile(pFile->shared);
32520     osCloseHandle(pFile->hShared);
32521
32522     /* Done with the mutex */
32523     winceMutexRelease(pFile->hMutex);    
32524     osCloseHandle(pFile->hMutex);
32525     pFile->hMutex = NULL;
32526   }
32527 }
32528
32529 /* 
32530 ** An implementation of the LockFile() API of Windows for CE
32531 */
32532 static BOOL winceLockFile(
32533   LPHANDLE phFile,
32534   DWORD dwFileOffsetLow,
32535   DWORD dwFileOffsetHigh,
32536   DWORD nNumberOfBytesToLockLow,
32537   DWORD nNumberOfBytesToLockHigh
32538 ){
32539   winFile *pFile = HANDLE_TO_WINFILE(phFile);
32540   BOOL bReturn = FALSE;
32541
32542   UNUSED_PARAMETER(dwFileOffsetHigh);
32543   UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
32544
32545   if (!pFile->hMutex) return TRUE;
32546   winceMutexAcquire(pFile->hMutex);
32547
32548   /* Wanting an exclusive lock? */
32549   if (dwFileOffsetLow == (DWORD)SHARED_FIRST
32550        && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
32551     if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
32552        pFile->shared->bExclusive = TRUE;
32553        pFile->local.bExclusive = TRUE;
32554        bReturn = TRUE;
32555     }
32556   }
32557
32558   /* Want a read-only lock? */
32559   else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
32560            nNumberOfBytesToLockLow == 1){
32561     if (pFile->shared->bExclusive == 0){
32562       pFile->local.nReaders ++;
32563       if (pFile->local.nReaders == 1){
32564         pFile->shared->nReaders ++;
32565       }
32566       bReturn = TRUE;
32567     }
32568   }
32569
32570   /* Want a pending lock? */
32571   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
32572            && nNumberOfBytesToLockLow == 1){
32573     /* If no pending lock has been acquired, then acquire it */
32574     if (pFile->shared->bPending == 0) {
32575       pFile->shared->bPending = TRUE;
32576       pFile->local.bPending = TRUE;
32577       bReturn = TRUE;
32578     }
32579   }
32580
32581   /* Want a reserved lock? */
32582   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
32583            && nNumberOfBytesToLockLow == 1){
32584     if (pFile->shared->bReserved == 0) {
32585       pFile->shared->bReserved = TRUE;
32586       pFile->local.bReserved = TRUE;
32587       bReturn = TRUE;
32588     }
32589   }
32590
32591   winceMutexRelease(pFile->hMutex);
32592   return bReturn;
32593 }
32594
32595 /*
32596 ** An implementation of the UnlockFile API of Windows for CE
32597 */
32598 static BOOL winceUnlockFile(
32599   LPHANDLE phFile,
32600   DWORD dwFileOffsetLow,
32601   DWORD dwFileOffsetHigh,
32602   DWORD nNumberOfBytesToUnlockLow,
32603   DWORD nNumberOfBytesToUnlockHigh
32604 ){
32605   winFile *pFile = HANDLE_TO_WINFILE(phFile);
32606   BOOL bReturn = FALSE;
32607
32608   UNUSED_PARAMETER(dwFileOffsetHigh);
32609   UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
32610
32611   if (!pFile->hMutex) return TRUE;
32612   winceMutexAcquire(pFile->hMutex);
32613
32614   /* Releasing a reader lock or an exclusive lock */
32615   if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
32616     /* Did we have an exclusive lock? */
32617     if (pFile->local.bExclusive){
32618       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
32619       pFile->local.bExclusive = FALSE;
32620       pFile->shared->bExclusive = FALSE;
32621       bReturn = TRUE;
32622     }
32623
32624     /* Did we just have a reader lock? */
32625     else if (pFile->local.nReaders){
32626       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
32627              || nNumberOfBytesToUnlockLow == 1);
32628       pFile->local.nReaders --;
32629       if (pFile->local.nReaders == 0)
32630       {
32631         pFile->shared->nReaders --;
32632       }
32633       bReturn = TRUE;
32634     }
32635   }
32636
32637   /* Releasing a pending lock */
32638   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
32639            && nNumberOfBytesToUnlockLow == 1){
32640     if (pFile->local.bPending){
32641       pFile->local.bPending = FALSE;
32642       pFile->shared->bPending = FALSE;
32643       bReturn = TRUE;
32644     }
32645   }
32646   /* Releasing a reserved lock */
32647   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
32648            && nNumberOfBytesToUnlockLow == 1){
32649     if (pFile->local.bReserved) {
32650       pFile->local.bReserved = FALSE;
32651       pFile->shared->bReserved = FALSE;
32652       bReturn = TRUE;
32653     }
32654   }
32655
32656   winceMutexRelease(pFile->hMutex);
32657   return bReturn;
32658 }
32659 /*
32660 ** End of the special code for wince
32661 *****************************************************************************/
32662 #endif /* SQLITE_OS_WINCE */
32663
32664 /*
32665 ** Lock a file region.
32666 */
32667 static BOOL winLockFile(
32668   LPHANDLE phFile,
32669   DWORD flags,
32670   DWORD offsetLow,
32671   DWORD offsetHigh,
32672   DWORD numBytesLow,
32673   DWORD numBytesHigh
32674 ){
32675 #if SQLITE_OS_WINCE
32676   /*
32677   ** NOTE: Windows CE is handled differently here due its lack of the Win32
32678   **       API LockFile.
32679   */
32680   return winceLockFile(phFile, offsetLow, offsetHigh,
32681                        numBytesLow, numBytesHigh);
32682 #else
32683   if( isNT() ){
32684     OVERLAPPED ovlp;
32685     memset(&ovlp, 0, sizeof(OVERLAPPED));
32686     ovlp.Offset = offsetLow;
32687     ovlp.OffsetHigh = offsetHigh;
32688     return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
32689   }else{
32690     return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
32691                       numBytesHigh);
32692   }
32693 #endif
32694 }
32695
32696 /*
32697 ** Unlock a file region.
32698  */
32699 static BOOL winUnlockFile(
32700   LPHANDLE phFile,
32701   DWORD offsetLow,
32702   DWORD offsetHigh,
32703   DWORD numBytesLow,
32704   DWORD numBytesHigh
32705 ){
32706 #if SQLITE_OS_WINCE
32707   /*
32708   ** NOTE: Windows CE is handled differently here due its lack of the Win32
32709   **       API UnlockFile.
32710   */
32711   return winceUnlockFile(phFile, offsetLow, offsetHigh,
32712                          numBytesLow, numBytesHigh);
32713 #else
32714   if( isNT() ){
32715     OVERLAPPED ovlp;
32716     memset(&ovlp, 0, sizeof(OVERLAPPED));
32717     ovlp.Offset = offsetLow;
32718     ovlp.OffsetHigh = offsetHigh;
32719     return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
32720   }else{
32721     return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
32722                         numBytesHigh);
32723   }
32724 #endif
32725 }
32726
32727 /*****************************************************************************
32728 ** The next group of routines implement the I/O methods specified
32729 ** by the sqlite3_io_methods object.
32730 ******************************************************************************/
32731
32732 /*
32733 ** Some Microsoft compilers lack this definition.
32734 */
32735 #ifndef INVALID_SET_FILE_POINTER
32736 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
32737 #endif
32738
32739 /*
32740 ** Move the current position of the file handle passed as the first 
32741 ** argument to offset iOffset within the file. If successful, return 0. 
32742 ** Otherwise, set pFile->lastErrno and return non-zero.
32743 */
32744 static int seekWinFile(winFile *pFile, sqlite3_int64 iOffset){
32745 #if !SQLITE_OS_WINRT
32746   LONG upperBits;                 /* Most sig. 32 bits of new offset */
32747   LONG lowerBits;                 /* Least sig. 32 bits of new offset */
32748   DWORD dwRet;                    /* Value returned by SetFilePointer() */
32749   DWORD lastErrno;                /* Value returned by GetLastError() */
32750
32751   OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
32752
32753   upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
32754   lowerBits = (LONG)(iOffset & 0xffffffff);
32755
32756   /* API oddity: If successful, SetFilePointer() returns a dword 
32757   ** containing the lower 32-bits of the new file-offset. Or, if it fails,
32758   ** it returns INVALID_SET_FILE_POINTER. However according to MSDN, 
32759   ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine 
32760   ** whether an error has actually occurred, it is also necessary to call 
32761   ** GetLastError().
32762   */
32763   dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
32764
32765   if( (dwRet==INVALID_SET_FILE_POINTER
32766       && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
32767     pFile->lastErrno = lastErrno;
32768     winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
32769              "seekWinFile", pFile->zPath);
32770     OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
32771     return 1;
32772   }
32773
32774   OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
32775   return 0;
32776 #else
32777   /*
32778   ** Same as above, except that this implementation works for WinRT.
32779   */
32780
32781   LARGE_INTEGER x;                /* The new offset */
32782   BOOL bRet;                      /* Value returned by SetFilePointerEx() */
32783
32784   x.QuadPart = iOffset;
32785   bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
32786
32787   if(!bRet){
32788     pFile->lastErrno = osGetLastError();
32789     winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
32790              "seekWinFile", pFile->zPath);
32791     OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
32792     return 1;
32793   }
32794
32795   OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
32796   return 0;
32797 #endif
32798 }
32799
32800 #if SQLITE_MAX_MMAP_SIZE>0
32801 /* Forward references to VFS methods */
32802 static int winUnmapfile(winFile*);
32803 #endif
32804
32805 /*
32806 ** Close a file.
32807 **
32808 ** It is reported that an attempt to close a handle might sometimes
32809 ** fail.  This is a very unreasonable result, but Windows is notorious
32810 ** for being unreasonable so I do not doubt that it might happen.  If
32811 ** the close fails, we pause for 100 milliseconds and try again.  As
32812 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
32813 ** giving up and returning an error.
32814 */
32815 #define MX_CLOSE_ATTEMPT 3
32816 static int winClose(sqlite3_file *id){
32817   int rc, cnt = 0;
32818   winFile *pFile = (winFile*)id;
32819
32820   assert( id!=0 );
32821 #ifndef SQLITE_OMIT_WAL
32822   assert( pFile->pShm==0 );
32823 #endif
32824   assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
32825   OSTRACE(("CLOSE file=%p\n", pFile->h));
32826
32827 #if SQLITE_MAX_MMAP_SIZE>0
32828   rc = winUnmapfile(pFile);
32829   if( rc!=SQLITE_OK ) return rc;
32830 #endif
32831
32832   do{
32833     rc = osCloseHandle(pFile->h);
32834     /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
32835   }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
32836 #if SQLITE_OS_WINCE
32837 #define WINCE_DELETION_ATTEMPTS 3
32838   winceDestroyLock(pFile);
32839   if( pFile->zDeleteOnClose ){
32840     int cnt = 0;
32841     while(
32842            osDeleteFileW(pFile->zDeleteOnClose)==0
32843         && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff 
32844         && cnt++ < WINCE_DELETION_ATTEMPTS
32845     ){
32846        sqlite3_win32_sleep(100);  /* Wait a little before trying again */
32847     }
32848     sqlite3_free(pFile->zDeleteOnClose);
32849   }
32850 #endif
32851   if( rc ){
32852     pFile->h = NULL;
32853   }
32854   OpenCounter(-1);
32855   OSTRACE(("CLOSE file=%p, rc=%s\n", pFile->h, rc ? "ok" : "failed"));
32856   return rc ? SQLITE_OK
32857             : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
32858                           "winClose", pFile->zPath);
32859 }
32860
32861 /*
32862 ** Read data from a file into a buffer.  Return SQLITE_OK if all
32863 ** bytes were read successfully and SQLITE_IOERR if anything goes
32864 ** wrong.
32865 */
32866 static int winRead(
32867   sqlite3_file *id,          /* File to read from */
32868   void *pBuf,                /* Write content into this buffer */
32869   int amt,                   /* Number of bytes to read */
32870   sqlite3_int64 offset       /* Begin reading at this offset */
32871 ){
32872 #if !SQLITE_OS_WINCE
32873   OVERLAPPED overlapped;          /* The offset for ReadFile. */
32874 #endif
32875   winFile *pFile = (winFile*)id;  /* file handle */
32876   DWORD nRead;                    /* Number of bytes actually read from file */
32877   int nRetry = 0;                 /* Number of retrys */
32878
32879   assert( id!=0 );
32880   assert( amt>0 );
32881   assert( offset>=0 );
32882   SimulateIOError(return SQLITE_IOERR_READ);
32883   OSTRACE(("READ file=%p, buffer=%p, amount=%d, offset=%lld, lock=%d\n",
32884            pFile->h, pBuf, amt, offset, pFile->locktype));
32885
32886 #if SQLITE_MAX_MMAP_SIZE>0
32887   /* Deal with as much of this read request as possible by transfering
32888   ** data from the memory mapping using memcpy().  */
32889   if( offset<pFile->mmapSize ){
32890     if( offset+amt <= pFile->mmapSize ){
32891       memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
32892       OSTRACE(("READ-MMAP file=%p, rc=SQLITE_OK\n", pFile->h));
32893       return SQLITE_OK;
32894     }else{
32895       int nCopy = (int)(pFile->mmapSize - offset);
32896       memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
32897       pBuf = &((u8 *)pBuf)[nCopy];
32898       amt -= nCopy;
32899       offset += nCopy;
32900     }
32901   }
32902 #endif
32903
32904 #if SQLITE_OS_WINCE
32905   if( seekWinFile(pFile, offset) ){
32906     OSTRACE(("READ file=%p, rc=SQLITE_FULL\n", pFile->h));
32907     return SQLITE_FULL;
32908   }
32909   while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
32910 #else
32911   memset(&overlapped, 0, sizeof(OVERLAPPED));
32912   overlapped.Offset = (LONG)(offset & 0xffffffff);
32913   overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
32914   while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
32915          osGetLastError()!=ERROR_HANDLE_EOF ){
32916 #endif
32917     DWORD lastErrno;
32918     if( retryIoerr(&nRetry, &lastErrno) ) continue;
32919     pFile->lastErrno = lastErrno;
32920     OSTRACE(("READ file=%p, rc=SQLITE_IOERR_READ\n", pFile->h));
32921     return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
32922              "winRead", pFile->zPath);
32923   }
32924   logIoerr(nRetry);
32925   if( nRead<(DWORD)amt ){
32926     /* Unread parts of the buffer must be zero-filled */
32927     memset(&((char*)pBuf)[nRead], 0, amt-nRead);
32928     OSTRACE(("READ file=%p, rc=SQLITE_IOERR_SHORT_READ\n", pFile->h));
32929     return SQLITE_IOERR_SHORT_READ;
32930   }
32931
32932   OSTRACE(("READ file=%p, rc=SQLITE_OK\n", pFile->h));
32933   return SQLITE_OK;
32934 }
32935
32936 /*
32937 ** Write data from a buffer into a file.  Return SQLITE_OK on success
32938 ** or some other error code on failure.
32939 */
32940 static int winWrite(
32941   sqlite3_file *id,               /* File to write into */
32942   const void *pBuf,               /* The bytes to be written */
32943   int amt,                        /* Number of bytes to write */
32944   sqlite3_int64 offset            /* Offset into the file to begin writing at */
32945 ){
32946   int rc = 0;                     /* True if error has occurred, else false */
32947   winFile *pFile = (winFile*)id;  /* File handle */
32948   int nRetry = 0;                 /* Number of retries */
32949
32950   assert( amt>0 );
32951   assert( pFile );
32952   SimulateIOError(return SQLITE_IOERR_WRITE);
32953   SimulateDiskfullError(return SQLITE_FULL);
32954
32955   OSTRACE(("WRITE file=%p, buffer=%p, amount=%d, offset=%lld, lock=%d\n",
32956            pFile->h, pBuf, amt, offset, pFile->locktype));
32957
32958 #if SQLITE_MAX_MMAP_SIZE>0
32959   /* Deal with as much of this write request as possible by transfering
32960   ** data from the memory mapping using memcpy().  */
32961   if( offset<pFile->mmapSize ){
32962     if( offset+amt <= pFile->mmapSize ){
32963       memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
32964       OSTRACE(("WRITE-MMAP file=%p, rc=SQLITE_OK\n", pFile->h));
32965       return SQLITE_OK;
32966     }else{
32967       int nCopy = (int)(pFile->mmapSize - offset);
32968       memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
32969       pBuf = &((u8 *)pBuf)[nCopy];
32970       amt -= nCopy;
32971       offset += nCopy;
32972     }
32973   }
32974 #endif
32975
32976 #if SQLITE_OS_WINCE
32977   rc = seekWinFile(pFile, offset);
32978   if( rc==0 ){
32979 #else
32980   {
32981 #endif
32982 #if !SQLITE_OS_WINCE
32983     OVERLAPPED overlapped;        /* The offset for WriteFile. */
32984 #endif
32985     u8 *aRem = (u8 *)pBuf;        /* Data yet to be written */
32986     int nRem = amt;               /* Number of bytes yet to be written */
32987     DWORD nWrite;                 /* Bytes written by each WriteFile() call */
32988     DWORD lastErrno = NO_ERROR;   /* Value returned by GetLastError() */
32989
32990 #if !SQLITE_OS_WINCE
32991     memset(&overlapped, 0, sizeof(OVERLAPPED));
32992     overlapped.Offset = (LONG)(offset & 0xffffffff);
32993     overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
32994 #endif
32995
32996     while( nRem>0 ){
32997 #if SQLITE_OS_WINCE
32998       if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
32999 #else
33000       if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
33001 #endif
33002         if( retryIoerr(&nRetry, &lastErrno) ) continue;
33003         break;
33004       }
33005       assert( nWrite==0 || nWrite<=(DWORD)nRem );
33006       if( nWrite==0 || nWrite>(DWORD)nRem ){
33007         lastErrno = osGetLastError();
33008         break;
33009       }
33010 #if !SQLITE_OS_WINCE
33011       offset += nWrite;
33012       overlapped.Offset = (LONG)(offset & 0xffffffff);
33013       overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
33014 #endif
33015       aRem += nWrite;
33016       nRem -= nWrite;
33017     }
33018     if( nRem>0 ){
33019       pFile->lastErrno = lastErrno;
33020       rc = 1;
33021     }
33022   }
33023
33024   if( rc ){
33025     if(   ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
33026        || ( pFile->lastErrno==ERROR_DISK_FULL )){
33027       OSTRACE(("WRITE file=%p, rc=SQLITE_FULL\n", pFile->h));
33028       return SQLITE_FULL;
33029     }
33030     OSTRACE(("WRITE file=%p, rc=SQLITE_IOERR_WRITE\n", pFile->h));
33031     return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
33032              "winWrite", pFile->zPath);
33033   }else{
33034     logIoerr(nRetry);
33035   }
33036   OSTRACE(("WRITE file=%p, rc=SQLITE_OK\n", pFile->h));
33037   return SQLITE_OK;
33038 }
33039
33040 /*
33041 ** Truncate an open file to a specified size
33042 */
33043 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
33044   winFile *pFile = (winFile*)id;  /* File handle object */
33045   int rc = SQLITE_OK;             /* Return code for this function */
33046   DWORD lastErrno;
33047
33048   assert( pFile );
33049   SimulateIOError(return SQLITE_IOERR_TRUNCATE);
33050   OSTRACE(("TRUNCATE file=%p, size=%lld, lock=%d\n",
33051            pFile->h, nByte, pFile->locktype));
33052
33053   /* If the user has configured a chunk-size for this file, truncate the
33054   ** file so that it consists of an integer number of chunks (i.e. the
33055   ** actual file size after the operation may be larger than the requested
33056   ** size).
33057   */
33058   if( pFile->szChunk>0 ){
33059     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
33060   }
33061
33062   /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
33063   if( seekWinFile(pFile, nByte) ){
33064     rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
33065                      "winTruncate1", pFile->zPath);
33066   }else if( 0==osSetEndOfFile(pFile->h) &&
33067             ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
33068     pFile->lastErrno = lastErrno;
33069     rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
33070                      "winTruncate2", pFile->zPath);
33071   }
33072
33073 #if SQLITE_MAX_MMAP_SIZE>0
33074   /* If the file was truncated to a size smaller than the currently
33075   ** mapped region, reduce the effective mapping size as well. SQLite will
33076   ** use read() and write() to access data beyond this point from now on.
33077   */
33078   if( pFile->pMapRegion && nByte<pFile->mmapSize ){
33079     pFile->mmapSize = nByte;
33080   }
33081 #endif
33082
33083   OSTRACE(("TRUNCATE file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
33084   return rc;
33085 }
33086
33087 #ifdef SQLITE_TEST
33088 /*
33089 ** Count the number of fullsyncs and normal syncs.  This is used to test
33090 ** that syncs and fullsyncs are occuring at the right times.
33091 */
33092 SQLITE_API int sqlite3_sync_count = 0;
33093 SQLITE_API int sqlite3_fullsync_count = 0;
33094 #endif
33095
33096 /*
33097 ** Make sure all writes to a particular file are committed to disk.
33098 */
33099 static int winSync(sqlite3_file *id, int flags){
33100 #ifndef SQLITE_NO_SYNC
33101   /*
33102   ** Used only when SQLITE_NO_SYNC is not defined.
33103    */
33104   BOOL rc;
33105 #endif
33106 #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
33107     (defined(SQLITE_TEST) && defined(SQLITE_DEBUG))
33108   /*
33109   ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
33110   ** OSTRACE() macros.
33111    */
33112   winFile *pFile = (winFile*)id;
33113 #else
33114   UNUSED_PARAMETER(id);
33115 #endif
33116
33117   assert( pFile );
33118   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
33119   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
33120       || (flags&0x0F)==SQLITE_SYNC_FULL
33121   );
33122
33123   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
33124   ** line is to test that doing so does not cause any problems.
33125   */
33126   SimulateDiskfullError( return SQLITE_FULL );
33127
33128   OSTRACE(("SYNC file=%p, flags=%x, lock=%d\n",
33129            pFile->h, flags, pFile->locktype));
33130
33131 #ifndef SQLITE_TEST
33132   UNUSED_PARAMETER(flags);
33133 #else
33134   if( (flags&0x0F)==SQLITE_SYNC_FULL ){
33135     sqlite3_fullsync_count++;
33136   }
33137   sqlite3_sync_count++;
33138 #endif
33139
33140   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
33141   ** no-op
33142   */
33143 #ifdef SQLITE_NO_SYNC
33144   return SQLITE_OK;
33145 #else
33146   rc = osFlushFileBuffers(pFile->h);
33147   SimulateIOError( rc=FALSE );
33148   if( rc ){
33149     OSTRACE(("SYNC file=%p, rc=SQLITE_OK\n", pFile->h));
33150     return SQLITE_OK;
33151   }else{
33152     pFile->lastErrno = osGetLastError();
33153     OSTRACE(("SYNC file=%p, rc=SQLITE_IOERR_FSYNC\n", pFile->h));
33154     return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
33155              "winSync", pFile->zPath);
33156   }
33157 #endif
33158 }
33159
33160 /*
33161 ** Determine the current size of a file in bytes
33162 */
33163 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
33164   winFile *pFile = (winFile*)id;
33165   int rc = SQLITE_OK;
33166
33167   assert( id!=0 );
33168   assert( pSize!=0 );
33169   SimulateIOError(return SQLITE_IOERR_FSTAT);
33170   OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
33171
33172 #if SQLITE_OS_WINRT
33173   {
33174     FILE_STANDARD_INFO info;
33175     if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
33176                                      &info, sizeof(info)) ){
33177       *pSize = info.EndOfFile.QuadPart;
33178     }else{
33179       pFile->lastErrno = osGetLastError();
33180       rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
33181                        "winFileSize", pFile->zPath);
33182     }
33183   }
33184 #else
33185   {
33186     DWORD upperBits;
33187     DWORD lowerBits;
33188     DWORD lastErrno;
33189
33190     lowerBits = osGetFileSize(pFile->h, &upperBits);
33191     *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
33192     if(   (lowerBits == INVALID_FILE_SIZE)
33193        && ((lastErrno = osGetLastError())!=NO_ERROR) ){
33194       pFile->lastErrno = lastErrno;
33195       rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
33196              "winFileSize", pFile->zPath);
33197     }
33198   }
33199 #endif
33200   OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
33201            pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
33202   return rc;
33203 }
33204
33205 /*
33206 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
33207 */
33208 #ifndef LOCKFILE_FAIL_IMMEDIATELY
33209 # define LOCKFILE_FAIL_IMMEDIATELY 1
33210 #endif
33211
33212 #ifndef LOCKFILE_EXCLUSIVE_LOCK
33213 # define LOCKFILE_EXCLUSIVE_LOCK 2
33214 #endif
33215
33216 /*
33217 ** Historically, SQLite has used both the LockFile and LockFileEx functions.
33218 ** When the LockFile function was used, it was always expected to fail
33219 ** immediately if the lock could not be obtained.  Also, it always expected to
33220 ** obtain an exclusive lock.  These flags are used with the LockFileEx function
33221 ** and reflect those expectations; therefore, they should not be changed.
33222 */
33223 #ifndef SQLITE_LOCKFILE_FLAGS
33224 # define SQLITE_LOCKFILE_FLAGS   (LOCKFILE_FAIL_IMMEDIATELY | \
33225                                   LOCKFILE_EXCLUSIVE_LOCK)
33226 #endif
33227
33228 /*
33229 ** Currently, SQLite never calls the LockFileEx function without wanting the
33230 ** call to fail immediately if the lock cannot be obtained.
33231 */
33232 #ifndef SQLITE_LOCKFILEEX_FLAGS
33233 # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
33234 #endif
33235
33236 /*
33237 ** Acquire a reader lock.
33238 ** Different API routines are called depending on whether or not this
33239 ** is Win9x or WinNT.
33240 */
33241 static int getReadLock(winFile *pFile){
33242   int res;
33243   OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
33244   if( isNT() ){
33245 #if SQLITE_OS_WINCE
33246     /*
33247     ** NOTE: Windows CE is handled differently here due its lack of the Win32
33248     **       API LockFileEx.
33249     */
33250     res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
33251 #else
33252     res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
33253                       SHARED_SIZE, 0);
33254 #endif
33255   }
33256 #ifdef SQLITE_WIN32_HAS_ANSI
33257   else{
33258     int lk;
33259     sqlite3_randomness(sizeof(lk), &lk);
33260     pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
33261     res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
33262                       SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
33263   }
33264 #endif
33265   if( res == 0 ){
33266     pFile->lastErrno = osGetLastError();
33267     /* No need to log a failure to lock */
33268   }
33269   OSTRACE(("READ-LOCK file=%p, rc=%s\n", pFile->h, sqlite3ErrName(res)));
33270   return res;
33271 }
33272
33273 /*
33274 ** Undo a readlock
33275 */
33276 static int unlockReadLock(winFile *pFile){
33277   int res;
33278   DWORD lastErrno;
33279   OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
33280   if( isNT() ){
33281     res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
33282   }
33283 #ifdef SQLITE_WIN32_HAS_ANSI
33284   else{
33285     res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
33286   }
33287 #endif
33288   if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
33289     pFile->lastErrno = lastErrno;
33290     winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
33291              "unlockReadLock", pFile->zPath);
33292   }
33293   OSTRACE(("READ-UNLOCK file=%p, rc=%s\n", pFile->h, sqlite3ErrName(res)));
33294   return res;
33295 }
33296
33297 /*
33298 ** Lock the file with the lock specified by parameter locktype - one
33299 ** of the following:
33300 **
33301 **     (1) SHARED_LOCK
33302 **     (2) RESERVED_LOCK
33303 **     (3) PENDING_LOCK
33304 **     (4) EXCLUSIVE_LOCK
33305 **
33306 ** Sometimes when requesting one lock state, additional lock states
33307 ** are inserted in between.  The locking might fail on one of the later
33308 ** transitions leaving the lock state different from what it started but
33309 ** still short of its goal.  The following chart shows the allowed
33310 ** transitions and the inserted intermediate states:
33311 **
33312 **    UNLOCKED -> SHARED
33313 **    SHARED -> RESERVED
33314 **    SHARED -> (PENDING) -> EXCLUSIVE
33315 **    RESERVED -> (PENDING) -> EXCLUSIVE
33316 **    PENDING -> EXCLUSIVE
33317 **
33318 ** This routine will only increase a lock.  The winUnlock() routine
33319 ** erases all locks at once and returns us immediately to locking level 0.
33320 ** It is not possible to lower the locking level one step at a time.  You
33321 ** must go straight to locking level 0.
33322 */
33323 static int winLock(sqlite3_file *id, int locktype){
33324   int rc = SQLITE_OK;    /* Return code from subroutines */
33325   int res = 1;           /* Result of a Windows lock call */
33326   int newLocktype;       /* Set pFile->locktype to this value before exiting */
33327   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
33328   winFile *pFile = (winFile*)id;
33329   DWORD lastErrno = NO_ERROR;
33330
33331   assert( id!=0 );
33332   OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
33333            pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
33334
33335   /* If there is already a lock of this type or more restrictive on the
33336   ** OsFile, do nothing. Don't use the end_lock: exit path, as
33337   ** sqlite3OsEnterMutex() hasn't been called yet.
33338   */
33339   if( pFile->locktype>=locktype ){
33340     OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
33341     return SQLITE_OK;
33342   }
33343
33344   /* Make sure the locking sequence is correct
33345   */
33346   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
33347   assert( locktype!=PENDING_LOCK );
33348   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
33349
33350   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
33351   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
33352   ** the PENDING_LOCK byte is temporary.
33353   */
33354   newLocktype = pFile->locktype;
33355   if(   (pFile->locktype==NO_LOCK)
33356      || (   (locktype==EXCLUSIVE_LOCK)
33357          && (pFile->locktype==RESERVED_LOCK))
33358   ){
33359     int cnt = 3;
33360     while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
33361                                          PENDING_BYTE, 0, 1, 0))==0 ){
33362       /* Try 3 times to get the pending lock.  This is needed to work
33363       ** around problems caused by indexing and/or anti-virus software on
33364       ** Windows systems.
33365       ** If you are using this code as a model for alternative VFSes, do not
33366       ** copy this retry logic.  It is a hack intended for Windows only.
33367       */
33368       OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, rc=%s\n",
33369                pFile->h, cnt, sqlite3ErrName(res)));
33370       if( cnt ) sqlite3_win32_sleep(1);
33371     }
33372     gotPendingLock = res;
33373     if( !res ){
33374       lastErrno = osGetLastError();
33375     }
33376   }
33377
33378   /* Acquire a shared lock
33379   */
33380   if( locktype==SHARED_LOCK && res ){
33381     assert( pFile->locktype==NO_LOCK );
33382     res = getReadLock(pFile);
33383     if( res ){
33384       newLocktype = SHARED_LOCK;
33385     }else{
33386       lastErrno = osGetLastError();
33387     }
33388   }
33389
33390   /* Acquire a RESERVED lock
33391   */
33392   if( locktype==RESERVED_LOCK && res ){
33393     assert( pFile->locktype==SHARED_LOCK );
33394     res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
33395     if( res ){
33396       newLocktype = RESERVED_LOCK;
33397     }else{
33398       lastErrno = osGetLastError();
33399     }
33400   }
33401
33402   /* Acquire a PENDING lock
33403   */
33404   if( locktype==EXCLUSIVE_LOCK && res ){
33405     newLocktype = PENDING_LOCK;
33406     gotPendingLock = 0;
33407   }
33408
33409   /* Acquire an EXCLUSIVE lock
33410   */
33411   if( locktype==EXCLUSIVE_LOCK && res ){
33412     assert( pFile->locktype>=SHARED_LOCK );
33413     res = unlockReadLock(pFile);
33414     res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
33415                       SHARED_SIZE, 0);
33416     if( res ){
33417       newLocktype = EXCLUSIVE_LOCK;
33418     }else{
33419       lastErrno = osGetLastError();
33420       getReadLock(pFile);
33421     }
33422   }
33423
33424   /* If we are holding a PENDING lock that ought to be released, then
33425   ** release it now.
33426   */
33427   if( gotPendingLock && locktype==SHARED_LOCK ){
33428     winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
33429   }
33430
33431   /* Update the state of the lock has held in the file descriptor then
33432   ** return the appropriate result code.
33433   */
33434   if( res ){
33435     rc = SQLITE_OK;
33436   }else{
33437     OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
33438              pFile->h, locktype, newLocktype));
33439     pFile->lastErrno = lastErrno;
33440     rc = SQLITE_BUSY;
33441   }
33442   pFile->locktype = (u8)newLocktype;
33443   OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
33444            pFile->h, pFile->locktype, sqlite3ErrName(rc)));
33445   return rc;
33446 }
33447
33448 /*
33449 ** This routine checks if there is a RESERVED lock held on the specified
33450 ** file by this or any other process. If such a lock is held, return
33451 ** non-zero, otherwise zero.
33452 */
33453 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
33454   int rc;
33455   winFile *pFile = (winFile*)id;
33456
33457   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
33458   OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
33459
33460   assert( id!=0 );
33461   if( pFile->locktype>=RESERVED_LOCK ){
33462     rc = 1;
33463     OSTRACE(("TEST-WR-LOCK file=%p, rc=%d (local)\n", pFile->h, rc));
33464   }else{
33465     rc = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE, 0, 1, 0);
33466     if( rc ){
33467       winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
33468     }
33469     rc = !rc;
33470     OSTRACE(("TEST-WR-LOCK file=%p, rc=%d (remote)\n", pFile->h, rc));
33471   }
33472   *pResOut = rc;
33473   OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
33474            pFile->h, pResOut, *pResOut));
33475   return SQLITE_OK;
33476 }
33477
33478 /*
33479 ** Lower the locking level on file descriptor id to locktype.  locktype
33480 ** must be either NO_LOCK or SHARED_LOCK.
33481 **
33482 ** If the locking level of the file descriptor is already at or below
33483 ** the requested locking level, this routine is a no-op.
33484 **
33485 ** It is not possible for this routine to fail if the second argument
33486 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
33487 ** might return SQLITE_IOERR;
33488 */
33489 static int winUnlock(sqlite3_file *id, int locktype){
33490   int type;
33491   winFile *pFile = (winFile*)id;
33492   int rc = SQLITE_OK;
33493   assert( pFile!=0 );
33494   assert( locktype<=SHARED_LOCK );
33495   OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
33496            pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
33497   type = pFile->locktype;
33498   if( type>=EXCLUSIVE_LOCK ){
33499     winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
33500     if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
33501       /* This should never happen.  We should always be able to
33502       ** reacquire the read lock */
33503       rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
33504                "winUnlock", pFile->zPath);
33505     }
33506   }
33507   if( type>=RESERVED_LOCK ){
33508     winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
33509   }
33510   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
33511     unlockReadLock(pFile);
33512   }
33513   if( type>=PENDING_LOCK ){
33514     winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
33515   }
33516   pFile->locktype = (u8)locktype;
33517   OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
33518            pFile->h, pFile->locktype, sqlite3ErrName(rc)));
33519   return rc;
33520 }
33521
33522 /*
33523 ** If *pArg is inititially negative then this is a query.  Set *pArg to
33524 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
33525 **
33526 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
33527 */
33528 static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
33529   if( *pArg<0 ){
33530     *pArg = (pFile->ctrlFlags & mask)!=0;
33531   }else if( (*pArg)==0 ){
33532     pFile->ctrlFlags &= ~mask;
33533   }else{
33534     pFile->ctrlFlags |= mask;
33535   }
33536 }
33537
33538 /* Forward declaration */
33539 static int getTempname(int nBuf, char *zBuf);
33540
33541 /*
33542 ** Control and query of the open file handle.
33543 */
33544 static int winFileControl(sqlite3_file *id, int op, void *pArg){
33545   winFile *pFile = (winFile*)id;
33546   OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
33547   switch( op ){
33548     case SQLITE_FCNTL_LOCKSTATE: {
33549       *(int*)pArg = pFile->locktype;
33550       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
33551       return SQLITE_OK;
33552     }
33553     case SQLITE_LAST_ERRNO: {
33554       *(int*)pArg = (int)pFile->lastErrno;
33555       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
33556       return SQLITE_OK;
33557     }
33558     case SQLITE_FCNTL_CHUNK_SIZE: {
33559       pFile->szChunk = *(int *)pArg;
33560       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
33561       return SQLITE_OK;
33562     }
33563     case SQLITE_FCNTL_SIZE_HINT: {
33564       if( pFile->szChunk>0 ){
33565         sqlite3_int64 oldSz;
33566         int rc = winFileSize(id, &oldSz);
33567         if( rc==SQLITE_OK ){
33568           sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
33569           if( newSz>oldSz ){
33570             SimulateIOErrorBenign(1);
33571             rc = winTruncate(id, newSz);
33572             SimulateIOErrorBenign(0);
33573           }
33574         }
33575         OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
33576         return rc;
33577       }
33578       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
33579       return SQLITE_OK;
33580     }
33581     case SQLITE_FCNTL_PERSIST_WAL: {
33582       winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
33583       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
33584       return SQLITE_OK;
33585     }
33586     case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
33587       winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
33588       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
33589       return SQLITE_OK;
33590     }
33591     case SQLITE_FCNTL_VFSNAME: {
33592       *(char**)pArg = sqlite3_mprintf("win32");
33593       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
33594       return SQLITE_OK;
33595     }
33596     case SQLITE_FCNTL_WIN32_AV_RETRY: {
33597       int *a = (int*)pArg;
33598       if( a[0]>0 ){
33599         win32IoerrRetry = a[0];
33600       }else{
33601         a[0] = win32IoerrRetry;
33602       }
33603       if( a[1]>0 ){
33604         win32IoerrRetryDelay = a[1];
33605       }else{
33606         a[1] = win32IoerrRetryDelay;
33607       }
33608       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
33609       return SQLITE_OK;
33610     }
33611     case SQLITE_FCNTL_TEMPFILENAME: {
33612       char *zTFile = sqlite3MallocZero( pFile->pVfs->mxPathname );
33613       if( zTFile ){
33614         getTempname(pFile->pVfs->mxPathname, zTFile);
33615         *(char**)pArg = zTFile;
33616       }
33617       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
33618       return SQLITE_OK;
33619     }
33620 #if SQLITE_MAX_MMAP_SIZE>0
33621     case SQLITE_FCNTL_MMAP_SIZE: {
33622       i64 newLimit = *(i64*)pArg;
33623       if( newLimit>sqlite3GlobalConfig.mxMmap ){
33624         newLimit = sqlite3GlobalConfig.mxMmap;
33625       }
33626       *(i64*)pArg = pFile->mmapSizeMax;
33627       if( newLimit>=0 ) pFile->mmapSizeMax = newLimit;
33628       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
33629       return SQLITE_OK;
33630     }
33631 #endif
33632   }
33633   OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
33634   return SQLITE_NOTFOUND;
33635 }
33636
33637 /*
33638 ** Return the sector size in bytes of the underlying block device for
33639 ** the specified file. This is almost always 512 bytes, but may be
33640 ** larger for some devices.
33641 **
33642 ** SQLite code assumes this function cannot fail. It also assumes that
33643 ** if two files are created in the same file-system directory (i.e.
33644 ** a database and its journal file) that the sector size will be the
33645 ** same for both.
33646 */
33647 static int winSectorSize(sqlite3_file *id){
33648   (void)id;
33649   return SQLITE_DEFAULT_SECTOR_SIZE;
33650 }
33651
33652 /*
33653 ** Return a vector of device characteristics.
33654 */
33655 static int winDeviceCharacteristics(sqlite3_file *id){
33656   winFile *p = (winFile*)id;
33657   return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
33658          ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
33659 }
33660
33661 /* 
33662 ** Windows will only let you create file view mappings
33663 ** on allocation size granularity boundaries.
33664 ** During sqlite3_os_init() we do a GetSystemInfo()
33665 ** to get the granularity size.
33666 */
33667 SYSTEM_INFO winSysInfo;
33668
33669 #ifndef SQLITE_OMIT_WAL
33670
33671 /*
33672 ** Helper functions to obtain and relinquish the global mutex. The
33673 ** global mutex is used to protect the winLockInfo objects used by 
33674 ** this file, all of which may be shared by multiple threads.
33675 **
33676 ** Function winShmMutexHeld() is used to assert() that the global mutex 
33677 ** is held when required. This function is only used as part of assert() 
33678 ** statements. e.g.
33679 **
33680 **   winShmEnterMutex()
33681 **     assert( winShmMutexHeld() );
33682 **   winShmLeaveMutex()
33683 */
33684 static void winShmEnterMutex(void){
33685   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
33686 }
33687 static void winShmLeaveMutex(void){
33688   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
33689 }
33690 #ifdef SQLITE_DEBUG
33691 static int winShmMutexHeld(void) {
33692   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
33693 }
33694 #endif
33695
33696 /*
33697 ** Object used to represent a single file opened and mmapped to provide
33698 ** shared memory.  When multiple threads all reference the same
33699 ** log-summary, each thread has its own winFile object, but they all
33700 ** point to a single instance of this object.  In other words, each
33701 ** log-summary is opened only once per process.
33702 **
33703 ** winShmMutexHeld() must be true when creating or destroying
33704 ** this object or while reading or writing the following fields:
33705 **
33706 **      nRef
33707 **      pNext 
33708 **
33709 ** The following fields are read-only after the object is created:
33710 ** 
33711 **      fid
33712 **      zFilename
33713 **
33714 ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
33715 ** winShmMutexHeld() is true when reading or writing any other field
33716 ** in this structure.
33717 **
33718 */
33719 struct winShmNode {
33720   sqlite3_mutex *mutex;      /* Mutex to access this object */
33721   char *zFilename;           /* Name of the file */
33722   winFile hFile;             /* File handle from winOpen */
33723
33724   int szRegion;              /* Size of shared-memory regions */
33725   int nRegion;               /* Size of array apRegion */
33726   struct ShmRegion {
33727     HANDLE hMap;             /* File handle from CreateFileMapping */
33728     void *pMap;
33729   } *aRegion;
33730   DWORD lastErrno;           /* The Windows errno from the last I/O error */
33731
33732   int nRef;                  /* Number of winShm objects pointing to this */
33733   winShm *pFirst;            /* All winShm objects pointing to this */
33734   winShmNode *pNext;         /* Next in list of all winShmNode objects */
33735 #ifdef SQLITE_DEBUG
33736   u8 nextShmId;              /* Next available winShm.id value */
33737 #endif
33738 };
33739
33740 /*
33741 ** A global array of all winShmNode objects.
33742 **
33743 ** The winShmMutexHeld() must be true while reading or writing this list.
33744 */
33745 static winShmNode *winShmNodeList = 0;
33746
33747 /*
33748 ** Structure used internally by this VFS to record the state of an
33749 ** open shared memory connection.
33750 **
33751 ** The following fields are initialized when this object is created and
33752 ** are read-only thereafter:
33753 **
33754 **    winShm.pShmNode
33755 **    winShm.id
33756 **
33757 ** All other fields are read/write.  The winShm.pShmNode->mutex must be held
33758 ** while accessing any read/write fields.
33759 */
33760 struct winShm {
33761   winShmNode *pShmNode;      /* The underlying winShmNode object */
33762   winShm *pNext;             /* Next winShm with the same winShmNode */
33763   u8 hasMutex;               /* True if holding the winShmNode mutex */
33764   u16 sharedMask;            /* Mask of shared locks held */
33765   u16 exclMask;              /* Mask of exclusive locks held */
33766 #ifdef SQLITE_DEBUG
33767   u8 id;                     /* Id of this connection with its winShmNode */
33768 #endif
33769 };
33770
33771 /*
33772 ** Constants used for locking
33773 */
33774 #define WIN_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
33775 #define WIN_SHM_DMS    (WIN_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
33776
33777 /*
33778 ** Apply advisory locks for all n bytes beginning at ofst.
33779 */
33780 #define _SHM_UNLCK  1
33781 #define _SHM_RDLCK  2
33782 #define _SHM_WRLCK  3
33783 static int winShmSystemLock(
33784   winShmNode *pFile,    /* Apply locks to this open shared-memory segment */
33785   int lockType,         /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
33786   int ofst,             /* Offset to first byte to be locked/unlocked */
33787   int nByte             /* Number of bytes to lock or unlock */
33788 ){
33789   int rc = 0;           /* Result code form Lock/UnlockFileEx() */
33790
33791   /* Access to the winShmNode object is serialized by the caller */
33792   assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
33793
33794   OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
33795            pFile->hFile.h, lockType, ofst, nByte));
33796
33797   /* Release/Acquire the system-level lock */
33798   if( lockType==_SHM_UNLCK ){
33799     rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
33800   }else{
33801     /* Initialize the locking parameters */
33802     DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
33803     if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
33804     rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
33805   }
33806   
33807   if( rc!= 0 ){
33808     rc = SQLITE_OK;
33809   }else{
33810     pFile->lastErrno =  osGetLastError();
33811     rc = SQLITE_BUSY;
33812   }
33813
33814   OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
33815            pFile->hFile.h, (lockType == _SHM_UNLCK) ? "winUnlockFile" :
33816            "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
33817
33818   return rc;
33819 }
33820
33821 /* Forward references to VFS methods */
33822 static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
33823 static int winDelete(sqlite3_vfs *,const char*,int);
33824
33825 /*
33826 ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
33827 **
33828 ** This is not a VFS shared-memory method; it is a utility function called
33829 ** by VFS shared-memory methods.
33830 */
33831 static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
33832   winShmNode **pp;
33833   winShmNode *p;
33834   BOOL bRc;
33835   assert( winShmMutexHeld() );
33836   OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
33837            osGetCurrentProcessId(), deleteFlag));
33838   pp = &winShmNodeList;
33839   while( (p = *pp)!=0 ){
33840     if( p->nRef==0 ){
33841       int i;
33842       if( p->mutex ) sqlite3_mutex_free(p->mutex);
33843       for(i=0; i<p->nRegion; i++){
33844         bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
33845         OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
33846                  osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
33847         bRc = osCloseHandle(p->aRegion[i].hMap);
33848         OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
33849                  osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
33850       }
33851       if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
33852         SimulateIOErrorBenign(1);
33853         winClose((sqlite3_file *)&p->hFile);
33854         SimulateIOErrorBenign(0);
33855       }
33856       if( deleteFlag ){
33857         SimulateIOErrorBenign(1);
33858         sqlite3BeginBenignMalloc();
33859         winDelete(pVfs, p->zFilename, 0);
33860         sqlite3EndBenignMalloc();
33861         SimulateIOErrorBenign(0);
33862       }
33863       *pp = p->pNext;
33864       sqlite3_free(p->aRegion);
33865       sqlite3_free(p);
33866     }else{
33867       pp = &p->pNext;
33868     }
33869   }
33870 }
33871
33872 /*
33873 ** Open the shared-memory area associated with database file pDbFd.
33874 **
33875 ** When opening a new shared-memory file, if no other instances of that
33876 ** file are currently open, in this process or in other processes, then
33877 ** the file must be truncated to zero length or have its header cleared.
33878 */
33879 static int winOpenSharedMemory(winFile *pDbFd){
33880   struct winShm *p;                  /* The connection to be opened */
33881   struct winShmNode *pShmNode = 0;   /* The underlying mmapped file */
33882   int rc;                            /* Result code */
33883   struct winShmNode *pNew;           /* Newly allocated winShmNode */
33884   int nName;                         /* Size of zName in bytes */
33885
33886   assert( pDbFd->pShm==0 );    /* Not previously opened */
33887
33888   /* Allocate space for the new sqlite3_shm object.  Also speculatively
33889   ** allocate space for a new winShmNode and filename.
33890   */
33891   p = sqlite3MallocZero( sizeof(*p) );
33892   if( p==0 ) return SQLITE_IOERR_NOMEM;
33893   nName = sqlite3Strlen30(pDbFd->zPath);
33894   pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
33895   if( pNew==0 ){
33896     sqlite3_free(p);
33897     return SQLITE_IOERR_NOMEM;
33898   }
33899   pNew->zFilename = (char*)&pNew[1];
33900   sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
33901   sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename); 
33902
33903   /* Look to see if there is an existing winShmNode that can be used.
33904   ** If no matching winShmNode currently exists, create a new one.
33905   */
33906   winShmEnterMutex();
33907   for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
33908     /* TBD need to come up with better match here.  Perhaps
33909     ** use FILE_ID_BOTH_DIR_INFO Structure.
33910     */
33911     if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
33912   }
33913   if( pShmNode ){
33914     sqlite3_free(pNew);
33915   }else{
33916     pShmNode = pNew;
33917     pNew = 0;
33918     ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
33919     pShmNode->pNext = winShmNodeList;
33920     winShmNodeList = pShmNode;
33921
33922     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
33923     if( pShmNode->mutex==0 ){
33924       rc = SQLITE_IOERR_NOMEM;
33925       goto shm_open_err;
33926     }
33927
33928     rc = winOpen(pDbFd->pVfs,
33929                  pShmNode->zFilename,             /* Name of the file (UTF-8) */
33930                  (sqlite3_file*)&pShmNode->hFile,  /* File handle here */
33931                  SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
33932                  0);
33933     if( SQLITE_OK!=rc ){
33934       goto shm_open_err;
33935     }
33936
33937     /* Check to see if another process is holding the dead-man switch.
33938     ** If not, truncate the file to zero length. 
33939     */
33940     if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
33941       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
33942       if( rc!=SQLITE_OK ){
33943         rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
33944                  "winOpenShm", pDbFd->zPath);
33945       }
33946     }
33947     if( rc==SQLITE_OK ){
33948       winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
33949       rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
33950     }
33951     if( rc ) goto shm_open_err;
33952   }
33953
33954   /* Make the new connection a child of the winShmNode */
33955   p->pShmNode = pShmNode;
33956 #ifdef SQLITE_DEBUG
33957   p->id = pShmNode->nextShmId++;
33958 #endif
33959   pShmNode->nRef++;
33960   pDbFd->pShm = p;
33961   winShmLeaveMutex();
33962
33963   /* The reference count on pShmNode has already been incremented under
33964   ** the cover of the winShmEnterMutex() mutex and the pointer from the
33965   ** new (struct winShm) object to the pShmNode has been set. All that is
33966   ** left to do is to link the new object into the linked list starting
33967   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex 
33968   ** mutex.
33969   */
33970   sqlite3_mutex_enter(pShmNode->mutex);
33971   p->pNext = pShmNode->pFirst;
33972   pShmNode->pFirst = p;
33973   sqlite3_mutex_leave(pShmNode->mutex);
33974   return SQLITE_OK;
33975
33976   /* Jump here on any error */
33977 shm_open_err:
33978   winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
33979   winShmPurge(pDbFd->pVfs, 0);      /* This call frees pShmNode if required */
33980   sqlite3_free(p);
33981   sqlite3_free(pNew);
33982   winShmLeaveMutex();
33983   return rc;
33984 }
33985
33986 /*
33987 ** Close a connection to shared-memory.  Delete the underlying 
33988 ** storage if deleteFlag is true.
33989 */
33990 static int winShmUnmap(
33991   sqlite3_file *fd,          /* Database holding shared memory */
33992   int deleteFlag             /* Delete after closing if true */
33993 ){
33994   winFile *pDbFd;       /* Database holding shared-memory */
33995   winShm *p;            /* The connection to be closed */
33996   winShmNode *pShmNode; /* The underlying shared-memory file */
33997   winShm **pp;          /* For looping over sibling connections */
33998
33999   pDbFd = (winFile*)fd;
34000   p = pDbFd->pShm;
34001   if( p==0 ) return SQLITE_OK;
34002   pShmNode = p->pShmNode;
34003
34004   /* Remove connection p from the set of connections associated
34005   ** with pShmNode */
34006   sqlite3_mutex_enter(pShmNode->mutex);
34007   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
34008   *pp = p->pNext;
34009
34010   /* Free the connection p */
34011   sqlite3_free(p);
34012   pDbFd->pShm = 0;
34013   sqlite3_mutex_leave(pShmNode->mutex);
34014
34015   /* If pShmNode->nRef has reached 0, then close the underlying
34016   ** shared-memory file, too */
34017   winShmEnterMutex();
34018   assert( pShmNode->nRef>0 );
34019   pShmNode->nRef--;
34020   if( pShmNode->nRef==0 ){
34021     winShmPurge(pDbFd->pVfs, deleteFlag);
34022   }
34023   winShmLeaveMutex();
34024
34025   return SQLITE_OK;
34026 }
34027
34028 /*
34029 ** Change the lock state for a shared-memory segment.
34030 */
34031 static int winShmLock(
34032   sqlite3_file *fd,          /* Database file holding the shared memory */
34033   int ofst,                  /* First lock to acquire or release */
34034   int n,                     /* Number of locks to acquire or release */
34035   int flags                  /* What to do with the lock */
34036 ){
34037   winFile *pDbFd = (winFile*)fd;        /* Connection holding shared memory */
34038   winShm *p = pDbFd->pShm;              /* The shared memory being locked */
34039   winShm *pX;                           /* For looping over all siblings */
34040   winShmNode *pShmNode = p->pShmNode;
34041   int rc = SQLITE_OK;                   /* Result code */
34042   u16 mask;                             /* Mask of locks to take or release */
34043
34044   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
34045   assert( n>=1 );
34046   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
34047        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
34048        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
34049        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
34050   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
34051
34052   mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
34053   assert( n>1 || mask==(1<<ofst) );
34054   sqlite3_mutex_enter(pShmNode->mutex);
34055   if( flags & SQLITE_SHM_UNLOCK ){
34056     u16 allMask = 0; /* Mask of locks held by siblings */
34057
34058     /* See if any siblings hold this same lock */
34059     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
34060       if( pX==p ) continue;
34061       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
34062       allMask |= pX->sharedMask;
34063     }
34064
34065     /* Unlock the system-level locks */
34066     if( (mask & allMask)==0 ){
34067       rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
34068     }else{
34069       rc = SQLITE_OK;
34070     }
34071
34072     /* Undo the local locks */
34073     if( rc==SQLITE_OK ){
34074       p->exclMask &= ~mask;
34075       p->sharedMask &= ~mask;
34076     } 
34077   }else if( flags & SQLITE_SHM_SHARED ){
34078     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
34079
34080     /* Find out which shared locks are already held by sibling connections.
34081     ** If any sibling already holds an exclusive lock, go ahead and return
34082     ** SQLITE_BUSY.
34083     */
34084     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
34085       if( (pX->exclMask & mask)!=0 ){
34086         rc = SQLITE_BUSY;
34087         break;
34088       }
34089       allShared |= pX->sharedMask;
34090     }
34091
34092     /* Get shared locks at the system level, if necessary */
34093     if( rc==SQLITE_OK ){
34094       if( (allShared & mask)==0 ){
34095         rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
34096       }else{
34097         rc = SQLITE_OK;
34098       }
34099     }
34100
34101     /* Get the local shared locks */
34102     if( rc==SQLITE_OK ){
34103       p->sharedMask |= mask;
34104     }
34105   }else{
34106     /* Make sure no sibling connections hold locks that will block this
34107     ** lock.  If any do, return SQLITE_BUSY right away.
34108     */
34109     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
34110       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
34111         rc = SQLITE_BUSY;
34112         break;
34113       }
34114     }
34115   
34116     /* Get the exclusive locks at the system level.  Then if successful
34117     ** also mark the local connection as being locked.
34118     */
34119     if( rc==SQLITE_OK ){
34120       rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
34121       if( rc==SQLITE_OK ){
34122         assert( (p->sharedMask & mask)==0 );
34123         p->exclMask |= mask;
34124       }
34125     }
34126   }
34127   sqlite3_mutex_leave(pShmNode->mutex);
34128   OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
34129            osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
34130            sqlite3ErrName(rc)));
34131   return rc;
34132 }
34133
34134 /*
34135 ** Implement a memory barrier or memory fence on shared memory.  
34136 **
34137 ** All loads and stores begun before the barrier must complete before
34138 ** any load or store begun after the barrier.
34139 */
34140 static void winShmBarrier(
34141   sqlite3_file *fd          /* Database holding the shared memory */
34142 ){
34143   UNUSED_PARAMETER(fd);
34144   /* MemoryBarrier(); // does not work -- do not know why not */
34145   winShmEnterMutex();
34146   winShmLeaveMutex();
34147 }
34148
34149 /*
34150 ** This function is called to obtain a pointer to region iRegion of the 
34151 ** shared-memory associated with the database file fd. Shared-memory regions 
34152 ** are numbered starting from zero. Each shared-memory region is szRegion 
34153 ** bytes in size.
34154 **
34155 ** If an error occurs, an error code is returned and *pp is set to NULL.
34156 **
34157 ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
34158 ** region has not been allocated (by any client, including one running in a
34159 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If 
34160 ** isWrite is non-zero and the requested shared-memory region has not yet 
34161 ** been allocated, it is allocated by this function.
34162 **
34163 ** If the shared-memory region has already been allocated or is allocated by
34164 ** this call as described above, then it is mapped into this processes 
34165 ** address space (if it is not already), *pp is set to point to the mapped 
34166 ** memory and SQLITE_OK returned.
34167 */
34168 static int winShmMap(
34169   sqlite3_file *fd,               /* Handle open on database file */
34170   int iRegion,                    /* Region to retrieve */
34171   int szRegion,                   /* Size of regions */
34172   int isWrite,                    /* True to extend file if necessary */
34173   void volatile **pp              /* OUT: Mapped memory */
34174 ){
34175   winFile *pDbFd = (winFile*)fd;
34176   winShm *p = pDbFd->pShm;
34177   winShmNode *pShmNode;
34178   int rc = SQLITE_OK;
34179
34180   if( !p ){
34181     rc = winOpenSharedMemory(pDbFd);
34182     if( rc!=SQLITE_OK ) return rc;
34183     p = pDbFd->pShm;
34184   }
34185   pShmNode = p->pShmNode;
34186
34187   sqlite3_mutex_enter(pShmNode->mutex);
34188   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
34189
34190   if( pShmNode->nRegion<=iRegion ){
34191     struct ShmRegion *apNew;           /* New aRegion[] array */
34192     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
34193     sqlite3_int64 sz;                  /* Current size of wal-index file */
34194
34195     pShmNode->szRegion = szRegion;
34196
34197     /* The requested region is not mapped into this processes address space.
34198     ** Check to see if it has been allocated (i.e. if the wal-index file is
34199     ** large enough to contain the requested region).
34200     */
34201     rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
34202     if( rc!=SQLITE_OK ){
34203       rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
34204                "winShmMap1", pDbFd->zPath);
34205       goto shmpage_out;
34206     }
34207
34208     if( sz<nByte ){
34209       /* The requested memory region does not exist. If isWrite is set to
34210       ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
34211       **
34212       ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
34213       ** the requested memory region.
34214       */
34215       if( !isWrite ) goto shmpage_out;
34216       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
34217       if( rc!=SQLITE_OK ){
34218         rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
34219                  "winShmMap2", pDbFd->zPath);
34220         goto shmpage_out;
34221       }
34222     }
34223
34224     /* Map the requested memory region into this processes address space. */
34225     apNew = (struct ShmRegion *)sqlite3_realloc(
34226         pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
34227     );
34228     if( !apNew ){
34229       rc = SQLITE_IOERR_NOMEM;
34230       goto shmpage_out;
34231     }
34232     pShmNode->aRegion = apNew;
34233
34234     while( pShmNode->nRegion<=iRegion ){
34235       HANDLE hMap = NULL;         /* file-mapping handle */
34236       void *pMap = 0;             /* Mapped memory region */
34237      
34238 #if SQLITE_OS_WINRT
34239       hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
34240           NULL, PAGE_READWRITE, nByte, NULL
34241       );
34242 #elif defined(SQLITE_WIN32_HAS_WIDE)
34243       hMap = osCreateFileMappingW(pShmNode->hFile.h, 
34244           NULL, PAGE_READWRITE, 0, nByte, NULL
34245       );
34246 #elif defined(SQLITE_WIN32_HAS_ANSI)
34247       hMap = osCreateFileMappingA(pShmNode->hFile.h, 
34248           NULL, PAGE_READWRITE, 0, nByte, NULL
34249       );
34250 #endif
34251       OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
34252                osGetCurrentProcessId(), pShmNode->nRegion, nByte,
34253                hMap ? "ok" : "failed"));
34254       if( hMap ){
34255         int iOffset = pShmNode->nRegion*szRegion;
34256         int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
34257 #if SQLITE_OS_WINRT
34258         pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
34259             iOffset - iOffsetShift, szRegion + iOffsetShift
34260         );
34261 #else
34262         pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
34263             0, iOffset - iOffsetShift, szRegion + iOffsetShift
34264         );
34265 #endif
34266         OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
34267                  osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
34268                  szRegion, pMap ? "ok" : "failed"));
34269       }
34270       if( !pMap ){
34271         pShmNode->lastErrno = osGetLastError();
34272         rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
34273                  "winShmMap3", pDbFd->zPath);
34274         if( hMap ) osCloseHandle(hMap);
34275         goto shmpage_out;
34276       }
34277
34278       pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
34279       pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
34280       pShmNode->nRegion++;
34281     }
34282   }
34283
34284 shmpage_out:
34285   if( pShmNode->nRegion>iRegion ){
34286     int iOffset = iRegion*szRegion;
34287     int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
34288     char *p = (char *)pShmNode->aRegion[iRegion].pMap;
34289     *pp = (void *)&p[iOffsetShift];
34290   }else{
34291     *pp = 0;
34292   }
34293   sqlite3_mutex_leave(pShmNode->mutex);
34294   return rc;
34295 }
34296
34297 #else
34298 # define winShmMap     0
34299 # define winShmLock    0
34300 # define winShmBarrier 0
34301 # define winShmUnmap   0
34302 #endif /* #ifndef SQLITE_OMIT_WAL */
34303
34304 /*
34305 ** Cleans up the mapped region of the specified file, if any.
34306 */
34307 #if SQLITE_MAX_MMAP_SIZE>0
34308 static int winUnmapfile(winFile *pFile){
34309   assert( pFile!=0 );
34310   OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
34311            "mmapSize=%lld, mmapSizeActual=%lld, mmapSizeMax=%lld\n",
34312            osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
34313            pFile->mmapSize, pFile->mmapSizeActual, pFile->mmapSizeMax));
34314   if( pFile->pMapRegion ){
34315     if( !osUnmapViewOfFile(pFile->pMapRegion) ){
34316       pFile->lastErrno = osGetLastError();
34317       OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
34318                "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
34319                pFile->pMapRegion));
34320       return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
34321                          "winUnmap1", pFile->zPath);
34322     }
34323     pFile->pMapRegion = 0;
34324     pFile->mmapSize = 0;
34325     pFile->mmapSizeActual = 0;
34326   }
34327   if( pFile->hMap!=NULL ){
34328     if( !osCloseHandle(pFile->hMap) ){
34329       pFile->lastErrno = osGetLastError();
34330       OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
34331                osGetCurrentProcessId(), pFile, pFile->hMap));
34332       return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
34333                          "winUnmap2", pFile->zPath);
34334     }
34335     pFile->hMap = NULL;
34336   }
34337   OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
34338            osGetCurrentProcessId(), pFile));
34339   return SQLITE_OK;
34340 }
34341
34342 /*
34343 ** Memory map or remap the file opened by file-descriptor pFd (if the file
34344 ** is already mapped, the existing mapping is replaced by the new). Or, if 
34345 ** there already exists a mapping for this file, and there are still 
34346 ** outstanding xFetch() references to it, this function is a no-op.
34347 **
34348 ** If parameter nByte is non-negative, then it is the requested size of 
34349 ** the mapping to create. Otherwise, if nByte is less than zero, then the 
34350 ** requested size is the size of the file on disk. The actual size of the
34351 ** created mapping is either the requested size or the value configured 
34352 ** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
34353 **
34354 ** SQLITE_OK is returned if no error occurs (even if the mapping is not
34355 ** recreated as a result of outstanding references) or an SQLite error
34356 ** code otherwise.
34357 */
34358 static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
34359   sqlite3_int64 nMap = nByte;
34360   int rc;
34361
34362   assert( nMap>=0 || pFd->nFetchOut==0 );
34363   OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
34364            osGetCurrentProcessId(), pFd, nByte));
34365
34366   if( pFd->nFetchOut>0 ) return SQLITE_OK;
34367
34368   if( nMap<0 ){
34369     rc = winFileSize((sqlite3_file*)pFd, &nMap);
34370     if( rc ){
34371       OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
34372                osGetCurrentProcessId(), pFd));
34373       return SQLITE_IOERR_FSTAT;
34374     }
34375   }
34376   if( nMap>pFd->mmapSizeMax ){
34377     nMap = pFd->mmapSizeMax;
34378   }
34379   nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
34380  
34381   if( nMap==0 && pFd->mmapSize>0 ){
34382     winUnmapfile(pFd);
34383   }
34384   if( nMap!=pFd->mmapSize ){
34385     void *pNew = 0;
34386     DWORD protect = PAGE_READONLY;
34387     DWORD flags = FILE_MAP_READ;
34388
34389     winUnmapfile(pFd);
34390     if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
34391       protect = PAGE_READWRITE;
34392       flags |= FILE_MAP_WRITE;
34393     }
34394 #if SQLITE_OS_WINRT
34395     pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
34396 #elif defined(SQLITE_WIN32_HAS_WIDE)
34397     pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
34398                                 (DWORD)((nMap>>32) & 0xffffffff),
34399                                 (DWORD)(nMap & 0xffffffff), NULL);
34400 #elif defined(SQLITE_WIN32_HAS_ANSI)
34401     pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
34402                                 (DWORD)((nMap>>32) & 0xffffffff),
34403                                 (DWORD)(nMap & 0xffffffff), NULL);
34404 #endif
34405     if( pFd->hMap==NULL ){
34406       pFd->lastErrno = osGetLastError();
34407       rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
34408                        "winMapfile", pFd->zPath);
34409       /* Log the error, but continue normal operation using xRead/xWrite */
34410       OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=SQLITE_IOERR_MMAP\n",
34411                osGetCurrentProcessId(), pFd));
34412       return SQLITE_OK;
34413     }
34414     assert( (nMap % winSysInfo.dwPageSize)==0 );
34415 #if SQLITE_OS_WINRT
34416     pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, nMap);
34417 #else
34418     assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
34419     pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
34420 #endif
34421     if( pNew==NULL ){
34422       osCloseHandle(pFd->hMap);
34423       pFd->hMap = NULL;
34424       pFd->lastErrno = osGetLastError();
34425       winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
34426                   "winMapfile", pFd->zPath);
34427       OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=SQLITE_IOERR_MMAP\n",
34428                osGetCurrentProcessId(), pFd));
34429       return SQLITE_OK;
34430     }
34431     pFd->pMapRegion = pNew;
34432     pFd->mmapSize = nMap;
34433     pFd->mmapSizeActual = nMap;
34434   }
34435
34436   OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
34437            osGetCurrentProcessId(), pFd));
34438   return SQLITE_OK;
34439 }
34440 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
34441
34442 /*
34443 ** If possible, return a pointer to a mapping of file fd starting at offset
34444 ** iOff. The mapping must be valid for at least nAmt bytes.
34445 **
34446 ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
34447 ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
34448 ** Finally, if an error does occur, return an SQLite error code. The final
34449 ** value of *pp is undefined in this case.
34450 **
34451 ** If this function does return a pointer, the caller must eventually 
34452 ** release the reference by calling winUnfetch().
34453 */
34454 static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
34455 #if SQLITE_MAX_MMAP_SIZE>0
34456   winFile *pFd = (winFile*)fd;   /* The underlying database file */
34457 #endif
34458   *pp = 0;
34459
34460   OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
34461            osGetCurrentProcessId(), fd, iOff, nAmt, pp));
34462
34463 #if SQLITE_MAX_MMAP_SIZE>0
34464   if( pFd->mmapSizeMax>0 ){
34465     if( pFd->pMapRegion==0 ){
34466       int rc = winMapfile(pFd, -1);
34467       if( rc!=SQLITE_OK ){
34468         OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
34469                  osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
34470         return rc;
34471       }
34472     }
34473     if( pFd->mmapSize >= iOff+nAmt ){
34474       *pp = &((u8 *)pFd->pMapRegion)[iOff];
34475       pFd->nFetchOut++;
34476     }
34477   }
34478 #endif
34479
34480   OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
34481            osGetCurrentProcessId(), fd, pp, *pp));
34482   return SQLITE_OK;
34483 }
34484
34485 /*
34486 ** If the third argument is non-NULL, then this function releases a 
34487 ** reference obtained by an earlier call to winFetch(). The second
34488 ** argument passed to this function must be the same as the corresponding
34489 ** argument that was passed to the winFetch() invocation. 
34490 **
34491 ** Or, if the third argument is NULL, then this function is being called 
34492 ** to inform the VFS layer that, according to POSIX, any existing mapping 
34493 ** may now be invalid and should be unmapped.
34494 */
34495 static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
34496 #if SQLITE_MAX_MMAP_SIZE>0
34497   winFile *pFd = (winFile*)fd;   /* The underlying database file */
34498
34499   /* If p==0 (unmap the entire file) then there must be no outstanding 
34500   ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
34501   ** then there must be at least one outstanding.  */
34502   assert( (p==0)==(pFd->nFetchOut==0) );
34503
34504   /* If p!=0, it must match the iOff value. */
34505   assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
34506
34507   OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
34508            osGetCurrentProcessId(), pFd, iOff, p));
34509
34510   if( p ){
34511     pFd->nFetchOut--;
34512   }else{
34513     /* FIXME:  If Windows truly always prevents truncating or deleting a
34514     ** file while a mapping is held, then the following winUnmapfile() call
34515     ** is unnecessary can can be omitted - potentially improving
34516     ** performance.  */
34517     winUnmapfile(pFd);
34518   }
34519
34520   assert( pFd->nFetchOut>=0 );
34521 #endif
34522
34523   OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
34524            osGetCurrentProcessId(), fd));
34525   return SQLITE_OK;
34526 }
34527
34528 /*
34529 ** Here ends the implementation of all sqlite3_file methods.
34530 **
34531 ********************** End sqlite3_file Methods *******************************
34532 ******************************************************************************/
34533
34534 /*
34535 ** This vector defines all the methods that can operate on an
34536 ** sqlite3_file for win32.
34537 */
34538 static const sqlite3_io_methods winIoMethod = {
34539   3,                              /* iVersion */
34540   winClose,                       /* xClose */
34541   winRead,                        /* xRead */
34542   winWrite,                       /* xWrite */
34543   winTruncate,                    /* xTruncate */
34544   winSync,                        /* xSync */
34545   winFileSize,                    /* xFileSize */
34546   winLock,                        /* xLock */
34547   winUnlock,                      /* xUnlock */
34548   winCheckReservedLock,           /* xCheckReservedLock */
34549   winFileControl,                 /* xFileControl */
34550   winSectorSize,                  /* xSectorSize */
34551   winDeviceCharacteristics,       /* xDeviceCharacteristics */
34552   winShmMap,                      /* xShmMap */
34553   winShmLock,                     /* xShmLock */
34554   winShmBarrier,                  /* xShmBarrier */
34555   winShmUnmap,                    /* xShmUnmap */
34556   winFetch,                       /* xFetch */
34557   winUnfetch                      /* xUnfetch */
34558 };
34559
34560 /****************************************************************************
34561 **************************** sqlite3_vfs methods ****************************
34562 **
34563 ** This division contains the implementation of methods on the
34564 ** sqlite3_vfs object.
34565 */
34566
34567 /*
34568 ** Convert a UTF-8 filename into whatever form the underlying
34569 ** operating system wants filenames in.  Space to hold the result
34570 ** is obtained from malloc and must be freed by the calling
34571 ** function.
34572 */
34573 static void *convertUtf8Filename(const char *zFilename){
34574   void *zConverted = 0;
34575   if( isNT() ){
34576     zConverted = utf8ToUnicode(zFilename);
34577   }
34578 #ifdef SQLITE_WIN32_HAS_ANSI
34579   else{
34580     zConverted = sqlite3_win32_utf8_to_mbcs(zFilename);
34581   }
34582 #endif
34583   /* caller will handle out of memory */
34584   return zConverted;
34585 }
34586
34587 /*
34588 ** Create a temporary file name in zBuf.  zBuf must be big enough to
34589 ** hold at pVfs->mxPathname characters.
34590 */
34591 static int getTempname(int nBuf, char *zBuf){
34592   static char zChars[] =
34593     "abcdefghijklmnopqrstuvwxyz"
34594     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
34595     "0123456789";
34596   size_t i, j;
34597   int nTempPath;
34598   char zTempPath[MAX_PATH+2];
34599
34600   /* It's odd to simulate an io-error here, but really this is just
34601   ** using the io-error infrastructure to test that SQLite handles this
34602   ** function failing. 
34603   */
34604   SimulateIOError( return SQLITE_IOERR );
34605
34606   memset(zTempPath, 0, MAX_PATH+2);
34607
34608   if( sqlite3_temp_directory ){
34609     sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
34610   }
34611 #if !SQLITE_OS_WINRT
34612   else if( isNT() ){
34613     char *zMulti;
34614     WCHAR zWidePath[MAX_PATH];
34615     osGetTempPathW(MAX_PATH-30, zWidePath);
34616     zMulti = unicodeToUtf8(zWidePath);
34617     if( zMulti ){
34618       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
34619       sqlite3_free(zMulti);
34620     }else{
34621       OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
34622       return SQLITE_IOERR_NOMEM;
34623     }
34624   }
34625 #ifdef SQLITE_WIN32_HAS_ANSI
34626   else{
34627     char *zUtf8;
34628     char zMbcsPath[MAX_PATH];
34629     osGetTempPathA(MAX_PATH-30, zMbcsPath);
34630     zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
34631     if( zUtf8 ){
34632       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
34633       sqlite3_free(zUtf8);
34634     }else{
34635       OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
34636       return SQLITE_IOERR_NOMEM;
34637     }
34638   }
34639 #endif
34640 #endif
34641
34642   /* Check that the output buffer is large enough for the temporary file 
34643   ** name. If it is not, return SQLITE_ERROR.
34644   */
34645   nTempPath = sqlite3Strlen30(zTempPath);
34646
34647   if( (nTempPath + sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX) + 18) >= nBuf ){
34648     OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
34649     return SQLITE_ERROR;
34650   }
34651
34652   for(i=nTempPath; i>0 && zTempPath[i-1]=='\\'; i--){}
34653   zTempPath[i] = 0;
34654
34655   sqlite3_snprintf(nBuf-18, zBuf, (nTempPath > 0) ?
34656                        "%s\\"SQLITE_TEMP_FILE_PREFIX : SQLITE_TEMP_FILE_PREFIX,
34657                    zTempPath);
34658   j = sqlite3Strlen30(zBuf);
34659   sqlite3_randomness(15, &zBuf[j]);
34660   for(i=0; i<15; i++, j++){
34661     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
34662   }
34663   zBuf[j] = 0;
34664   zBuf[j+1] = 0;
34665
34666   OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
34667   return SQLITE_OK;
34668 }
34669
34670 /*
34671 ** Return TRUE if the named file is really a directory.  Return false if
34672 ** it is something other than a directory, or if there is any kind of memory
34673 ** allocation failure.
34674 */
34675 static int winIsDir(const void *zConverted){
34676   DWORD attr;
34677   int rc = 0;
34678   DWORD lastErrno;
34679
34680   if( isNT() ){
34681     int cnt = 0;
34682     WIN32_FILE_ATTRIBUTE_DATA sAttrData;
34683     memset(&sAttrData, 0, sizeof(sAttrData));
34684     while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
34685                              GetFileExInfoStandard,
34686                              &sAttrData)) && retryIoerr(&cnt, &lastErrno) ){}
34687     if( !rc ){
34688       return 0; /* Invalid name? */
34689     }
34690     attr = sAttrData.dwFileAttributes;
34691 #if SQLITE_OS_WINCE==0
34692   }else{
34693     attr = osGetFileAttributesA((char*)zConverted);
34694 #endif
34695   }
34696   return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
34697 }
34698
34699 /*
34700 ** Open a file.
34701 */
34702 static int winOpen(
34703   sqlite3_vfs *pVfs,        /* Not used */
34704   const char *zName,        /* Name of the file (UTF-8) */
34705   sqlite3_file *id,         /* Write the SQLite file handle here */
34706   int flags,                /* Open mode flags */
34707   int *pOutFlags            /* Status return flags */
34708 ){
34709   HANDLE h;
34710   DWORD lastErrno;
34711   DWORD dwDesiredAccess;
34712   DWORD dwShareMode;
34713   DWORD dwCreationDisposition;
34714   DWORD dwFlagsAndAttributes = 0;
34715 #if SQLITE_OS_WINCE
34716   int isTemp = 0;
34717 #endif
34718   winFile *pFile = (winFile*)id;
34719   void *zConverted;              /* Filename in OS encoding */
34720   const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
34721   int cnt = 0;
34722
34723   /* If argument zPath is a NULL pointer, this function is required to open
34724   ** a temporary file. Use this buffer to store the file name in.
34725   */
34726   char zTmpname[MAX_PATH+2];     /* Buffer used to create temp filename */
34727
34728   int rc = SQLITE_OK;            /* Function Return Code */
34729 #if !defined(NDEBUG) || SQLITE_OS_WINCE
34730   int eType = flags&0xFFFFFF00;  /* Type of file to open */
34731 #endif
34732
34733   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
34734   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
34735   int isCreate     = (flags & SQLITE_OPEN_CREATE);
34736   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
34737   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
34738
34739 #ifndef NDEBUG
34740   int isOpenJournal = (isCreate && (
34741         eType==SQLITE_OPEN_MASTER_JOURNAL 
34742      || eType==SQLITE_OPEN_MAIN_JOURNAL 
34743      || eType==SQLITE_OPEN_WAL
34744   ));
34745 #endif
34746
34747   OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
34748            zUtf8Name, id, flags, pOutFlags));
34749
34750   /* Check the following statements are true: 
34751   **
34752   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
34753   **   (b) if CREATE is set, then READWRITE must also be set, and
34754   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
34755   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
34756   */
34757   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
34758   assert(isCreate==0 || isReadWrite);
34759   assert(isExclusive==0 || isCreate);
34760   assert(isDelete==0 || isCreate);
34761
34762   /* The main DB, main journal, WAL file and master journal are never 
34763   ** automatically deleted. Nor are they ever temporary files.  */
34764   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
34765   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
34766   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
34767   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
34768
34769   /* Assert that the upper layer has set one of the "file-type" flags. */
34770   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
34771        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
34772        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
34773        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
34774   );
34775
34776   assert( pFile!=0 );
34777   memset(pFile, 0, sizeof(winFile));
34778   pFile->h = INVALID_HANDLE_VALUE;
34779
34780 #if SQLITE_OS_WINRT
34781   if( !sqlite3_temp_directory ){
34782     sqlite3_log(SQLITE_ERROR,
34783         "sqlite3_temp_directory variable should be set for WinRT");
34784   }
34785 #endif
34786
34787   /* If the second argument to this function is NULL, generate a 
34788   ** temporary file name to use 
34789   */
34790   if( !zUtf8Name ){
34791     assert(isDelete && !isOpenJournal);
34792     memset(zTmpname, 0, MAX_PATH+2);
34793     rc = getTempname(MAX_PATH+2, zTmpname);
34794     if( rc!=SQLITE_OK ){
34795       OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
34796       return rc;
34797     }
34798     zUtf8Name = zTmpname;
34799   }
34800
34801   /* Database filenames are double-zero terminated if they are not
34802   ** URIs with parameters.  Hence, they can always be passed into
34803   ** sqlite3_uri_parameter().
34804   */
34805   assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
34806         zUtf8Name[strlen(zUtf8Name)+1]==0 );
34807
34808   /* Convert the filename to the system encoding. */
34809   zConverted = convertUtf8Filename(zUtf8Name);
34810   if( zConverted==0 ){
34811     OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
34812     return SQLITE_IOERR_NOMEM;
34813   }
34814
34815   if( winIsDir(zConverted) ){
34816     sqlite3_free(zConverted);
34817     OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
34818     return SQLITE_CANTOPEN_ISDIR;
34819   }
34820
34821   if( isReadWrite ){
34822     dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
34823   }else{
34824     dwDesiredAccess = GENERIC_READ;
34825   }
34826
34827   /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is 
34828   ** created. SQLite doesn't use it to indicate "exclusive access" 
34829   ** as it is usually understood.
34830   */
34831   if( isExclusive ){
34832     /* Creates a new file, only if it does not already exist. */
34833     /* If the file exists, it fails. */
34834     dwCreationDisposition = CREATE_NEW;
34835   }else if( isCreate ){
34836     /* Open existing file, or create if it doesn't exist */
34837     dwCreationDisposition = OPEN_ALWAYS;
34838   }else{
34839     /* Opens a file, only if it exists. */
34840     dwCreationDisposition = OPEN_EXISTING;
34841   }
34842
34843   dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
34844
34845   if( isDelete ){
34846 #if SQLITE_OS_WINCE
34847     dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
34848     isTemp = 1;
34849 #else
34850     dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
34851                                | FILE_ATTRIBUTE_HIDDEN
34852                                | FILE_FLAG_DELETE_ON_CLOSE;
34853 #endif
34854   }else{
34855     dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
34856   }
34857   /* Reports from the internet are that performance is always
34858   ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
34859 #if SQLITE_OS_WINCE
34860   dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
34861 #endif
34862
34863   if( isNT() ){
34864 #if SQLITE_OS_WINRT
34865     CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
34866     extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
34867     extendedParameters.dwFileAttributes =
34868             dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
34869     extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
34870     extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
34871     extendedParameters.lpSecurityAttributes = NULL;
34872     extendedParameters.hTemplateFile = NULL;
34873     while( (h = osCreateFile2((LPCWSTR)zConverted,
34874                               dwDesiredAccess,
34875                               dwShareMode,
34876                               dwCreationDisposition,
34877                               &extendedParameters))==INVALID_HANDLE_VALUE &&
34878                               retryIoerr(&cnt, &lastErrno) ){
34879                /* Noop */
34880     }
34881 #else
34882     while( (h = osCreateFileW((LPCWSTR)zConverted,
34883                               dwDesiredAccess,
34884                               dwShareMode, NULL,
34885                               dwCreationDisposition,
34886                               dwFlagsAndAttributes,
34887                               NULL))==INVALID_HANDLE_VALUE &&
34888                               retryIoerr(&cnt, &lastErrno) ){
34889                /* Noop */
34890     }
34891 #endif
34892   }
34893 #ifdef SQLITE_WIN32_HAS_ANSI
34894   else{
34895     while( (h = osCreateFileA((LPCSTR)zConverted,
34896                               dwDesiredAccess,
34897                               dwShareMode, NULL,
34898                               dwCreationDisposition,
34899                               dwFlagsAndAttributes,
34900                               NULL))==INVALID_HANDLE_VALUE &&
34901                               retryIoerr(&cnt, &lastErrno) ){
34902                /* Noop */
34903     }
34904   }
34905 #endif
34906   logIoerr(cnt);
34907
34908   OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
34909            dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
34910
34911   if( h==INVALID_HANDLE_VALUE ){
34912     pFile->lastErrno = lastErrno;
34913     winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
34914     sqlite3_free(zConverted);
34915     if( isReadWrite && !isExclusive ){
34916       return winOpen(pVfs, zName, id, 
34917          ((flags|SQLITE_OPEN_READONLY) &
34918                      ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
34919          pOutFlags);
34920     }else{
34921       return SQLITE_CANTOPEN_BKPT;
34922     }
34923   }
34924
34925   if( pOutFlags ){
34926     if( isReadWrite ){
34927       *pOutFlags = SQLITE_OPEN_READWRITE;
34928     }else{
34929       *pOutFlags = SQLITE_OPEN_READONLY;
34930     }
34931   }
34932
34933   OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
34934            "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
34935            *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
34936
34937 #if SQLITE_OS_WINCE
34938   if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
34939        && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
34940   ){
34941     osCloseHandle(h);
34942     sqlite3_free(zConverted);
34943     OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
34944     return rc;
34945   }
34946   if( isTemp ){
34947     pFile->zDeleteOnClose = zConverted;
34948   }else
34949 #endif
34950   {
34951     sqlite3_free(zConverted);
34952   }
34953
34954   pFile->pMethod = &winIoMethod;
34955   pFile->pVfs = pVfs;
34956   pFile->h = h;
34957   if( isReadonly ){
34958     pFile->ctrlFlags |= WINFILE_RDONLY;
34959   }
34960   if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
34961     pFile->ctrlFlags |= WINFILE_PSOW;
34962   }
34963   pFile->lastErrno = NO_ERROR;
34964   pFile->zPath = zName;
34965 #if SQLITE_MAX_MMAP_SIZE>0
34966   pFile->hMap = NULL;
34967   pFile->pMapRegion = 0;
34968   pFile->mmapSize = 0;
34969   pFile->mmapSizeActual = 0;
34970   pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
34971 #endif
34972
34973   OpenCounter(+1);
34974   return rc;
34975 }
34976
34977 /*
34978 ** Delete the named file.
34979 **
34980 ** Note that Windows does not allow a file to be deleted if some other
34981 ** process has it open.  Sometimes a virus scanner or indexing program
34982 ** will open a journal file shortly after it is created in order to do
34983 ** whatever it does.  While this other process is holding the
34984 ** file open, we will be unable to delete it.  To work around this
34985 ** problem, we delay 100 milliseconds and try to delete again.  Up
34986 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
34987 ** up and returning an error.
34988 */
34989 static int winDelete(
34990   sqlite3_vfs *pVfs,          /* Not used on win32 */
34991   const char *zFilename,      /* Name of file to delete */
34992   int syncDir                 /* Not used on win32 */
34993 ){
34994   int cnt = 0;
34995   int rc;
34996   DWORD attr;
34997   DWORD lastErrno;
34998   void *zConverted;
34999   UNUSED_PARAMETER(pVfs);
35000   UNUSED_PARAMETER(syncDir);
35001
35002   SimulateIOError(return SQLITE_IOERR_DELETE);
35003   OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
35004
35005   zConverted = convertUtf8Filename(zFilename);
35006   if( zConverted==0 ){
35007     return SQLITE_IOERR_NOMEM;
35008   }
35009   if( isNT() ){
35010     do {
35011 #if SQLITE_OS_WINRT
35012       WIN32_FILE_ATTRIBUTE_DATA sAttrData;
35013       memset(&sAttrData, 0, sizeof(sAttrData));
35014       if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
35015                                   &sAttrData) ){
35016         attr = sAttrData.dwFileAttributes;
35017       }else{
35018         lastErrno = osGetLastError();
35019         if( lastErrno==ERROR_FILE_NOT_FOUND
35020          || lastErrno==ERROR_PATH_NOT_FOUND ){
35021           rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
35022         }else{
35023           rc = SQLITE_ERROR;
35024         }
35025         break;
35026       }
35027 #else
35028       attr = osGetFileAttributesW(zConverted);
35029 #endif
35030       if ( attr==INVALID_FILE_ATTRIBUTES ){
35031         lastErrno = osGetLastError();
35032         if( lastErrno==ERROR_FILE_NOT_FOUND
35033          || lastErrno==ERROR_PATH_NOT_FOUND ){
35034           rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
35035         }else{
35036           rc = SQLITE_ERROR;
35037         }
35038         break;
35039       }
35040       if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
35041         rc = SQLITE_ERROR; /* Files only. */
35042         break;
35043       }
35044       if ( osDeleteFileW(zConverted) ){
35045         rc = SQLITE_OK; /* Deleted OK. */
35046         break;
35047       }
35048       if ( !retryIoerr(&cnt, &lastErrno) ){
35049         rc = SQLITE_ERROR; /* No more retries. */
35050         break;
35051       }
35052     } while(1);
35053   }
35054 #ifdef SQLITE_WIN32_HAS_ANSI
35055   else{
35056     do {
35057       attr = osGetFileAttributesA(zConverted);
35058       if ( attr==INVALID_FILE_ATTRIBUTES ){
35059         lastErrno = osGetLastError();
35060         if( lastErrno==ERROR_FILE_NOT_FOUND
35061          || lastErrno==ERROR_PATH_NOT_FOUND ){
35062           rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
35063         }else{
35064           rc = SQLITE_ERROR;
35065         }
35066         break;
35067       }
35068       if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
35069         rc = SQLITE_ERROR; /* Files only. */
35070         break;
35071       }
35072       if ( osDeleteFileA(zConverted) ){
35073         rc = SQLITE_OK; /* Deleted OK. */
35074         break;
35075       }
35076       if ( !retryIoerr(&cnt, &lastErrno) ){
35077         rc = SQLITE_ERROR; /* No more retries. */
35078         break;
35079       }
35080     } while(1);
35081   }
35082 #endif
35083   if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
35084     rc = winLogError(SQLITE_IOERR_DELETE, lastErrno,
35085              "winDelete", zFilename);
35086   }else{
35087     logIoerr(cnt);
35088   }
35089   sqlite3_free(zConverted);
35090   OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
35091   return rc;
35092 }
35093
35094 /*
35095 ** Check the existence and status of a file.
35096 */
35097 static int winAccess(
35098   sqlite3_vfs *pVfs,         /* Not used on win32 */
35099   const char *zFilename,     /* Name of file to check */
35100   int flags,                 /* Type of test to make on this file */
35101   int *pResOut               /* OUT: Result */
35102 ){
35103   DWORD attr;
35104   int rc = 0;
35105   DWORD lastErrno;
35106   void *zConverted;
35107   UNUSED_PARAMETER(pVfs);
35108
35109   SimulateIOError( return SQLITE_IOERR_ACCESS; );
35110   OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
35111            zFilename, flags, pResOut));
35112
35113   zConverted = convertUtf8Filename(zFilename);
35114   if( zConverted==0 ){
35115     OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
35116     return SQLITE_IOERR_NOMEM;
35117   }
35118   if( isNT() ){
35119     int cnt = 0;
35120     WIN32_FILE_ATTRIBUTE_DATA sAttrData;
35121     memset(&sAttrData, 0, sizeof(sAttrData));
35122     while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
35123                              GetFileExInfoStandard, 
35124                              &sAttrData)) && retryIoerr(&cnt, &lastErrno) ){}
35125     if( rc ){
35126       /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
35127       ** as if it does not exist.
35128       */
35129       if(    flags==SQLITE_ACCESS_EXISTS
35130           && sAttrData.nFileSizeHigh==0 
35131           && sAttrData.nFileSizeLow==0 ){
35132         attr = INVALID_FILE_ATTRIBUTES;
35133       }else{
35134         attr = sAttrData.dwFileAttributes;
35135       }
35136     }else{
35137       logIoerr(cnt);
35138       if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
35139         winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess", zFilename);
35140         sqlite3_free(zConverted);
35141         return SQLITE_IOERR_ACCESS;
35142       }else{
35143         attr = INVALID_FILE_ATTRIBUTES;
35144       }
35145     }
35146   }
35147 #ifdef SQLITE_WIN32_HAS_ANSI
35148   else{
35149     attr = osGetFileAttributesA((char*)zConverted);
35150   }
35151 #endif
35152   sqlite3_free(zConverted);
35153   switch( flags ){
35154     case SQLITE_ACCESS_READ:
35155     case SQLITE_ACCESS_EXISTS:
35156       rc = attr!=INVALID_FILE_ATTRIBUTES;
35157       break;
35158     case SQLITE_ACCESS_READWRITE:
35159       rc = attr!=INVALID_FILE_ATTRIBUTES &&
35160              (attr & FILE_ATTRIBUTE_READONLY)==0;
35161       break;
35162     default:
35163       assert(!"Invalid flags argument");
35164   }
35165   *pResOut = rc;
35166   OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
35167            zFilename, pResOut, *pResOut));
35168   return SQLITE_OK;
35169 }
35170
35171
35172 /*
35173 ** Returns non-zero if the specified path name should be used verbatim.  If
35174 ** non-zero is returned from this function, the calling function must simply
35175 ** use the provided path name verbatim -OR- resolve it into a full path name
35176 ** using the GetFullPathName Win32 API function (if available).
35177 */
35178 static BOOL winIsVerbatimPathname(
35179   const char *zPathname
35180 ){
35181   /*
35182   ** If the path name starts with a forward slash or a backslash, it is either
35183   ** a legal UNC name, a volume relative path, or an absolute path name in the
35184   ** "Unix" format on Windows.  There is no easy way to differentiate between
35185   ** the final two cases; therefore, we return the safer return value of TRUE
35186   ** so that callers of this function will simply use it verbatim.
35187   */
35188   if ( zPathname[0]=='/' || zPathname[0]=='\\' ){
35189     return TRUE;
35190   }
35191
35192   /*
35193   ** If the path name starts with a letter and a colon it is either a volume
35194   ** relative path or an absolute path.  Callers of this function must not
35195   ** attempt to treat it as a relative path name (i.e. they should simply use
35196   ** it verbatim).
35197   */
35198   if ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' ){
35199     return TRUE;
35200   }
35201
35202   /*
35203   ** If we get to this point, the path name should almost certainly be a purely
35204   ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
35205   */
35206   return FALSE;
35207 }
35208
35209 /*
35210 ** Turn a relative pathname into a full pathname.  Write the full
35211 ** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
35212 ** bytes in size.
35213 */
35214 static int winFullPathname(
35215   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
35216   const char *zRelative,        /* Possibly relative input path */
35217   int nFull,                    /* Size of output buffer in bytes */
35218   char *zFull                   /* Output buffer */
35219 ){
35220   
35221 #if defined(__CYGWIN__)
35222   SimulateIOError( return SQLITE_ERROR );
35223   UNUSED_PARAMETER(nFull);
35224   assert( pVfs->mxPathname>=MAX_PATH );
35225   assert( nFull>=pVfs->mxPathname );
35226   if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
35227     /*
35228     ** NOTE: We are dealing with a relative path name and the data
35229     **       directory has been set.  Therefore, use it as the basis
35230     **       for converting the relative path name to an absolute
35231     **       one by prepending the data directory and a slash.
35232     */
35233     char zOut[MAX_PATH+1];
35234     memset(zOut, 0, MAX_PATH+1);
35235     cygwin_conv_path(CCP_POSIX_TO_WIN_A|CCP_RELATIVE, zRelative, zOut,
35236                      MAX_PATH+1);
35237     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s\\%s",
35238                      sqlite3_data_directory, zOut);
35239   }else{
35240     cygwin_conv_path(CCP_POSIX_TO_WIN_A, zRelative, zFull, nFull);
35241   }
35242   return SQLITE_OK;
35243 #endif
35244
35245 #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
35246   SimulateIOError( return SQLITE_ERROR );
35247   /* WinCE has no concept of a relative pathname, or so I am told. */
35248   /* WinRT has no way to convert a relative path to an absolute one. */
35249   if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
35250     /*
35251     ** NOTE: We are dealing with a relative path name and the data
35252     **       directory has been set.  Therefore, use it as the basis
35253     **       for converting the relative path name to an absolute
35254     **       one by prepending the data directory and a backslash.
35255     */
35256     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s\\%s",
35257                      sqlite3_data_directory, zRelative);
35258   }else{
35259     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
35260   }
35261   return SQLITE_OK;
35262 #endif
35263
35264 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
35265   DWORD nByte;
35266   void *zConverted;
35267   char *zOut;
35268
35269   /* If this path name begins with "/X:", where "X" is any alphabetic
35270   ** character, discard the initial "/" from the pathname.
35271   */
35272   if( zRelative[0]=='/' && sqlite3Isalpha(zRelative[1]) && zRelative[2]==':' ){
35273     zRelative++;
35274   }
35275
35276   /* It's odd to simulate an io-error here, but really this is just
35277   ** using the io-error infrastructure to test that SQLite handles this
35278   ** function failing. This function could fail if, for example, the
35279   ** current working directory has been unlinked.
35280   */
35281   SimulateIOError( return SQLITE_ERROR );
35282   if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
35283     /*
35284     ** NOTE: We are dealing with a relative path name and the data
35285     **       directory has been set.  Therefore, use it as the basis
35286     **       for converting the relative path name to an absolute
35287     **       one by prepending the data directory and a backslash.
35288     */
35289     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s\\%s",
35290                      sqlite3_data_directory, zRelative);
35291     return SQLITE_OK;
35292   }
35293   zConverted = convertUtf8Filename(zRelative);
35294   if( zConverted==0 ){
35295     return SQLITE_IOERR_NOMEM;
35296   }
35297   if( isNT() ){
35298     LPWSTR zTemp;
35299     nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
35300     if( nByte==0 ){
35301       winLogError(SQLITE_ERROR, osGetLastError(),
35302                   "GetFullPathNameW1", zConverted);
35303       sqlite3_free(zConverted);
35304       return SQLITE_CANTOPEN_FULLPATH;
35305     }
35306     nByte += 3;
35307     zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
35308     if( zTemp==0 ){
35309       sqlite3_free(zConverted);
35310       return SQLITE_IOERR_NOMEM;
35311     }
35312     nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
35313     if( nByte==0 ){
35314       winLogError(SQLITE_ERROR, osGetLastError(),
35315                   "GetFullPathNameW2", zConverted);
35316       sqlite3_free(zConverted);
35317       sqlite3_free(zTemp);
35318       return SQLITE_CANTOPEN_FULLPATH;
35319     }
35320     sqlite3_free(zConverted);
35321     zOut = unicodeToUtf8(zTemp);
35322     sqlite3_free(zTemp);
35323   }
35324 #ifdef SQLITE_WIN32_HAS_ANSI
35325   else{
35326     char *zTemp;
35327     nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
35328     if( nByte==0 ){
35329       winLogError(SQLITE_ERROR, osGetLastError(),
35330                   "GetFullPathNameA1", zConverted);
35331       sqlite3_free(zConverted);
35332       return SQLITE_CANTOPEN_FULLPATH;
35333     }
35334     nByte += 3;
35335     zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
35336     if( zTemp==0 ){
35337       sqlite3_free(zConverted);
35338       return SQLITE_IOERR_NOMEM;
35339     }
35340     nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
35341     if( nByte==0 ){
35342       winLogError(SQLITE_ERROR, osGetLastError(),
35343                   "GetFullPathNameA2", zConverted);
35344       sqlite3_free(zConverted);
35345       sqlite3_free(zTemp);
35346       return SQLITE_CANTOPEN_FULLPATH;
35347     }
35348     sqlite3_free(zConverted);
35349     zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
35350     sqlite3_free(zTemp);
35351   }
35352 #endif
35353   if( zOut ){
35354     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
35355     sqlite3_free(zOut);
35356     return SQLITE_OK;
35357   }else{
35358     return SQLITE_IOERR_NOMEM;
35359   }
35360 #endif
35361 }
35362
35363 #ifndef SQLITE_OMIT_LOAD_EXTENSION
35364 /*
35365 ** Interfaces for opening a shared library, finding entry points
35366 ** within the shared library, and closing the shared library.
35367 */
35368 /*
35369 ** Interfaces for opening a shared library, finding entry points
35370 ** within the shared library, and closing the shared library.
35371 */
35372 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
35373   HANDLE h;
35374   void *zConverted = convertUtf8Filename(zFilename);
35375   UNUSED_PARAMETER(pVfs);
35376   if( zConverted==0 ){
35377     return 0;
35378   }
35379   if( isNT() ){
35380 #if SQLITE_OS_WINRT
35381     h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
35382 #else
35383     h = osLoadLibraryW((LPCWSTR)zConverted);
35384 #endif
35385   }
35386 #ifdef SQLITE_WIN32_HAS_ANSI
35387   else{
35388     h = osLoadLibraryA((char*)zConverted);
35389   }
35390 #endif
35391   sqlite3_free(zConverted);
35392   return (void*)h;
35393 }
35394 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
35395   UNUSED_PARAMETER(pVfs);
35396   getLastErrorMsg(osGetLastError(), nBuf, zBufOut);
35397 }
35398 static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
35399   UNUSED_PARAMETER(pVfs);
35400   return (void(*)(void))osGetProcAddressA((HANDLE)pH, zSym);
35401 }
35402 static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
35403   UNUSED_PARAMETER(pVfs);
35404   osFreeLibrary((HANDLE)pHandle);
35405 }
35406 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
35407   #define winDlOpen  0
35408   #define winDlError 0
35409   #define winDlSym   0
35410   #define winDlClose 0
35411 #endif
35412
35413
35414 /*
35415 ** Write up to nBuf bytes of randomness into zBuf.
35416 */
35417 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
35418   int n = 0;
35419   UNUSED_PARAMETER(pVfs);
35420 #if defined(SQLITE_TEST)
35421   n = nBuf;
35422   memset(zBuf, 0, nBuf);
35423 #else
35424   if( sizeof(SYSTEMTIME)<=nBuf-n ){
35425     SYSTEMTIME x;
35426     osGetSystemTime(&x);
35427     memcpy(&zBuf[n], &x, sizeof(x));
35428     n += sizeof(x);
35429   }
35430   if( sizeof(DWORD)<=nBuf-n ){
35431     DWORD pid = osGetCurrentProcessId();
35432     memcpy(&zBuf[n], &pid, sizeof(pid));
35433     n += sizeof(pid);
35434   }
35435 #if SQLITE_OS_WINRT
35436   if( sizeof(ULONGLONG)<=nBuf-n ){
35437     ULONGLONG cnt = osGetTickCount64();
35438     memcpy(&zBuf[n], &cnt, sizeof(cnt));
35439     n += sizeof(cnt);
35440   }
35441 #else
35442   if( sizeof(DWORD)<=nBuf-n ){
35443     DWORD cnt = osGetTickCount();
35444     memcpy(&zBuf[n], &cnt, sizeof(cnt));
35445     n += sizeof(cnt);
35446   }
35447 #endif
35448   if( sizeof(LARGE_INTEGER)<=nBuf-n ){
35449     LARGE_INTEGER i;
35450     osQueryPerformanceCounter(&i);
35451     memcpy(&zBuf[n], &i, sizeof(i));
35452     n += sizeof(i);
35453   }
35454 #endif
35455   return n;
35456 }
35457
35458
35459 /*
35460 ** Sleep for a little while.  Return the amount of time slept.
35461 */
35462 static int winSleep(sqlite3_vfs *pVfs, int microsec){
35463   sqlite3_win32_sleep((microsec+999)/1000);
35464   UNUSED_PARAMETER(pVfs);
35465   return ((microsec+999)/1000)*1000;
35466 }
35467
35468 /*
35469 ** The following variable, if set to a non-zero value, is interpreted as
35470 ** the number of seconds since 1970 and is used to set the result of
35471 ** sqlite3OsCurrentTime() during testing.
35472 */
35473 #ifdef SQLITE_TEST
35474 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
35475 #endif
35476
35477 /*
35478 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
35479 ** the current time and date as a Julian Day number times 86_400_000.  In
35480 ** other words, write into *piNow the number of milliseconds since the Julian
35481 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
35482 ** proleptic Gregorian calendar.
35483 **
35484 ** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date 
35485 ** cannot be found.
35486 */
35487 static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
35488   /* FILETIME structure is a 64-bit value representing the number of 
35489      100-nanosecond intervals since January 1, 1601 (= JD 2305813.5). 
35490   */
35491   FILETIME ft;
35492   static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
35493 #ifdef SQLITE_TEST
35494   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
35495 #endif
35496   /* 2^32 - to avoid use of LL and warnings in gcc */
35497   static const sqlite3_int64 max32BitValue = 
35498       (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
35499       (sqlite3_int64)294967296;
35500
35501 #if SQLITE_OS_WINCE
35502   SYSTEMTIME time;
35503   osGetSystemTime(&time);
35504   /* if SystemTimeToFileTime() fails, it returns zero. */
35505   if (!osSystemTimeToFileTime(&time,&ft)){
35506     return SQLITE_ERROR;
35507   }
35508 #else
35509   osGetSystemTimeAsFileTime( &ft );
35510 #endif
35511
35512   *piNow = winFiletimeEpoch +
35513             ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) + 
35514                (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
35515
35516 #ifdef SQLITE_TEST
35517   if( sqlite3_current_time ){
35518     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
35519   }
35520 #endif
35521   UNUSED_PARAMETER(pVfs);
35522   return SQLITE_OK;
35523 }
35524
35525 /*
35526 ** Find the current time (in Universal Coordinated Time).  Write the
35527 ** current time and date as a Julian Day number into *prNow and
35528 ** return 0.  Return 1 if the time and date cannot be found.
35529 */
35530 static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
35531   int rc;
35532   sqlite3_int64 i;
35533   rc = winCurrentTimeInt64(pVfs, &i);
35534   if( !rc ){
35535     *prNow = i/86400000.0;
35536   }
35537   return rc;
35538 }
35539
35540 /*
35541 ** The idea is that this function works like a combination of
35542 ** GetLastError() and FormatMessage() on Windows (or errno and
35543 ** strerror_r() on Unix). After an error is returned by an OS
35544 ** function, SQLite calls this function with zBuf pointing to
35545 ** a buffer of nBuf bytes. The OS layer should populate the
35546 ** buffer with a nul-terminated UTF-8 encoded error message
35547 ** describing the last IO error to have occurred within the calling
35548 ** thread.
35549 **
35550 ** If the error message is too large for the supplied buffer,
35551 ** it should be truncated. The return value of xGetLastError
35552 ** is zero if the error message fits in the buffer, or non-zero
35553 ** otherwise (if the message was truncated). If non-zero is returned,
35554 ** then it is not necessary to include the nul-terminator character
35555 ** in the output buffer.
35556 **
35557 ** Not supplying an error message will have no adverse effect
35558 ** on SQLite. It is fine to have an implementation that never
35559 ** returns an error message:
35560 **
35561 **   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
35562 **     assert(zBuf[0]=='\0');
35563 **     return 0;
35564 **   }
35565 **
35566 ** However if an error message is supplied, it will be incorporated
35567 ** by sqlite into the error message available to the user using
35568 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
35569 */
35570 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
35571   UNUSED_PARAMETER(pVfs);
35572   return getLastErrorMsg(osGetLastError(), nBuf, zBuf);
35573 }
35574
35575 /*
35576 ** Initialize and deinitialize the operating system interface.
35577 */
35578 SQLITE_API int sqlite3_os_init(void){
35579   static sqlite3_vfs winVfs = {
35580     3,                   /* iVersion */
35581     sizeof(winFile),     /* szOsFile */
35582     MAX_PATH,            /* mxPathname */
35583     0,                   /* pNext */
35584     "win32",             /* zName */
35585     0,                   /* pAppData */
35586     winOpen,             /* xOpen */
35587     winDelete,           /* xDelete */
35588     winAccess,           /* xAccess */
35589     winFullPathname,     /* xFullPathname */
35590     winDlOpen,           /* xDlOpen */
35591     winDlError,          /* xDlError */
35592     winDlSym,            /* xDlSym */
35593     winDlClose,          /* xDlClose */
35594     winRandomness,       /* xRandomness */
35595     winSleep,            /* xSleep */
35596     winCurrentTime,      /* xCurrentTime */
35597     winGetLastError,     /* xGetLastError */
35598     winCurrentTimeInt64, /* xCurrentTimeInt64 */
35599     winSetSystemCall,    /* xSetSystemCall */
35600     winGetSystemCall,    /* xGetSystemCall */
35601     winNextSystemCall,   /* xNextSystemCall */
35602   };
35603
35604   /* Double-check that the aSyscall[] array has been constructed
35605   ** correctly.  See ticket [bb3a86e890c8e96ab] */
35606   assert( ArraySize(aSyscall)==74 );
35607
35608   /* get memory map allocation granularity */
35609   memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
35610 #if SQLITE_OS_WINRT
35611   osGetNativeSystemInfo(&winSysInfo);
35612 #else
35613   osGetSystemInfo(&winSysInfo);
35614 #endif
35615   assert( winSysInfo.dwAllocationGranularity>0 );
35616   assert( winSysInfo.dwPageSize>0 );
35617
35618   sqlite3_vfs_register(&winVfs, 1);
35619   return SQLITE_OK; 
35620 }
35621
35622 SQLITE_API int sqlite3_os_end(void){ 
35623 #if SQLITE_OS_WINRT
35624   if( sleepObj!=NULL ){
35625     osCloseHandle(sleepObj);
35626     sleepObj = NULL;
35627   }
35628 #endif
35629   return SQLITE_OK;
35630 }
35631
35632 #endif /* SQLITE_OS_WIN */
35633
35634 /************** End of os_win.c **********************************************/
35635 /************** Begin file bitvec.c ******************************************/
35636 /*
35637 ** 2008 February 16
35638 **
35639 ** The author disclaims copyright to this source code.  In place of
35640 ** a legal notice, here is a blessing:
35641 **
35642 **    May you do good and not evil.
35643 **    May you find forgiveness for yourself and forgive others.
35644 **    May you share freely, never taking more than you give.
35645 **
35646 *************************************************************************
35647 ** This file implements an object that represents a fixed-length
35648 ** bitmap.  Bits are numbered starting with 1.
35649 **
35650 ** A bitmap is used to record which pages of a database file have been
35651 ** journalled during a transaction, or which pages have the "dont-write"
35652 ** property.  Usually only a few pages are meet either condition.
35653 ** So the bitmap is usually sparse and has low cardinality.
35654 ** But sometimes (for example when during a DROP of a large table) most
35655 ** or all of the pages in a database can get journalled.  In those cases, 
35656 ** the bitmap becomes dense with high cardinality.  The algorithm needs 
35657 ** to handle both cases well.
35658 **
35659 ** The size of the bitmap is fixed when the object is created.
35660 **
35661 ** All bits are clear when the bitmap is created.  Individual bits
35662 ** may be set or cleared one at a time.
35663 **
35664 ** Test operations are about 100 times more common that set operations.
35665 ** Clear operations are exceedingly rare.  There are usually between
35666 ** 5 and 500 set operations per Bitvec object, though the number of sets can
35667 ** sometimes grow into tens of thousands or larger.  The size of the
35668 ** Bitvec object is the number of pages in the database file at the
35669 ** start of a transaction, and is thus usually less than a few thousand,
35670 ** but can be as large as 2 billion for a really big database.
35671 */
35672
35673 /* Size of the Bitvec structure in bytes. */
35674 #define BITVEC_SZ        512
35675
35676 /* Round the union size down to the nearest pointer boundary, since that's how 
35677 ** it will be aligned within the Bitvec struct. */
35678 #define BITVEC_USIZE     (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
35679
35680 /* Type of the array "element" for the bitmap representation. 
35681 ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE. 
35682 ** Setting this to the "natural word" size of your CPU may improve
35683 ** performance. */
35684 #define BITVEC_TELEM     u8
35685 /* Size, in bits, of the bitmap element. */
35686 #define BITVEC_SZELEM    8
35687 /* Number of elements in a bitmap array. */
35688 #define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
35689 /* Number of bits in the bitmap array. */
35690 #define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
35691
35692 /* Number of u32 values in hash table. */
35693 #define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
35694 /* Maximum number of entries in hash table before 
35695 ** sub-dividing and re-hashing. */
35696 #define BITVEC_MXHASH    (BITVEC_NINT/2)
35697 /* Hashing function for the aHash representation.
35698 ** Empirical testing showed that the *37 multiplier 
35699 ** (an arbitrary prime)in the hash function provided 
35700 ** no fewer collisions than the no-op *1. */
35701 #define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
35702
35703 #define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
35704
35705
35706 /*
35707 ** A bitmap is an instance of the following structure.
35708 **
35709 ** This bitmap records the existence of zero or more bits
35710 ** with values between 1 and iSize, inclusive.
35711 **
35712 ** There are three possible representations of the bitmap.
35713 ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
35714 ** bitmap.  The least significant bit is bit 1.
35715 **
35716 ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
35717 ** a hash table that will hold up to BITVEC_MXHASH distinct values.
35718 **
35719 ** Otherwise, the value i is redirected into one of BITVEC_NPTR
35720 ** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
35721 ** handles up to iDivisor separate values of i.  apSub[0] holds
35722 ** values between 1 and iDivisor.  apSub[1] holds values between
35723 ** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
35724 ** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
35725 ** to hold deal with values between 1 and iDivisor.
35726 */
35727 struct Bitvec {
35728   u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
35729   u32 nSet;       /* Number of bits that are set - only valid for aHash
35730                   ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
35731                   ** this would be 125. */
35732   u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
35733                   /* Should >=0 for apSub element. */
35734                   /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
35735                   /* For a BITVEC_SZ of 512, this would be 34,359,739. */
35736   union {
35737     BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
35738     u32 aHash[BITVEC_NINT];      /* Hash table representation */
35739     Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
35740   } u;
35741 };
35742
35743 /*
35744 ** Create a new bitmap object able to handle bits between 0 and iSize,
35745 ** inclusive.  Return a pointer to the new object.  Return NULL if 
35746 ** malloc fails.
35747 */
35748 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
35749   Bitvec *p;
35750   assert( sizeof(*p)==BITVEC_SZ );
35751   p = sqlite3MallocZero( sizeof(*p) );
35752   if( p ){
35753     p->iSize = iSize;
35754   }
35755   return p;
35756 }
35757
35758 /*
35759 ** Check to see if the i-th bit is set.  Return true or false.
35760 ** If p is NULL (if the bitmap has not been created) or if
35761 ** i is out of range, then return false.
35762 */
35763 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
35764   if( p==0 ) return 0;
35765   if( i>p->iSize || i==0 ) return 0;
35766   i--;
35767   while( p->iDivisor ){
35768     u32 bin = i/p->iDivisor;
35769     i = i%p->iDivisor;
35770     p = p->u.apSub[bin];
35771     if (!p) {
35772       return 0;
35773     }
35774   }
35775   if( p->iSize<=BITVEC_NBIT ){
35776     return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
35777   } else{
35778     u32 h = BITVEC_HASH(i++);
35779     while( p->u.aHash[h] ){
35780       if( p->u.aHash[h]==i ) return 1;
35781       h = (h+1) % BITVEC_NINT;
35782     }
35783     return 0;
35784   }
35785 }
35786
35787 /*
35788 ** Set the i-th bit.  Return 0 on success and an error code if
35789 ** anything goes wrong.
35790 **
35791 ** This routine might cause sub-bitmaps to be allocated.  Failing
35792 ** to get the memory needed to hold the sub-bitmap is the only
35793 ** that can go wrong with an insert, assuming p and i are valid.
35794 **
35795 ** The calling function must ensure that p is a valid Bitvec object
35796 ** and that the value for "i" is within range of the Bitvec object.
35797 ** Otherwise the behavior is undefined.
35798 */
35799 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
35800   u32 h;
35801   if( p==0 ) return SQLITE_OK;
35802   assert( i>0 );
35803   assert( i<=p->iSize );
35804   i--;
35805   while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
35806     u32 bin = i/p->iDivisor;
35807     i = i%p->iDivisor;
35808     if( p->u.apSub[bin]==0 ){
35809       p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
35810       if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
35811     }
35812     p = p->u.apSub[bin];
35813   }
35814   if( p->iSize<=BITVEC_NBIT ){
35815     p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
35816     return SQLITE_OK;
35817   }
35818   h = BITVEC_HASH(i++);
35819   /* if there wasn't a hash collision, and this doesn't */
35820   /* completely fill the hash, then just add it without */
35821   /* worring about sub-dividing and re-hashing. */
35822   if( !p->u.aHash[h] ){
35823     if (p->nSet<(BITVEC_NINT-1)) {
35824       goto bitvec_set_end;
35825     } else {
35826       goto bitvec_set_rehash;
35827     }
35828   }
35829   /* there was a collision, check to see if it's already */
35830   /* in hash, if not, try to find a spot for it */
35831   do {
35832     if( p->u.aHash[h]==i ) return SQLITE_OK;
35833     h++;
35834     if( h>=BITVEC_NINT ) h = 0;
35835   } while( p->u.aHash[h] );
35836   /* we didn't find it in the hash.  h points to the first */
35837   /* available free spot. check to see if this is going to */
35838   /* make our hash too "full".  */
35839 bitvec_set_rehash:
35840   if( p->nSet>=BITVEC_MXHASH ){
35841     unsigned int j;
35842     int rc;
35843     u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
35844     if( aiValues==0 ){
35845       return SQLITE_NOMEM;
35846     }else{
35847       memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
35848       memset(p->u.apSub, 0, sizeof(p->u.apSub));
35849       p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
35850       rc = sqlite3BitvecSet(p, i);
35851       for(j=0; j<BITVEC_NINT; j++){
35852         if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
35853       }
35854       sqlite3StackFree(0, aiValues);
35855       return rc;
35856     }
35857   }
35858 bitvec_set_end:
35859   p->nSet++;
35860   p->u.aHash[h] = i;
35861   return SQLITE_OK;
35862 }
35863
35864 /*
35865 ** Clear the i-th bit.
35866 **
35867 ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
35868 ** that BitvecClear can use to rebuilt its hash table.
35869 */
35870 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
35871   if( p==0 ) return;
35872   assert( i>0 );
35873   i--;
35874   while( p->iDivisor ){
35875     u32 bin = i/p->iDivisor;
35876     i = i%p->iDivisor;
35877     p = p->u.apSub[bin];
35878     if (!p) {
35879       return;
35880     }
35881   }
35882   if( p->iSize<=BITVEC_NBIT ){
35883     p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
35884   }else{
35885     unsigned int j;
35886     u32 *aiValues = pBuf;
35887     memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
35888     memset(p->u.aHash, 0, sizeof(p->u.aHash));
35889     p->nSet = 0;
35890     for(j=0; j<BITVEC_NINT; j++){
35891       if( aiValues[j] && aiValues[j]!=(i+1) ){
35892         u32 h = BITVEC_HASH(aiValues[j]-1);
35893         p->nSet++;
35894         while( p->u.aHash[h] ){
35895           h++;
35896           if( h>=BITVEC_NINT ) h = 0;
35897         }
35898         p->u.aHash[h] = aiValues[j];
35899       }
35900     }
35901   }
35902 }
35903
35904 /*
35905 ** Destroy a bitmap object.  Reclaim all memory used.
35906 */
35907 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
35908   if( p==0 ) return;
35909   if( p->iDivisor ){
35910     unsigned int i;
35911     for(i=0; i<BITVEC_NPTR; i++){
35912       sqlite3BitvecDestroy(p->u.apSub[i]);
35913     }
35914   }
35915   sqlite3_free(p);
35916 }
35917
35918 /*
35919 ** Return the value of the iSize parameter specified when Bitvec *p
35920 ** was created.
35921 */
35922 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
35923   return p->iSize;
35924 }
35925
35926 #ifndef SQLITE_OMIT_BUILTIN_TEST
35927 /*
35928 ** Let V[] be an array of unsigned characters sufficient to hold
35929 ** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
35930 ** Then the following macros can be used to set, clear, or test
35931 ** individual bits within V.
35932 */
35933 #define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
35934 #define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
35935 #define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
35936
35937 /*
35938 ** This routine runs an extensive test of the Bitvec code.
35939 **
35940 ** The input is an array of integers that acts as a program
35941 ** to test the Bitvec.  The integers are opcodes followed
35942 ** by 0, 1, or 3 operands, depending on the opcode.  Another
35943 ** opcode follows immediately after the last operand.
35944 **
35945 ** There are 6 opcodes numbered from 0 through 5.  0 is the
35946 ** "halt" opcode and causes the test to end.
35947 **
35948 **    0          Halt and return the number of errors
35949 **    1 N S X    Set N bits beginning with S and incrementing by X
35950 **    2 N S X    Clear N bits beginning with S and incrementing by X
35951 **    3 N        Set N randomly chosen bits
35952 **    4 N        Clear N randomly chosen bits
35953 **    5 N S X    Set N bits from S increment X in array only, not in bitvec
35954 **
35955 ** The opcodes 1 through 4 perform set and clear operations are performed
35956 ** on both a Bitvec object and on a linear array of bits obtained from malloc.
35957 ** Opcode 5 works on the linear array only, not on the Bitvec.
35958 ** Opcode 5 is used to deliberately induce a fault in order to
35959 ** confirm that error detection works.
35960 **
35961 ** At the conclusion of the test the linear array is compared
35962 ** against the Bitvec object.  If there are any differences,
35963 ** an error is returned.  If they are the same, zero is returned.
35964 **
35965 ** If a memory allocation error occurs, return -1.
35966 */
35967 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
35968   Bitvec *pBitvec = 0;
35969   unsigned char *pV = 0;
35970   int rc = -1;
35971   int i, nx, pc, op;
35972   void *pTmpSpace;
35973
35974   /* Allocate the Bitvec to be tested and a linear array of
35975   ** bits to act as the reference */
35976   pBitvec = sqlite3BitvecCreate( sz );
35977   pV = sqlite3MallocZero( (sz+7)/8 + 1 );
35978   pTmpSpace = sqlite3_malloc(BITVEC_SZ);
35979   if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
35980
35981   /* NULL pBitvec tests */
35982   sqlite3BitvecSet(0, 1);
35983   sqlite3BitvecClear(0, 1, pTmpSpace);
35984
35985   /* Run the program */
35986   pc = 0;
35987   while( (op = aOp[pc])!=0 ){
35988     switch( op ){
35989       case 1:
35990       case 2:
35991       case 5: {
35992         nx = 4;
35993         i = aOp[pc+2] - 1;
35994         aOp[pc+2] += aOp[pc+3];
35995         break;
35996       }
35997       case 3:
35998       case 4: 
35999       default: {
36000         nx = 2;
36001         sqlite3_randomness(sizeof(i), &i);
36002         break;
36003       }
36004     }
36005     if( (--aOp[pc+1]) > 0 ) nx = 0;
36006     pc += nx;
36007     i = (i & 0x7fffffff)%sz;
36008     if( (op & 1)!=0 ){
36009       SETBIT(pV, (i+1));
36010       if( op!=5 ){
36011         if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
36012       }
36013     }else{
36014       CLEARBIT(pV, (i+1));
36015       sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
36016     }
36017   }
36018
36019   /* Test to make sure the linear array exactly matches the
36020   ** Bitvec object.  Start with the assumption that they do
36021   ** match (rc==0).  Change rc to non-zero if a discrepancy
36022   ** is found.
36023   */
36024   rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
36025           + sqlite3BitvecTest(pBitvec, 0)
36026           + (sqlite3BitvecSize(pBitvec) - sz);
36027   for(i=1; i<=sz; i++){
36028     if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
36029       rc = i;
36030       break;
36031     }
36032   }
36033
36034   /* Free allocated structure */
36035 bitvec_end:
36036   sqlite3_free(pTmpSpace);
36037   sqlite3_free(pV);
36038   sqlite3BitvecDestroy(pBitvec);
36039   return rc;
36040 }
36041 #endif /* SQLITE_OMIT_BUILTIN_TEST */
36042
36043 /************** End of bitvec.c **********************************************/
36044 /************** Begin file pcache.c ******************************************/
36045 /*
36046 ** 2008 August 05
36047 **
36048 ** The author disclaims copyright to this source code.  In place of
36049 ** a legal notice, here is a blessing:
36050 **
36051 **    May you do good and not evil.
36052 **    May you find forgiveness for yourself and forgive others.
36053 **    May you share freely, never taking more than you give.
36054 **
36055 *************************************************************************
36056 ** This file implements that page cache.
36057 */
36058
36059 /*
36060 ** A complete page cache is an instance of this structure.
36061 */
36062 struct PCache {
36063   PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
36064   PgHdr *pSynced;                     /* Last synced page in dirty page list */
36065   int nRef;                           /* Number of referenced pages */
36066   int szCache;                        /* Configured cache size */
36067   int szPage;                         /* Size of every page in this cache */
36068   int szExtra;                        /* Size of extra space for each page */
36069   int bPurgeable;                     /* True if pages are on backing store */
36070   int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
36071   void *pStress;                      /* Argument to xStress */
36072   sqlite3_pcache *pCache;             /* Pluggable cache module */
36073   PgHdr *pPage1;                      /* Reference to page 1 */
36074 };
36075
36076 /*
36077 ** Some of the assert() macros in this code are too expensive to run
36078 ** even during normal debugging.  Use them only rarely on long-running
36079 ** tests.  Enable the expensive asserts using the
36080 ** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
36081 */
36082 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
36083 # define expensive_assert(X)  assert(X)
36084 #else
36085 # define expensive_assert(X)
36086 #endif
36087
36088 /********************************** Linked List Management ********************/
36089
36090 #if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
36091 /*
36092 ** Check that the pCache->pSynced variable is set correctly. If it
36093 ** is not, either fail an assert or return zero. Otherwise, return
36094 ** non-zero. This is only used in debugging builds, as follows:
36095 **
36096 **   expensive_assert( pcacheCheckSynced(pCache) );
36097 */
36098 static int pcacheCheckSynced(PCache *pCache){
36099   PgHdr *p;
36100   for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
36101     assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
36102   }
36103   return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
36104 }
36105 #endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
36106
36107 /*
36108 ** Remove page pPage from the list of dirty pages.
36109 */
36110 static void pcacheRemoveFromDirtyList(PgHdr *pPage){
36111   PCache *p = pPage->pCache;
36112
36113   assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
36114   assert( pPage->pDirtyPrev || pPage==p->pDirty );
36115
36116   /* Update the PCache1.pSynced variable if necessary. */
36117   if( p->pSynced==pPage ){
36118     PgHdr *pSynced = pPage->pDirtyPrev;
36119     while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
36120       pSynced = pSynced->pDirtyPrev;
36121     }
36122     p->pSynced = pSynced;
36123   }
36124
36125   if( pPage->pDirtyNext ){
36126     pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
36127   }else{
36128     assert( pPage==p->pDirtyTail );
36129     p->pDirtyTail = pPage->pDirtyPrev;
36130   }
36131   if( pPage->pDirtyPrev ){
36132     pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
36133   }else{
36134     assert( pPage==p->pDirty );
36135     p->pDirty = pPage->pDirtyNext;
36136   }
36137   pPage->pDirtyNext = 0;
36138   pPage->pDirtyPrev = 0;
36139
36140   expensive_assert( pcacheCheckSynced(p) );
36141 }
36142
36143 /*
36144 ** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
36145 ** pPage).
36146 */
36147 static void pcacheAddToDirtyList(PgHdr *pPage){
36148   PCache *p = pPage->pCache;
36149
36150   assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
36151
36152   pPage->pDirtyNext = p->pDirty;
36153   if( pPage->pDirtyNext ){
36154     assert( pPage->pDirtyNext->pDirtyPrev==0 );
36155     pPage->pDirtyNext->pDirtyPrev = pPage;
36156   }
36157   p->pDirty = pPage;
36158   if( !p->pDirtyTail ){
36159     p->pDirtyTail = pPage;
36160   }
36161   if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
36162     p->pSynced = pPage;
36163   }
36164   expensive_assert( pcacheCheckSynced(p) );
36165 }
36166
36167 /*
36168 ** Wrapper around the pluggable caches xUnpin method. If the cache is
36169 ** being used for an in-memory database, this function is a no-op.
36170 */
36171 static void pcacheUnpin(PgHdr *p){
36172   PCache *pCache = p->pCache;
36173   if( pCache->bPurgeable ){
36174     if( p->pgno==1 ){
36175       pCache->pPage1 = 0;
36176     }
36177     sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 0);
36178   }
36179 }
36180
36181 /*************************************************** General Interfaces ******
36182 **
36183 ** Initialize and shutdown the page cache subsystem. Neither of these 
36184 ** functions are threadsafe.
36185 */
36186 SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
36187   if( sqlite3GlobalConfig.pcache2.xInit==0 ){
36188     /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
36189     ** built-in default page cache is used instead of the application defined
36190     ** page cache. */
36191     sqlite3PCacheSetDefault();
36192   }
36193   return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
36194 }
36195 SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
36196   if( sqlite3GlobalConfig.pcache2.xShutdown ){
36197     /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
36198     sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
36199   }
36200 }
36201
36202 /*
36203 ** Return the size in bytes of a PCache object.
36204 */
36205 SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
36206
36207 /*
36208 ** Create a new PCache object. Storage space to hold the object
36209 ** has already been allocated and is passed in as the p pointer. 
36210 ** The caller discovers how much space needs to be allocated by 
36211 ** calling sqlite3PcacheSize().
36212 */
36213 SQLITE_PRIVATE void sqlite3PcacheOpen(
36214   int szPage,                  /* Size of every page */
36215   int szExtra,                 /* Extra space associated with each page */
36216   int bPurgeable,              /* True if pages are on backing store */
36217   int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
36218   void *pStress,               /* Argument to xStress */
36219   PCache *p                    /* Preallocated space for the PCache */
36220 ){
36221   memset(p, 0, sizeof(PCache));
36222   p->szPage = szPage;
36223   p->szExtra = szExtra;
36224   p->bPurgeable = bPurgeable;
36225   p->xStress = xStress;
36226   p->pStress = pStress;
36227   p->szCache = 100;
36228 }
36229
36230 /*
36231 ** Change the page size for PCache object. The caller must ensure that there
36232 ** are no outstanding page references when this function is called.
36233 */
36234 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
36235   assert( pCache->nRef==0 && pCache->pDirty==0 );
36236   if( pCache->pCache ){
36237     sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
36238     pCache->pCache = 0;
36239     pCache->pPage1 = 0;
36240   }
36241   pCache->szPage = szPage;
36242 }
36243
36244 /*
36245 ** Compute the number of pages of cache requested.
36246 */
36247 static int numberOfCachePages(PCache *p){
36248   if( p->szCache>=0 ){
36249     return p->szCache;
36250   }else{
36251     return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
36252   }
36253 }
36254
36255 /*
36256 ** Try to obtain a page from the cache.
36257 */
36258 SQLITE_PRIVATE int sqlite3PcacheFetch(
36259   PCache *pCache,       /* Obtain the page from this cache */
36260   Pgno pgno,            /* Page number to obtain */
36261   int createFlag,       /* If true, create page if it does not exist already */
36262   PgHdr **ppPage        /* Write the page here */
36263 ){
36264   sqlite3_pcache_page *pPage = 0;
36265   PgHdr *pPgHdr = 0;
36266   int eCreate;
36267
36268   assert( pCache!=0 );
36269   assert( createFlag==1 || createFlag==0 );
36270   assert( pgno>0 );
36271
36272   /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
36273   ** allocate it now.
36274   */
36275   if( !pCache->pCache && createFlag ){
36276     sqlite3_pcache *p;
36277     p = sqlite3GlobalConfig.pcache2.xCreate(
36278         pCache->szPage, pCache->szExtra + sizeof(PgHdr), pCache->bPurgeable
36279     );
36280     if( !p ){
36281       return SQLITE_NOMEM;
36282     }
36283     sqlite3GlobalConfig.pcache2.xCachesize(p, numberOfCachePages(pCache));
36284     pCache->pCache = p;
36285   }
36286
36287   eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty));
36288   if( pCache->pCache ){
36289     pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
36290   }
36291
36292   if( !pPage && eCreate==1 ){
36293     PgHdr *pPg;
36294
36295     /* Find a dirty page to write-out and recycle. First try to find a 
36296     ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
36297     ** cleared), but if that is not possible settle for any other 
36298     ** unreferenced dirty page.
36299     */
36300     expensive_assert( pcacheCheckSynced(pCache) );
36301     for(pPg=pCache->pSynced; 
36302         pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC)); 
36303         pPg=pPg->pDirtyPrev
36304     );
36305     pCache->pSynced = pPg;
36306     if( !pPg ){
36307       for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
36308     }
36309     if( pPg ){
36310       int rc;
36311 #ifdef SQLITE_LOG_CACHE_SPILL
36312       sqlite3_log(SQLITE_FULL, 
36313                   "spill page %d making room for %d - cache used: %d/%d",
36314                   pPg->pgno, pgno,
36315                   sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
36316                   numberOfCachePages(pCache));
36317 #endif
36318       rc = pCache->xStress(pCache->pStress, pPg);
36319       if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
36320         return rc;
36321       }
36322     }
36323
36324     pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
36325   }
36326
36327   if( pPage ){
36328     pPgHdr = (PgHdr *)pPage->pExtra;
36329
36330     if( !pPgHdr->pPage ){
36331       memset(pPgHdr, 0, sizeof(PgHdr));
36332       pPgHdr->pPage = pPage;
36333       pPgHdr->pData = pPage->pBuf;
36334       pPgHdr->pExtra = (void *)&pPgHdr[1];
36335       memset(pPgHdr->pExtra, 0, pCache->szExtra);
36336       pPgHdr->pCache = pCache;
36337       pPgHdr->pgno = pgno;
36338     }
36339     assert( pPgHdr->pCache==pCache );
36340     assert( pPgHdr->pgno==pgno );
36341     assert( pPgHdr->pData==pPage->pBuf );
36342     assert( pPgHdr->pExtra==(void *)&pPgHdr[1] );
36343
36344     if( 0==pPgHdr->nRef ){
36345       pCache->nRef++;
36346     }
36347     pPgHdr->nRef++;
36348     if( pgno==1 ){
36349       pCache->pPage1 = pPgHdr;
36350     }
36351   }
36352   *ppPage = pPgHdr;
36353   return (pPgHdr==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
36354 }
36355
36356 /*
36357 ** Decrement the reference count on a page. If the page is clean and the
36358 ** reference count drops to 0, then it is made elible for recycling.
36359 */
36360 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
36361   assert( p->nRef>0 );
36362   p->nRef--;
36363   if( p->nRef==0 ){
36364     PCache *pCache = p->pCache;
36365     pCache->nRef--;
36366     if( (p->flags&PGHDR_DIRTY)==0 ){
36367       pcacheUnpin(p);
36368     }else{
36369       /* Move the page to the head of the dirty list. */
36370       pcacheRemoveFromDirtyList(p);
36371       pcacheAddToDirtyList(p);
36372     }
36373   }
36374 }
36375
36376 /*
36377 ** Increase the reference count of a supplied page by 1.
36378 */
36379 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
36380   assert(p->nRef>0);
36381   p->nRef++;
36382 }
36383
36384 /*
36385 ** Drop a page from the cache. There must be exactly one reference to the
36386 ** page. This function deletes that reference, so after it returns the
36387 ** page pointed to by p is invalid.
36388 */
36389 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
36390   PCache *pCache;
36391   assert( p->nRef==1 );
36392   if( p->flags&PGHDR_DIRTY ){
36393     pcacheRemoveFromDirtyList(p);
36394   }
36395   pCache = p->pCache;
36396   pCache->nRef--;
36397   if( p->pgno==1 ){
36398     pCache->pPage1 = 0;
36399   }
36400   sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 1);
36401 }
36402
36403 /*
36404 ** Make sure the page is marked as dirty. If it isn't dirty already,
36405 ** make it so.
36406 */
36407 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
36408   p->flags &= ~PGHDR_DONT_WRITE;
36409   assert( p->nRef>0 );
36410   if( 0==(p->flags & PGHDR_DIRTY) ){
36411     p->flags |= PGHDR_DIRTY;
36412     pcacheAddToDirtyList( p);
36413   }
36414 }
36415
36416 /*
36417 ** Make sure the page is marked as clean. If it isn't clean already,
36418 ** make it so.
36419 */
36420 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
36421   if( (p->flags & PGHDR_DIRTY) ){
36422     pcacheRemoveFromDirtyList(p);
36423     p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
36424     if( p->nRef==0 ){
36425       pcacheUnpin(p);
36426     }
36427   }
36428 }
36429
36430 /*
36431 ** Make every page in the cache clean.
36432 */
36433 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
36434   PgHdr *p;
36435   while( (p = pCache->pDirty)!=0 ){
36436     sqlite3PcacheMakeClean(p);
36437   }
36438 }
36439
36440 /*
36441 ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
36442 */
36443 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
36444   PgHdr *p;
36445   for(p=pCache->pDirty; p; p=p->pDirtyNext){
36446     p->flags &= ~PGHDR_NEED_SYNC;
36447   }
36448   pCache->pSynced = pCache->pDirtyTail;
36449 }
36450
36451 /*
36452 ** Change the page number of page p to newPgno. 
36453 */
36454 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
36455   PCache *pCache = p->pCache;
36456   assert( p->nRef>0 );
36457   assert( newPgno>0 );
36458   sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
36459   p->pgno = newPgno;
36460   if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
36461     pcacheRemoveFromDirtyList(p);
36462     pcacheAddToDirtyList(p);
36463   }
36464 }
36465
36466 /*
36467 ** Drop every cache entry whose page number is greater than "pgno". The
36468 ** caller must ensure that there are no outstanding references to any pages
36469 ** other than page 1 with a page number greater than pgno.
36470 **
36471 ** If there is a reference to page 1 and the pgno parameter passed to this
36472 ** function is 0, then the data area associated with page 1 is zeroed, but
36473 ** the page object is not dropped.
36474 */
36475 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
36476   if( pCache->pCache ){
36477     PgHdr *p;
36478     PgHdr *pNext;
36479     for(p=pCache->pDirty; p; p=pNext){
36480       pNext = p->pDirtyNext;
36481       /* This routine never gets call with a positive pgno except right
36482       ** after sqlite3PcacheCleanAll().  So if there are dirty pages,
36483       ** it must be that pgno==0.
36484       */
36485       assert( p->pgno>0 );
36486       if( ALWAYS(p->pgno>pgno) ){
36487         assert( p->flags&PGHDR_DIRTY );
36488         sqlite3PcacheMakeClean(p);
36489       }
36490     }
36491     if( pgno==0 && pCache->pPage1 ){
36492       memset(pCache->pPage1->pData, 0, pCache->szPage);
36493       pgno = 1;
36494     }
36495     sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
36496   }
36497 }
36498
36499 /*
36500 ** Close a cache.
36501 */
36502 SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
36503   if( pCache->pCache ){
36504     sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
36505   }
36506 }
36507
36508 /* 
36509 ** Discard the contents of the cache.
36510 */
36511 SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
36512   sqlite3PcacheTruncate(pCache, 0);
36513 }
36514
36515 /*
36516 ** Merge two lists of pages connected by pDirty and in pgno order.
36517 ** Do not both fixing the pDirtyPrev pointers.
36518 */
36519 static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
36520   PgHdr result, *pTail;
36521   pTail = &result;
36522   while( pA && pB ){
36523     if( pA->pgno<pB->pgno ){
36524       pTail->pDirty = pA;
36525       pTail = pA;
36526       pA = pA->pDirty;
36527     }else{
36528       pTail->pDirty = pB;
36529       pTail = pB;
36530       pB = pB->pDirty;
36531     }
36532   }
36533   if( pA ){
36534     pTail->pDirty = pA;
36535   }else if( pB ){
36536     pTail->pDirty = pB;
36537   }else{
36538     pTail->pDirty = 0;
36539   }
36540   return result.pDirty;
36541 }
36542
36543 /*
36544 ** Sort the list of pages in accending order by pgno.  Pages are
36545 ** connected by pDirty pointers.  The pDirtyPrev pointers are
36546 ** corrupted by this sort.
36547 **
36548 ** Since there cannot be more than 2^31 distinct pages in a database,
36549 ** there cannot be more than 31 buckets required by the merge sorter.
36550 ** One extra bucket is added to catch overflow in case something
36551 ** ever changes to make the previous sentence incorrect.
36552 */
36553 #define N_SORT_BUCKET  32
36554 static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
36555   PgHdr *a[N_SORT_BUCKET], *p;
36556   int i;
36557   memset(a, 0, sizeof(a));
36558   while( pIn ){
36559     p = pIn;
36560     pIn = p->pDirty;
36561     p->pDirty = 0;
36562     for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
36563       if( a[i]==0 ){
36564         a[i] = p;
36565         break;
36566       }else{
36567         p = pcacheMergeDirtyList(a[i], p);
36568         a[i] = 0;
36569       }
36570     }
36571     if( NEVER(i==N_SORT_BUCKET-1) ){
36572       /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
36573       ** the input list.  But that is impossible.
36574       */
36575       a[i] = pcacheMergeDirtyList(a[i], p);
36576     }
36577   }
36578   p = a[0];
36579   for(i=1; i<N_SORT_BUCKET; i++){
36580     p = pcacheMergeDirtyList(p, a[i]);
36581   }
36582   return p;
36583 }
36584
36585 /*
36586 ** Return a list of all dirty pages in the cache, sorted by page number.
36587 */
36588 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
36589   PgHdr *p;
36590   for(p=pCache->pDirty; p; p=p->pDirtyNext){
36591     p->pDirty = p->pDirtyNext;
36592   }
36593   return pcacheSortDirtyList(pCache->pDirty);
36594 }
36595
36596 /* 
36597 ** Return the total number of referenced pages held by the cache.
36598 */
36599 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
36600   return pCache->nRef;
36601 }
36602
36603 /*
36604 ** Return the number of references to the page supplied as an argument.
36605 */
36606 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
36607   return p->nRef;
36608 }
36609
36610 /* 
36611 ** Return the total number of pages in the cache.
36612 */
36613 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
36614   int nPage = 0;
36615   if( pCache->pCache ){
36616     nPage = sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
36617   }
36618   return nPage;
36619 }
36620
36621 #ifdef SQLITE_TEST
36622 /*
36623 ** Get the suggested cache-size value.
36624 */
36625 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
36626   return numberOfCachePages(pCache);
36627 }
36628 #endif
36629
36630 /*
36631 ** Set the suggested cache-size value.
36632 */
36633 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
36634   pCache->szCache = mxPage;
36635   if( pCache->pCache ){
36636     sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
36637                                            numberOfCachePages(pCache));
36638   }
36639 }
36640
36641 /*
36642 ** Free up as much memory as possible from the page cache.
36643 */
36644 SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
36645   if( pCache->pCache ){
36646     sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
36647   }
36648 }
36649
36650 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
36651 /*
36652 ** For all dirty pages currently in the cache, invoke the specified
36653 ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
36654 ** defined.
36655 */
36656 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
36657   PgHdr *pDirty;
36658   for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
36659     xIter(pDirty);
36660   }
36661 }
36662 #endif
36663
36664 /************** End of pcache.c **********************************************/
36665 /************** Begin file pcache1.c *****************************************/
36666 /*
36667 ** 2008 November 05
36668 **
36669 ** The author disclaims copyright to this source code.  In place of
36670 ** a legal notice, here is a blessing:
36671 **
36672 **    May you do good and not evil.
36673 **    May you find forgiveness for yourself and forgive others.
36674 **    May you share freely, never taking more than you give.
36675 **
36676 *************************************************************************
36677 **
36678 ** This file implements the default page cache implementation (the
36679 ** sqlite3_pcache interface). It also contains part of the implementation
36680 ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
36681 ** If the default page cache implementation is overriden, then neither of
36682 ** these two features are available.
36683 */
36684
36685
36686 typedef struct PCache1 PCache1;
36687 typedef struct PgHdr1 PgHdr1;
36688 typedef struct PgFreeslot PgFreeslot;
36689 typedef struct PGroup PGroup;
36690
36691 /* Each page cache (or PCache) belongs to a PGroup.  A PGroup is a set 
36692 ** of one or more PCaches that are able to recycle each others unpinned
36693 ** pages when they are under memory pressure.  A PGroup is an instance of
36694 ** the following object.
36695 **
36696 ** This page cache implementation works in one of two modes:
36697 **
36698 **   (1)  Every PCache is the sole member of its own PGroup.  There is
36699 **        one PGroup per PCache.
36700 **
36701 **   (2)  There is a single global PGroup that all PCaches are a member
36702 **        of.
36703 **
36704 ** Mode 1 uses more memory (since PCache instances are not able to rob
36705 ** unused pages from other PCaches) but it also operates without a mutex,
36706 ** and is therefore often faster.  Mode 2 requires a mutex in order to be
36707 ** threadsafe, but recycles pages more efficiently.
36708 **
36709 ** For mode (1), PGroup.mutex is NULL.  For mode (2) there is only a single
36710 ** PGroup which is the pcache1.grp global variable and its mutex is
36711 ** SQLITE_MUTEX_STATIC_LRU.
36712 */
36713 struct PGroup {
36714   sqlite3_mutex *mutex;          /* MUTEX_STATIC_LRU or NULL */
36715   unsigned int nMaxPage;         /* Sum of nMax for purgeable caches */
36716   unsigned int nMinPage;         /* Sum of nMin for purgeable caches */
36717   unsigned int mxPinned;         /* nMaxpage + 10 - nMinPage */
36718   unsigned int nCurrentPage;     /* Number of purgeable pages allocated */
36719   PgHdr1 *pLruHead, *pLruTail;   /* LRU list of unpinned pages */
36720 };
36721
36722 /* Each page cache is an instance of the following object.  Every
36723 ** open database file (including each in-memory database and each
36724 ** temporary or transient database) has a single page cache which
36725 ** is an instance of this object.
36726 **
36727 ** Pointers to structures of this type are cast and returned as 
36728 ** opaque sqlite3_pcache* handles.
36729 */
36730 struct PCache1 {
36731   /* Cache configuration parameters. Page size (szPage) and the purgeable
36732   ** flag (bPurgeable) are set when the cache is created. nMax may be 
36733   ** modified at any time by a call to the pcache1Cachesize() method.
36734   ** The PGroup mutex must be held when accessing nMax.
36735   */
36736   PGroup *pGroup;                     /* PGroup this cache belongs to */
36737   int szPage;                         /* Size of allocated pages in bytes */
36738   int szExtra;                        /* Size of extra space in bytes */
36739   int bPurgeable;                     /* True if cache is purgeable */
36740   unsigned int nMin;                  /* Minimum number of pages reserved */
36741   unsigned int nMax;                  /* Configured "cache_size" value */
36742   unsigned int n90pct;                /* nMax*9/10 */
36743   unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
36744
36745   /* Hash table of all pages. The following variables may only be accessed
36746   ** when the accessor is holding the PGroup mutex.
36747   */
36748   unsigned int nRecyclable;           /* Number of pages in the LRU list */
36749   unsigned int nPage;                 /* Total number of pages in apHash */
36750   unsigned int nHash;                 /* Number of slots in apHash[] */
36751   PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
36752 };
36753
36754 /*
36755 ** Each cache entry is represented by an instance of the following 
36756 ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
36757 ** PgHdr1.pCache->szPage bytes is allocated directly before this structure 
36758 ** in memory.
36759 */
36760 struct PgHdr1 {
36761   sqlite3_pcache_page page;
36762   unsigned int iKey;             /* Key value (page number) */
36763   PgHdr1 *pNext;                 /* Next in hash table chain */
36764   PCache1 *pCache;               /* Cache that currently owns this page */
36765   PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
36766   PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
36767 };
36768
36769 /*
36770 ** Free slots in the allocator used to divide up the buffer provided using
36771 ** the SQLITE_CONFIG_PAGECACHE mechanism.
36772 */
36773 struct PgFreeslot {
36774   PgFreeslot *pNext;  /* Next free slot */
36775 };
36776
36777 /*
36778 ** Global data used by this cache.
36779 */
36780 static SQLITE_WSD struct PCacheGlobal {
36781   PGroup grp;                    /* The global PGroup for mode (2) */
36782
36783   /* Variables related to SQLITE_CONFIG_PAGECACHE settings.  The
36784   ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
36785   ** fixed at sqlite3_initialize() time and do not require mutex protection.
36786   ** The nFreeSlot and pFree values do require mutex protection.
36787   */
36788   int isInit;                    /* True if initialized */
36789   int szSlot;                    /* Size of each free slot */
36790   int nSlot;                     /* The number of pcache slots */
36791   int nReserve;                  /* Try to keep nFreeSlot above this */
36792   void *pStart, *pEnd;           /* Bounds of pagecache malloc range */
36793   /* Above requires no mutex.  Use mutex below for variable that follow. */
36794   sqlite3_mutex *mutex;          /* Mutex for accessing the following: */
36795   PgFreeslot *pFree;             /* Free page blocks */
36796   int nFreeSlot;                 /* Number of unused pcache slots */
36797   /* The following value requires a mutex to change.  We skip the mutex on
36798   ** reading because (1) most platforms read a 32-bit integer atomically and
36799   ** (2) even if an incorrect value is read, no great harm is done since this
36800   ** is really just an optimization. */
36801   int bUnderPressure;            /* True if low on PAGECACHE memory */
36802 } pcache1_g;
36803
36804 /*
36805 ** All code in this file should access the global structure above via the
36806 ** alias "pcache1". This ensures that the WSD emulation is used when
36807 ** compiling for systems that do not support real WSD.
36808 */
36809 #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
36810
36811 /*
36812 ** Macros to enter and leave the PCache LRU mutex.
36813 */
36814 #define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
36815 #define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
36816
36817 /******************************************************************************/
36818 /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
36819
36820 /*
36821 ** This function is called during initialization if a static buffer is 
36822 ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
36823 ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
36824 ** enough to contain 'n' buffers of 'sz' bytes each.
36825 **
36826 ** This routine is called from sqlite3_initialize() and so it is guaranteed
36827 ** to be serialized already.  There is no need for further mutexing.
36828 */
36829 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
36830   if( pcache1.isInit ){
36831     PgFreeslot *p;
36832     sz = ROUNDDOWN8(sz);
36833     pcache1.szSlot = sz;
36834     pcache1.nSlot = pcache1.nFreeSlot = n;
36835     pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
36836     pcache1.pStart = pBuf;
36837     pcache1.pFree = 0;
36838     pcache1.bUnderPressure = 0;
36839     while( n-- ){
36840       p = (PgFreeslot*)pBuf;
36841       p->pNext = pcache1.pFree;
36842       pcache1.pFree = p;
36843       pBuf = (void*)&((char*)pBuf)[sz];
36844     }
36845     pcache1.pEnd = pBuf;
36846   }
36847 }
36848
36849 /*
36850 ** Malloc function used within this file to allocate space from the buffer
36851 ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no 
36852 ** such buffer exists or there is no space left in it, this function falls 
36853 ** back to sqlite3Malloc().
36854 **
36855 ** Multiple threads can run this routine at the same time.  Global variables
36856 ** in pcache1 need to be protected via mutex.
36857 */
36858 static void *pcache1Alloc(int nByte){
36859   void *p = 0;
36860   assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
36861   sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
36862   if( nByte<=pcache1.szSlot ){
36863     sqlite3_mutex_enter(pcache1.mutex);
36864     p = (PgHdr1 *)pcache1.pFree;
36865     if( p ){
36866       pcache1.pFree = pcache1.pFree->pNext;
36867       pcache1.nFreeSlot--;
36868       pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
36869       assert( pcache1.nFreeSlot>=0 );
36870       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
36871     }
36872     sqlite3_mutex_leave(pcache1.mutex);
36873   }
36874   if( p==0 ){
36875     /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool.  Get
36876     ** it from sqlite3Malloc instead.
36877     */
36878     p = sqlite3Malloc(nByte);
36879 #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
36880     if( p ){
36881       int sz = sqlite3MallocSize(p);
36882       sqlite3_mutex_enter(pcache1.mutex);
36883       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
36884       sqlite3_mutex_leave(pcache1.mutex);
36885     }
36886 #endif
36887     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
36888   }
36889   return p;
36890 }
36891
36892 /*
36893 ** Free an allocated buffer obtained from pcache1Alloc().
36894 */
36895 static int pcache1Free(void *p){
36896   int nFreed = 0;
36897   if( p==0 ) return 0;
36898   if( p>=pcache1.pStart && p<pcache1.pEnd ){
36899     PgFreeslot *pSlot;
36900     sqlite3_mutex_enter(pcache1.mutex);
36901     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
36902     pSlot = (PgFreeslot*)p;
36903     pSlot->pNext = pcache1.pFree;
36904     pcache1.pFree = pSlot;
36905     pcache1.nFreeSlot++;
36906     pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
36907     assert( pcache1.nFreeSlot<=pcache1.nSlot );
36908     sqlite3_mutex_leave(pcache1.mutex);
36909   }else{
36910     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
36911     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
36912     nFreed = sqlite3MallocSize(p);
36913 #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
36914     sqlite3_mutex_enter(pcache1.mutex);
36915     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -nFreed);
36916     sqlite3_mutex_leave(pcache1.mutex);
36917 #endif
36918     sqlite3_free(p);
36919   }
36920   return nFreed;
36921 }
36922
36923 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
36924 /*
36925 ** Return the size of a pcache allocation
36926 */
36927 static int pcache1MemSize(void *p){
36928   if( p>=pcache1.pStart && p<pcache1.pEnd ){
36929     return pcache1.szSlot;
36930   }else{
36931     int iSize;
36932     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
36933     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
36934     iSize = sqlite3MallocSize(p);
36935     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
36936     return iSize;
36937   }
36938 }
36939 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
36940
36941 /*
36942 ** Allocate a new page object initially associated with cache pCache.
36943 */
36944 static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
36945   PgHdr1 *p = 0;
36946   void *pPg;
36947
36948   /* The group mutex must be released before pcache1Alloc() is called. This
36949   ** is because it may call sqlite3_release_memory(), which assumes that 
36950   ** this mutex is not held. */
36951   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
36952   pcache1LeaveMutex(pCache->pGroup);
36953 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
36954   pPg = pcache1Alloc(pCache->szPage);
36955   p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
36956   if( !pPg || !p ){
36957     pcache1Free(pPg);
36958     sqlite3_free(p);
36959     pPg = 0;
36960   }
36961 #else
36962   pPg = pcache1Alloc(sizeof(PgHdr1) + pCache->szPage + pCache->szExtra);
36963   p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
36964 #endif
36965   pcache1EnterMutex(pCache->pGroup);
36966
36967   if( pPg ){
36968     p->page.pBuf = pPg;
36969     p->page.pExtra = &p[1];
36970     if( pCache->bPurgeable ){
36971       pCache->pGroup->nCurrentPage++;
36972     }
36973     return p;
36974   }
36975   return 0;
36976 }
36977
36978 /*
36979 ** Free a page object allocated by pcache1AllocPage().
36980 **
36981 ** The pointer is allowed to be NULL, which is prudent.  But it turns out
36982 ** that the current implementation happens to never call this routine
36983 ** with a NULL pointer, so we mark the NULL test with ALWAYS().
36984 */
36985 static void pcache1FreePage(PgHdr1 *p){
36986   if( ALWAYS(p) ){
36987     PCache1 *pCache = p->pCache;
36988     assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
36989     pcache1Free(p->page.pBuf);
36990 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
36991     sqlite3_free(p);
36992 #endif
36993     if( pCache->bPurgeable ){
36994       pCache->pGroup->nCurrentPage--;
36995     }
36996   }
36997 }
36998
36999 /*
37000 ** Malloc function used by SQLite to obtain space from the buffer configured
37001 ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
37002 ** exists, this function falls back to sqlite3Malloc().
37003 */
37004 SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
37005   return pcache1Alloc(sz);
37006 }
37007
37008 /*
37009 ** Free an allocated buffer obtained from sqlite3PageMalloc().
37010 */
37011 SQLITE_PRIVATE void sqlite3PageFree(void *p){
37012   pcache1Free(p);
37013 }
37014
37015
37016 /*
37017 ** Return true if it desirable to avoid allocating a new page cache
37018 ** entry.
37019 **
37020 ** If memory was allocated specifically to the page cache using
37021 ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
37022 ** it is desirable to avoid allocating a new page cache entry because
37023 ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
37024 ** for all page cache needs and we should not need to spill the
37025 ** allocation onto the heap.
37026 **
37027 ** Or, the heap is used for all page cache memory but the heap is
37028 ** under memory pressure, then again it is desirable to avoid
37029 ** allocating a new page cache entry in order to avoid stressing
37030 ** the heap even further.
37031 */
37032 static int pcache1UnderMemoryPressure(PCache1 *pCache){
37033   if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
37034     return pcache1.bUnderPressure;
37035   }else{
37036     return sqlite3HeapNearlyFull();
37037   }
37038 }
37039
37040 /******************************************************************************/
37041 /******** General Implementation Functions ************************************/
37042
37043 /*
37044 ** This function is used to resize the hash table used by the cache passed
37045 ** as the first argument.
37046 **
37047 ** The PCache mutex must be held when this function is called.
37048 */
37049 static int pcache1ResizeHash(PCache1 *p){
37050   PgHdr1 **apNew;
37051   unsigned int nNew;
37052   unsigned int i;
37053
37054   assert( sqlite3_mutex_held(p->pGroup->mutex) );
37055
37056   nNew = p->nHash*2;
37057   if( nNew<256 ){
37058     nNew = 256;
37059   }
37060
37061   pcache1LeaveMutex(p->pGroup);
37062   if( p->nHash ){ sqlite3BeginBenignMalloc(); }
37063   apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
37064   if( p->nHash ){ sqlite3EndBenignMalloc(); }
37065   pcache1EnterMutex(p->pGroup);
37066   if( apNew ){
37067     for(i=0; i<p->nHash; i++){
37068       PgHdr1 *pPage;
37069       PgHdr1 *pNext = p->apHash[i];
37070       while( (pPage = pNext)!=0 ){
37071         unsigned int h = pPage->iKey % nNew;
37072         pNext = pPage->pNext;
37073         pPage->pNext = apNew[h];
37074         apNew[h] = pPage;
37075       }
37076     }
37077     sqlite3_free(p->apHash);
37078     p->apHash = apNew;
37079     p->nHash = nNew;
37080   }
37081
37082   return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
37083 }
37084
37085 /*
37086 ** This function is used internally to remove the page pPage from the 
37087 ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
37088 ** LRU list, then this function is a no-op.
37089 **
37090 ** The PGroup mutex must be held when this function is called.
37091 **
37092 ** If pPage is NULL then this routine is a no-op.
37093 */
37094 static void pcache1PinPage(PgHdr1 *pPage){
37095   PCache1 *pCache;
37096   PGroup *pGroup;
37097
37098   if( pPage==0 ) return;
37099   pCache = pPage->pCache;
37100   pGroup = pCache->pGroup;
37101   assert( sqlite3_mutex_held(pGroup->mutex) );
37102   if( pPage->pLruNext || pPage==pGroup->pLruTail ){
37103     if( pPage->pLruPrev ){
37104       pPage->pLruPrev->pLruNext = pPage->pLruNext;
37105     }
37106     if( pPage->pLruNext ){
37107       pPage->pLruNext->pLruPrev = pPage->pLruPrev;
37108     }
37109     if( pGroup->pLruHead==pPage ){
37110       pGroup->pLruHead = pPage->pLruNext;
37111     }
37112     if( pGroup->pLruTail==pPage ){
37113       pGroup->pLruTail = pPage->pLruPrev;
37114     }
37115     pPage->pLruNext = 0;
37116     pPage->pLruPrev = 0;
37117     pPage->pCache->nRecyclable--;
37118   }
37119 }
37120
37121
37122 /*
37123 ** Remove the page supplied as an argument from the hash table 
37124 ** (PCache1.apHash structure) that it is currently stored in.
37125 **
37126 ** The PGroup mutex must be held when this function is called.
37127 */
37128 static void pcache1RemoveFromHash(PgHdr1 *pPage){
37129   unsigned int h;
37130   PCache1 *pCache = pPage->pCache;
37131   PgHdr1 **pp;
37132
37133   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
37134   h = pPage->iKey % pCache->nHash;
37135   for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
37136   *pp = (*pp)->pNext;
37137
37138   pCache->nPage--;
37139 }
37140
37141 /*
37142 ** If there are currently more than nMaxPage pages allocated, try
37143 ** to recycle pages to reduce the number allocated to nMaxPage.
37144 */
37145 static void pcache1EnforceMaxPage(PGroup *pGroup){
37146   assert( sqlite3_mutex_held(pGroup->mutex) );
37147   while( pGroup->nCurrentPage>pGroup->nMaxPage && pGroup->pLruTail ){
37148     PgHdr1 *p = pGroup->pLruTail;
37149     assert( p->pCache->pGroup==pGroup );
37150     pcache1PinPage(p);
37151     pcache1RemoveFromHash(p);
37152     pcache1FreePage(p);
37153   }
37154 }
37155
37156 /*
37157 ** Discard all pages from cache pCache with a page number (key value) 
37158 ** greater than or equal to iLimit. Any pinned pages that meet this 
37159 ** criteria are unpinned before they are discarded.
37160 **
37161 ** The PCache mutex must be held when this function is called.
37162 */
37163 static void pcache1TruncateUnsafe(
37164   PCache1 *pCache,             /* The cache to truncate */
37165   unsigned int iLimit          /* Drop pages with this pgno or larger */
37166 ){
37167   TESTONLY( unsigned int nPage = 0; )  /* To assert pCache->nPage is correct */
37168   unsigned int h;
37169   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
37170   for(h=0; h<pCache->nHash; h++){
37171     PgHdr1 **pp = &pCache->apHash[h]; 
37172     PgHdr1 *pPage;
37173     while( (pPage = *pp)!=0 ){
37174       if( pPage->iKey>=iLimit ){
37175         pCache->nPage--;
37176         *pp = pPage->pNext;
37177         pcache1PinPage(pPage);
37178         pcache1FreePage(pPage);
37179       }else{
37180         pp = &pPage->pNext;
37181         TESTONLY( nPage++; )
37182       }
37183     }
37184   }
37185   assert( pCache->nPage==nPage );
37186 }
37187
37188 /******************************************************************************/
37189 /******** sqlite3_pcache Methods **********************************************/
37190
37191 /*
37192 ** Implementation of the sqlite3_pcache.xInit method.
37193 */
37194 static int pcache1Init(void *NotUsed){
37195   UNUSED_PARAMETER(NotUsed);
37196   assert( pcache1.isInit==0 );
37197   memset(&pcache1, 0, sizeof(pcache1));
37198   if( sqlite3GlobalConfig.bCoreMutex ){
37199     pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
37200     pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
37201   }
37202   pcache1.grp.mxPinned = 10;
37203   pcache1.isInit = 1;
37204   return SQLITE_OK;
37205 }
37206
37207 /*
37208 ** Implementation of the sqlite3_pcache.xShutdown method.
37209 ** Note that the static mutex allocated in xInit does 
37210 ** not need to be freed.
37211 */
37212 static void pcache1Shutdown(void *NotUsed){
37213   UNUSED_PARAMETER(NotUsed);
37214   assert( pcache1.isInit!=0 );
37215   memset(&pcache1, 0, sizeof(pcache1));
37216 }
37217
37218 /*
37219 ** Implementation of the sqlite3_pcache.xCreate method.
37220 **
37221 ** Allocate a new cache.
37222 */
37223 static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
37224   PCache1 *pCache;      /* The newly created page cache */
37225   PGroup *pGroup;       /* The group the new page cache will belong to */
37226   int sz;               /* Bytes of memory required to allocate the new cache */
37227
37228   /*
37229   ** The seperateCache variable is true if each PCache has its own private
37230   ** PGroup.  In other words, separateCache is true for mode (1) where no
37231   ** mutexing is required.
37232   **
37233   **   *  Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
37234   **
37235   **   *  Always use a unified cache in single-threaded applications
37236   **
37237   **   *  Otherwise (if multi-threaded and ENABLE_MEMORY_MANAGEMENT is off)
37238   **      use separate caches (mode-1)
37239   */
37240 #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
37241   const int separateCache = 0;
37242 #else
37243   int separateCache = sqlite3GlobalConfig.bCoreMutex>0;
37244 #endif
37245
37246   assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
37247   assert( szExtra < 300 );
37248
37249   sz = sizeof(PCache1) + sizeof(PGroup)*separateCache;
37250   pCache = (PCache1 *)sqlite3MallocZero(sz);
37251   if( pCache ){
37252     if( separateCache ){
37253       pGroup = (PGroup*)&pCache[1];
37254       pGroup->mxPinned = 10;
37255     }else{
37256       pGroup = &pcache1.grp;
37257     }
37258     pCache->pGroup = pGroup;
37259     pCache->szPage = szPage;
37260     pCache->szExtra = szExtra;
37261     pCache->bPurgeable = (bPurgeable ? 1 : 0);
37262     if( bPurgeable ){
37263       pCache->nMin = 10;
37264       pcache1EnterMutex(pGroup);
37265       pGroup->nMinPage += pCache->nMin;
37266       pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
37267       pcache1LeaveMutex(pGroup);
37268     }
37269   }
37270   return (sqlite3_pcache *)pCache;
37271 }
37272
37273 /*
37274 ** Implementation of the sqlite3_pcache.xCachesize method. 
37275 **
37276 ** Configure the cache_size limit for a cache.
37277 */
37278 static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
37279   PCache1 *pCache = (PCache1 *)p;
37280   if( pCache->bPurgeable ){
37281     PGroup *pGroup = pCache->pGroup;
37282     pcache1EnterMutex(pGroup);
37283     pGroup->nMaxPage += (nMax - pCache->nMax);
37284     pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
37285     pCache->nMax = nMax;
37286     pCache->n90pct = pCache->nMax*9/10;
37287     pcache1EnforceMaxPage(pGroup);
37288     pcache1LeaveMutex(pGroup);
37289   }
37290 }
37291
37292 /*
37293 ** Implementation of the sqlite3_pcache.xShrink method. 
37294 **
37295 ** Free up as much memory as possible.
37296 */
37297 static void pcache1Shrink(sqlite3_pcache *p){
37298   PCache1 *pCache = (PCache1*)p;
37299   if( pCache->bPurgeable ){
37300     PGroup *pGroup = pCache->pGroup;
37301     int savedMaxPage;
37302     pcache1EnterMutex(pGroup);
37303     savedMaxPage = pGroup->nMaxPage;
37304     pGroup->nMaxPage = 0;
37305     pcache1EnforceMaxPage(pGroup);
37306     pGroup->nMaxPage = savedMaxPage;
37307     pcache1LeaveMutex(pGroup);
37308   }
37309 }
37310
37311 /*
37312 ** Implementation of the sqlite3_pcache.xPagecount method. 
37313 */
37314 static int pcache1Pagecount(sqlite3_pcache *p){
37315   int n;
37316   PCache1 *pCache = (PCache1*)p;
37317   pcache1EnterMutex(pCache->pGroup);
37318   n = pCache->nPage;
37319   pcache1LeaveMutex(pCache->pGroup);
37320   return n;
37321 }
37322
37323 /*
37324 ** Implementation of the sqlite3_pcache.xFetch method. 
37325 **
37326 ** Fetch a page by key value.
37327 **
37328 ** Whether or not a new page may be allocated by this function depends on
37329 ** the value of the createFlag argument.  0 means do not allocate a new
37330 ** page.  1 means allocate a new page if space is easily available.  2 
37331 ** means to try really hard to allocate a new page.
37332 **
37333 ** For a non-purgeable cache (a cache used as the storage for an in-memory
37334 ** database) there is really no difference between createFlag 1 and 2.  So
37335 ** the calling function (pcache.c) will never have a createFlag of 1 on
37336 ** a non-purgeable cache.
37337 **
37338 ** There are three different approaches to obtaining space for a page,
37339 ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
37340 **
37341 **   1. Regardless of the value of createFlag, the cache is searched for a 
37342 **      copy of the requested page. If one is found, it is returned.
37343 **
37344 **   2. If createFlag==0 and the page is not already in the cache, NULL is
37345 **      returned.
37346 **
37347 **   3. If createFlag is 1, and the page is not already in the cache, then
37348 **      return NULL (do not allocate a new page) if any of the following
37349 **      conditions are true:
37350 **
37351 **       (a) the number of pages pinned by the cache is greater than
37352 **           PCache1.nMax, or
37353 **
37354 **       (b) the number of pages pinned by the cache is greater than
37355 **           the sum of nMax for all purgeable caches, less the sum of 
37356 **           nMin for all other purgeable caches, or
37357 **
37358 **   4. If none of the first three conditions apply and the cache is marked
37359 **      as purgeable, and if one of the following is true:
37360 **
37361 **       (a) The number of pages allocated for the cache is already 
37362 **           PCache1.nMax, or
37363 **
37364 **       (b) The number of pages allocated for all purgeable caches is
37365 **           already equal to or greater than the sum of nMax for all
37366 **           purgeable caches,
37367 **
37368 **       (c) The system is under memory pressure and wants to avoid
37369 **           unnecessary pages cache entry allocations
37370 **
37371 **      then attempt to recycle a page from the LRU list. If it is the right
37372 **      size, return the recycled buffer. Otherwise, free the buffer and
37373 **      proceed to step 5. 
37374 **
37375 **   5. Otherwise, allocate and return a new page buffer.
37376 */
37377 static sqlite3_pcache_page *pcache1Fetch(
37378   sqlite3_pcache *p, 
37379   unsigned int iKey, 
37380   int createFlag
37381 ){
37382   unsigned int nPinned;
37383   PCache1 *pCache = (PCache1 *)p;
37384   PGroup *pGroup;
37385   PgHdr1 *pPage = 0;
37386
37387   assert( pCache->bPurgeable || createFlag!=1 );
37388   assert( pCache->bPurgeable || pCache->nMin==0 );
37389   assert( pCache->bPurgeable==0 || pCache->nMin==10 );
37390   assert( pCache->nMin==0 || pCache->bPurgeable );
37391   pcache1EnterMutex(pGroup = pCache->pGroup);
37392
37393   /* Step 1: Search the hash table for an existing entry. */
37394   if( pCache->nHash>0 ){
37395     unsigned int h = iKey % pCache->nHash;
37396     for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
37397   }
37398
37399   /* Step 2: Abort if no existing page is found and createFlag is 0 */
37400   if( pPage || createFlag==0 ){
37401     pcache1PinPage(pPage);
37402     goto fetch_out;
37403   }
37404
37405   /* The pGroup local variable will normally be initialized by the
37406   ** pcache1EnterMutex() macro above.  But if SQLITE_MUTEX_OMIT is defined,
37407   ** then pcache1EnterMutex() is a no-op, so we have to initialize the
37408   ** local variable here.  Delaying the initialization of pGroup is an
37409   ** optimization:  The common case is to exit the module before reaching
37410   ** this point.
37411   */
37412 #ifdef SQLITE_MUTEX_OMIT
37413   pGroup = pCache->pGroup;
37414 #endif
37415
37416   /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
37417   assert( pCache->nPage >= pCache->nRecyclable );
37418   nPinned = pCache->nPage - pCache->nRecyclable;
37419   assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
37420   assert( pCache->n90pct == pCache->nMax*9/10 );
37421   if( createFlag==1 && (
37422         nPinned>=pGroup->mxPinned
37423      || nPinned>=pCache->n90pct
37424      || pcache1UnderMemoryPressure(pCache)
37425   )){
37426     goto fetch_out;
37427   }
37428
37429   if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
37430     goto fetch_out;
37431   }
37432
37433   /* Step 4. Try to recycle a page. */
37434   if( pCache->bPurgeable && pGroup->pLruTail && (
37435          (pCache->nPage+1>=pCache->nMax)
37436       || pGroup->nCurrentPage>=pGroup->nMaxPage
37437       || pcache1UnderMemoryPressure(pCache)
37438   )){
37439     PCache1 *pOther;
37440     pPage = pGroup->pLruTail;
37441     pcache1RemoveFromHash(pPage);
37442     pcache1PinPage(pPage);
37443     pOther = pPage->pCache;
37444
37445     /* We want to verify that szPage and szExtra are the same for pOther
37446     ** and pCache.  Assert that we can verify this by comparing sums. */
37447     assert( (pCache->szPage & (pCache->szPage-1))==0 && pCache->szPage>=512 );
37448     assert( pCache->szExtra<512 );
37449     assert( (pOther->szPage & (pOther->szPage-1))==0 && pOther->szPage>=512 );
37450     assert( pOther->szExtra<512 );
37451
37452     if( pOther->szPage+pOther->szExtra != pCache->szPage+pCache->szExtra ){
37453       pcache1FreePage(pPage);
37454       pPage = 0;
37455     }else{
37456       pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
37457     }
37458   }
37459
37460   /* Step 5. If a usable page buffer has still not been found, 
37461   ** attempt to allocate a new one. 
37462   */
37463   if( !pPage ){
37464     if( createFlag==1 ) sqlite3BeginBenignMalloc();
37465     pPage = pcache1AllocPage(pCache);
37466     if( createFlag==1 ) sqlite3EndBenignMalloc();
37467   }
37468
37469   if( pPage ){
37470     unsigned int h = iKey % pCache->nHash;
37471     pCache->nPage++;
37472     pPage->iKey = iKey;
37473     pPage->pNext = pCache->apHash[h];
37474     pPage->pCache = pCache;
37475     pPage->pLruPrev = 0;
37476     pPage->pLruNext = 0;
37477     *(void **)pPage->page.pExtra = 0;
37478     pCache->apHash[h] = pPage;
37479   }
37480
37481 fetch_out:
37482   if( pPage && iKey>pCache->iMaxKey ){
37483     pCache->iMaxKey = iKey;
37484   }
37485   pcache1LeaveMutex(pGroup);
37486   return &pPage->page;
37487 }
37488
37489
37490 /*
37491 ** Implementation of the sqlite3_pcache.xUnpin method.
37492 **
37493 ** Mark a page as unpinned (eligible for asynchronous recycling).
37494 */
37495 static void pcache1Unpin(
37496   sqlite3_pcache *p, 
37497   sqlite3_pcache_page *pPg, 
37498   int reuseUnlikely
37499 ){
37500   PCache1 *pCache = (PCache1 *)p;
37501   PgHdr1 *pPage = (PgHdr1 *)pPg;
37502   PGroup *pGroup = pCache->pGroup;
37503  
37504   assert( pPage->pCache==pCache );
37505   pcache1EnterMutex(pGroup);
37506
37507   /* It is an error to call this function if the page is already 
37508   ** part of the PGroup LRU list.
37509   */
37510   assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
37511   assert( pGroup->pLruHead!=pPage && pGroup->pLruTail!=pPage );
37512
37513   if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
37514     pcache1RemoveFromHash(pPage);
37515     pcache1FreePage(pPage);
37516   }else{
37517     /* Add the page to the PGroup LRU list. */
37518     if( pGroup->pLruHead ){
37519       pGroup->pLruHead->pLruPrev = pPage;
37520       pPage->pLruNext = pGroup->pLruHead;
37521       pGroup->pLruHead = pPage;
37522     }else{
37523       pGroup->pLruTail = pPage;
37524       pGroup->pLruHead = pPage;
37525     }
37526     pCache->nRecyclable++;
37527   }
37528
37529   pcache1LeaveMutex(pCache->pGroup);
37530 }
37531
37532 /*
37533 ** Implementation of the sqlite3_pcache.xRekey method. 
37534 */
37535 static void pcache1Rekey(
37536   sqlite3_pcache *p,
37537   sqlite3_pcache_page *pPg,
37538   unsigned int iOld,
37539   unsigned int iNew
37540 ){
37541   PCache1 *pCache = (PCache1 *)p;
37542   PgHdr1 *pPage = (PgHdr1 *)pPg;
37543   PgHdr1 **pp;
37544   unsigned int h; 
37545   assert( pPage->iKey==iOld );
37546   assert( pPage->pCache==pCache );
37547
37548   pcache1EnterMutex(pCache->pGroup);
37549
37550   h = iOld%pCache->nHash;
37551   pp = &pCache->apHash[h];
37552   while( (*pp)!=pPage ){
37553     pp = &(*pp)->pNext;
37554   }
37555   *pp = pPage->pNext;
37556
37557   h = iNew%pCache->nHash;
37558   pPage->iKey = iNew;
37559   pPage->pNext = pCache->apHash[h];
37560   pCache->apHash[h] = pPage;
37561   if( iNew>pCache->iMaxKey ){
37562     pCache->iMaxKey = iNew;
37563   }
37564
37565   pcache1LeaveMutex(pCache->pGroup);
37566 }
37567
37568 /*
37569 ** Implementation of the sqlite3_pcache.xTruncate method. 
37570 **
37571 ** Discard all unpinned pages in the cache with a page number equal to
37572 ** or greater than parameter iLimit. Any pinned pages with a page number
37573 ** equal to or greater than iLimit are implicitly unpinned.
37574 */
37575 static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
37576   PCache1 *pCache = (PCache1 *)p;
37577   pcache1EnterMutex(pCache->pGroup);
37578   if( iLimit<=pCache->iMaxKey ){
37579     pcache1TruncateUnsafe(pCache, iLimit);
37580     pCache->iMaxKey = iLimit-1;
37581   }
37582   pcache1LeaveMutex(pCache->pGroup);
37583 }
37584
37585 /*
37586 ** Implementation of the sqlite3_pcache.xDestroy method. 
37587 **
37588 ** Destroy a cache allocated using pcache1Create().
37589 */
37590 static void pcache1Destroy(sqlite3_pcache *p){
37591   PCache1 *pCache = (PCache1 *)p;
37592   PGroup *pGroup = pCache->pGroup;
37593   assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
37594   pcache1EnterMutex(pGroup);
37595   pcache1TruncateUnsafe(pCache, 0);
37596   assert( pGroup->nMaxPage >= pCache->nMax );
37597   pGroup->nMaxPage -= pCache->nMax;
37598   assert( pGroup->nMinPage >= pCache->nMin );
37599   pGroup->nMinPage -= pCache->nMin;
37600   pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
37601   pcache1EnforceMaxPage(pGroup);
37602   pcache1LeaveMutex(pGroup);
37603   sqlite3_free(pCache->apHash);
37604   sqlite3_free(pCache);
37605 }
37606
37607 /*
37608 ** This function is called during initialization (sqlite3_initialize()) to
37609 ** install the default pluggable cache module, assuming the user has not
37610 ** already provided an alternative.
37611 */
37612 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
37613   static const sqlite3_pcache_methods2 defaultMethods = {
37614     1,                       /* iVersion */
37615     0,                       /* pArg */
37616     pcache1Init,             /* xInit */
37617     pcache1Shutdown,         /* xShutdown */
37618     pcache1Create,           /* xCreate */
37619     pcache1Cachesize,        /* xCachesize */
37620     pcache1Pagecount,        /* xPagecount */
37621     pcache1Fetch,            /* xFetch */
37622     pcache1Unpin,            /* xUnpin */
37623     pcache1Rekey,            /* xRekey */
37624     pcache1Truncate,         /* xTruncate */
37625     pcache1Destroy,          /* xDestroy */
37626     pcache1Shrink            /* xShrink */
37627   };
37628   sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
37629 }
37630
37631 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
37632 /*
37633 ** This function is called to free superfluous dynamically allocated memory
37634 ** held by the pager system. Memory in use by any SQLite pager allocated
37635 ** by the current thread may be sqlite3_free()ed.
37636 **
37637 ** nReq is the number of bytes of memory required. Once this much has
37638 ** been released, the function returns. The return value is the total number 
37639 ** of bytes of memory released.
37640 */
37641 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
37642   int nFree = 0;
37643   assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
37644   assert( sqlite3_mutex_notheld(pcache1.mutex) );
37645   if( pcache1.pStart==0 ){
37646     PgHdr1 *p;
37647     pcache1EnterMutex(&pcache1.grp);
37648     while( (nReq<0 || nFree<nReq) && ((p=pcache1.grp.pLruTail)!=0) ){
37649       nFree += pcache1MemSize(p->page.pBuf);
37650 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
37651       nFree += sqlite3MemSize(p);
37652 #endif
37653       pcache1PinPage(p);
37654       pcache1RemoveFromHash(p);
37655       pcache1FreePage(p);
37656     }
37657     pcache1LeaveMutex(&pcache1.grp);
37658   }
37659   return nFree;
37660 }
37661 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
37662
37663 #ifdef SQLITE_TEST
37664 /*
37665 ** This function is used by test procedures to inspect the internal state
37666 ** of the global cache.
37667 */
37668 SQLITE_PRIVATE void sqlite3PcacheStats(
37669   int *pnCurrent,      /* OUT: Total number of pages cached */
37670   int *pnMax,          /* OUT: Global maximum cache size */
37671   int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
37672   int *pnRecyclable    /* OUT: Total number of pages available for recycling */
37673 ){
37674   PgHdr1 *p;
37675   int nRecyclable = 0;
37676   for(p=pcache1.grp.pLruHead; p; p=p->pLruNext){
37677     nRecyclable++;
37678   }
37679   *pnCurrent = pcache1.grp.nCurrentPage;
37680   *pnMax = (int)pcache1.grp.nMaxPage;
37681   *pnMin = (int)pcache1.grp.nMinPage;
37682   *pnRecyclable = nRecyclable;
37683 }
37684 #endif
37685
37686 /************** End of pcache1.c *********************************************/
37687 /************** Begin file rowset.c ******************************************/
37688 /*
37689 ** 2008 December 3
37690 **
37691 ** The author disclaims copyright to this source code.  In place of
37692 ** a legal notice, here is a blessing:
37693 **
37694 **    May you do good and not evil.
37695 **    May you find forgiveness for yourself and forgive others.
37696 **    May you share freely, never taking more than you give.
37697 **
37698 *************************************************************************
37699 **
37700 ** This module implements an object we call a "RowSet".
37701 **
37702 ** The RowSet object is a collection of rowids.  Rowids
37703 ** are inserted into the RowSet in an arbitrary order.  Inserts
37704 ** can be intermixed with tests to see if a given rowid has been
37705 ** previously inserted into the RowSet.
37706 **
37707 ** After all inserts are finished, it is possible to extract the
37708 ** elements of the RowSet in sorted order.  Once this extraction
37709 ** process has started, no new elements may be inserted.
37710 **
37711 ** Hence, the primitive operations for a RowSet are:
37712 **
37713 **    CREATE
37714 **    INSERT
37715 **    TEST
37716 **    SMALLEST
37717 **    DESTROY
37718 **
37719 ** The CREATE and DESTROY primitives are the constructor and destructor,
37720 ** obviously.  The INSERT primitive adds a new element to the RowSet.
37721 ** TEST checks to see if an element is already in the RowSet.  SMALLEST
37722 ** extracts the least value from the RowSet.
37723 **
37724 ** The INSERT primitive might allocate additional memory.  Memory is
37725 ** allocated in chunks so most INSERTs do no allocation.  There is an 
37726 ** upper bound on the size of allocated memory.  No memory is freed
37727 ** until DESTROY.
37728 **
37729 ** The TEST primitive includes a "batch" number.  The TEST primitive
37730 ** will only see elements that were inserted before the last change
37731 ** in the batch number.  In other words, if an INSERT occurs between
37732 ** two TESTs where the TESTs have the same batch nubmer, then the
37733 ** value added by the INSERT will not be visible to the second TEST.
37734 ** The initial batch number is zero, so if the very first TEST contains
37735 ** a non-zero batch number, it will see all prior INSERTs.
37736 **
37737 ** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
37738 ** that is attempted.
37739 **
37740 ** The cost of an INSERT is roughly constant.  (Sometime new memory
37741 ** has to be allocated on an INSERT.)  The cost of a TEST with a new
37742 ** batch number is O(NlogN) where N is the number of elements in the RowSet.
37743 ** The cost of a TEST using the same batch number is O(logN).  The cost
37744 ** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
37745 ** primitives are constant time.  The cost of DESTROY is O(N).
37746 **
37747 ** There is an added cost of O(N) when switching between TEST and
37748 ** SMALLEST primitives.
37749 */
37750
37751
37752 /*
37753 ** Target size for allocation chunks.
37754 */
37755 #define ROWSET_ALLOCATION_SIZE 1024
37756
37757 /*
37758 ** The number of rowset entries per allocation chunk.
37759 */
37760 #define ROWSET_ENTRY_PER_CHUNK  \
37761                        ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
37762
37763 /*
37764 ** Each entry in a RowSet is an instance of the following object.
37765 **
37766 ** This same object is reused to store a linked list of trees of RowSetEntry
37767 ** objects.  In that alternative use, pRight points to the next entry
37768 ** in the list, pLeft points to the tree, and v is unused.  The
37769 ** RowSet.pForest value points to the head of this forest list.
37770 */
37771 struct RowSetEntry {            
37772   i64 v;                        /* ROWID value for this entry */
37773   struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
37774   struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
37775 };
37776
37777 /*
37778 ** RowSetEntry objects are allocated in large chunks (instances of the
37779 ** following structure) to reduce memory allocation overhead.  The
37780 ** chunks are kept on a linked list so that they can be deallocated
37781 ** when the RowSet is destroyed.
37782 */
37783 struct RowSetChunk {
37784   struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
37785   struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
37786 };
37787
37788 /*
37789 ** A RowSet in an instance of the following structure.
37790 **
37791 ** A typedef of this structure if found in sqliteInt.h.
37792 */
37793 struct RowSet {
37794   struct RowSetChunk *pChunk;    /* List of all chunk allocations */
37795   sqlite3 *db;                   /* The database connection */
37796   struct RowSetEntry *pEntry;    /* List of entries using pRight */
37797   struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
37798   struct RowSetEntry *pFresh;    /* Source of new entry objects */
37799   struct RowSetEntry *pForest;   /* List of binary trees of entries */
37800   u16 nFresh;                    /* Number of objects on pFresh */
37801   u8 rsFlags;                    /* Various flags */
37802   u8 iBatch;                     /* Current insert batch */
37803 };
37804
37805 /*
37806 ** Allowed values for RowSet.rsFlags
37807 */
37808 #define ROWSET_SORTED  0x01   /* True if RowSet.pEntry is sorted */
37809 #define ROWSET_NEXT    0x02   /* True if sqlite3RowSetNext() has been called */
37810
37811 /*
37812 ** Turn bulk memory into a RowSet object.  N bytes of memory
37813 ** are available at pSpace.  The db pointer is used as a memory context
37814 ** for any subsequent allocations that need to occur.
37815 ** Return a pointer to the new RowSet object.
37816 **
37817 ** It must be the case that N is sufficient to make a Rowset.  If not
37818 ** an assertion fault occurs.
37819 ** 
37820 ** If N is larger than the minimum, use the surplus as an initial
37821 ** allocation of entries available to be filled.
37822 */
37823 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
37824   RowSet *p;
37825   assert( N >= ROUND8(sizeof(*p)) );
37826   p = pSpace;
37827   p->pChunk = 0;
37828   p->db = db;
37829   p->pEntry = 0;
37830   p->pLast = 0;
37831   p->pForest = 0;
37832   p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
37833   p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
37834   p->rsFlags = ROWSET_SORTED;
37835   p->iBatch = 0;
37836   return p;
37837 }
37838
37839 /*
37840 ** Deallocate all chunks from a RowSet.  This frees all memory that
37841 ** the RowSet has allocated over its lifetime.  This routine is
37842 ** the destructor for the RowSet.
37843 */
37844 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
37845   struct RowSetChunk *pChunk, *pNextChunk;
37846   for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
37847     pNextChunk = pChunk->pNextChunk;
37848     sqlite3DbFree(p->db, pChunk);
37849   }
37850   p->pChunk = 0;
37851   p->nFresh = 0;
37852   p->pEntry = 0;
37853   p->pLast = 0;
37854   p->pForest = 0;
37855   p->rsFlags = ROWSET_SORTED;
37856 }
37857
37858 /*
37859 ** Allocate a new RowSetEntry object that is associated with the
37860 ** given RowSet.  Return a pointer to the new and completely uninitialized
37861 ** objected.
37862 **
37863 ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
37864 ** routine returns NULL.
37865 */
37866 static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
37867   assert( p!=0 );
37868   if( p->nFresh==0 ){
37869     struct RowSetChunk *pNew;
37870     pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
37871     if( pNew==0 ){
37872       return 0;
37873     }
37874     pNew->pNextChunk = p->pChunk;
37875     p->pChunk = pNew;
37876     p->pFresh = pNew->aEntry;
37877     p->nFresh = ROWSET_ENTRY_PER_CHUNK;
37878   }
37879   p->nFresh--;
37880   return p->pFresh++;
37881 }
37882
37883 /*
37884 ** Insert a new value into a RowSet.
37885 **
37886 ** The mallocFailed flag of the database connection is set if a
37887 ** memory allocation fails.
37888 */
37889 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
37890   struct RowSetEntry *pEntry;  /* The new entry */
37891   struct RowSetEntry *pLast;   /* The last prior entry */
37892
37893   /* This routine is never called after sqlite3RowSetNext() */
37894   assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
37895
37896   pEntry = rowSetEntryAlloc(p);
37897   if( pEntry==0 ) return;
37898   pEntry->v = rowid;
37899   pEntry->pRight = 0;
37900   pLast = p->pLast;
37901   if( pLast ){
37902     if( (p->rsFlags & ROWSET_SORTED)!=0 && rowid<=pLast->v ){
37903       p->rsFlags &= ~ROWSET_SORTED;
37904     }
37905     pLast->pRight = pEntry;
37906   }else{
37907     p->pEntry = pEntry;
37908   }
37909   p->pLast = pEntry;
37910 }
37911
37912 /*
37913 ** Merge two lists of RowSetEntry objects.  Remove duplicates.
37914 **
37915 ** The input lists are connected via pRight pointers and are 
37916 ** assumed to each already be in sorted order.
37917 */
37918 static struct RowSetEntry *rowSetEntryMerge(
37919   struct RowSetEntry *pA,    /* First sorted list to be merged */
37920   struct RowSetEntry *pB     /* Second sorted list to be merged */
37921 ){
37922   struct RowSetEntry head;
37923   struct RowSetEntry *pTail;
37924
37925   pTail = &head;
37926   while( pA && pB ){
37927     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
37928     assert( pB->pRight==0 || pB->v<=pB->pRight->v );
37929     if( pA->v<pB->v ){
37930       pTail->pRight = pA;
37931       pA = pA->pRight;
37932       pTail = pTail->pRight;
37933     }else if( pB->v<pA->v ){
37934       pTail->pRight = pB;
37935       pB = pB->pRight;
37936       pTail = pTail->pRight;
37937     }else{
37938       pA = pA->pRight;
37939     }
37940   }
37941   if( pA ){
37942     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
37943     pTail->pRight = pA;
37944   }else{
37945     assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
37946     pTail->pRight = pB;
37947   }
37948   return head.pRight;
37949 }
37950
37951 /*
37952 ** Sort all elements on the list of RowSetEntry objects into order of
37953 ** increasing v.
37954 */ 
37955 static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
37956   unsigned int i;
37957   struct RowSetEntry *pNext, *aBucket[40];
37958
37959   memset(aBucket, 0, sizeof(aBucket));
37960   while( pIn ){
37961     pNext = pIn->pRight;
37962     pIn->pRight = 0;
37963     for(i=0; aBucket[i]; i++){
37964       pIn = rowSetEntryMerge(aBucket[i], pIn);
37965       aBucket[i] = 0;
37966     }
37967     aBucket[i] = pIn;
37968     pIn = pNext;
37969   }
37970   pIn = 0;
37971   for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
37972     pIn = rowSetEntryMerge(pIn, aBucket[i]);
37973   }
37974   return pIn;
37975 }
37976
37977
37978 /*
37979 ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
37980 ** Convert this tree into a linked list connected by the pRight pointers
37981 ** and return pointers to the first and last elements of the new list.
37982 */
37983 static void rowSetTreeToList(
37984   struct RowSetEntry *pIn,         /* Root of the input tree */
37985   struct RowSetEntry **ppFirst,    /* Write head of the output list here */
37986   struct RowSetEntry **ppLast      /* Write tail of the output list here */
37987 ){
37988   assert( pIn!=0 );
37989   if( pIn->pLeft ){
37990     struct RowSetEntry *p;
37991     rowSetTreeToList(pIn->pLeft, ppFirst, &p);
37992     p->pRight = pIn;
37993   }else{
37994     *ppFirst = pIn;
37995   }
37996   if( pIn->pRight ){
37997     rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
37998   }else{
37999     *ppLast = pIn;
38000   }
38001   assert( (*ppLast)->pRight==0 );
38002 }
38003
38004
38005 /*
38006 ** Convert a sorted list of elements (connected by pRight) into a binary
38007 ** tree with depth of iDepth.  A depth of 1 means the tree contains a single
38008 ** node taken from the head of *ppList.  A depth of 2 means a tree with
38009 ** three nodes.  And so forth.
38010 **
38011 ** Use as many entries from the input list as required and update the
38012 ** *ppList to point to the unused elements of the list.  If the input
38013 ** list contains too few elements, then construct an incomplete tree
38014 ** and leave *ppList set to NULL.
38015 **
38016 ** Return a pointer to the root of the constructed binary tree.
38017 */
38018 static struct RowSetEntry *rowSetNDeepTree(
38019   struct RowSetEntry **ppList,
38020   int iDepth
38021 ){
38022   struct RowSetEntry *p;         /* Root of the new tree */
38023   struct RowSetEntry *pLeft;     /* Left subtree */
38024   if( *ppList==0 ){
38025     return 0;
38026   }
38027   if( iDepth==1 ){
38028     p = *ppList;
38029     *ppList = p->pRight;
38030     p->pLeft = p->pRight = 0;
38031     return p;
38032   }
38033   pLeft = rowSetNDeepTree(ppList, iDepth-1);
38034   p = *ppList;
38035   if( p==0 ){
38036     return pLeft;
38037   }
38038   p->pLeft = pLeft;
38039   *ppList = p->pRight;
38040   p->pRight = rowSetNDeepTree(ppList, iDepth-1);
38041   return p;
38042 }
38043
38044 /*
38045 ** Convert a sorted list of elements into a binary tree. Make the tree
38046 ** as deep as it needs to be in order to contain the entire list.
38047 */
38048 static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
38049   int iDepth;           /* Depth of the tree so far */
38050   struct RowSetEntry *p;       /* Current tree root */
38051   struct RowSetEntry *pLeft;   /* Left subtree */
38052
38053   assert( pList!=0 );
38054   p = pList;
38055   pList = p->pRight;
38056   p->pLeft = p->pRight = 0;
38057   for(iDepth=1; pList; iDepth++){
38058     pLeft = p;
38059     p = pList;
38060     pList = p->pRight;
38061     p->pLeft = pLeft;
38062     p->pRight = rowSetNDeepTree(&pList, iDepth);
38063   }
38064   return p;
38065 }
38066
38067 /*
38068 ** Take all the entries on p->pEntry and on the trees in p->pForest and
38069 ** sort them all together into one big ordered list on p->pEntry.
38070 **
38071 ** This routine should only be called once in the life of a RowSet.
38072 */
38073 static void rowSetToList(RowSet *p){
38074
38075   /* This routine is called only once */
38076   assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
38077
38078   if( (p->rsFlags & ROWSET_SORTED)==0 ){
38079     p->pEntry = rowSetEntrySort(p->pEntry);
38080   }
38081
38082   /* While this module could theoretically support it, sqlite3RowSetNext()
38083   ** is never called after sqlite3RowSetText() for the same RowSet.  So
38084   ** there is never a forest to deal with.  Should this change, simply
38085   ** remove the assert() and the #if 0. */
38086   assert( p->pForest==0 );
38087 #if 0
38088   while( p->pForest ){
38089     struct RowSetEntry *pTree = p->pForest->pLeft;
38090     if( pTree ){
38091       struct RowSetEntry *pHead, *pTail;
38092       rowSetTreeToList(pTree, &pHead, &pTail);
38093       p->pEntry = rowSetEntryMerge(p->pEntry, pHead);
38094     }
38095     p->pForest = p->pForest->pRight;
38096   }
38097 #endif
38098   p->rsFlags |= ROWSET_NEXT;  /* Verify this routine is never called again */
38099 }
38100
38101 /*
38102 ** Extract the smallest element from the RowSet.
38103 ** Write the element into *pRowid.  Return 1 on success.  Return
38104 ** 0 if the RowSet is already empty.
38105 **
38106 ** After this routine has been called, the sqlite3RowSetInsert()
38107 ** routine may not be called again.  
38108 */
38109 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
38110   assert( p!=0 );
38111
38112   /* Merge the forest into a single sorted list on first call */
38113   if( (p->rsFlags & ROWSET_NEXT)==0 ) rowSetToList(p);
38114
38115   /* Return the next entry on the list */
38116   if( p->pEntry ){
38117     *pRowid = p->pEntry->v;
38118     p->pEntry = p->pEntry->pRight;
38119     if( p->pEntry==0 ){
38120       sqlite3RowSetClear(p);
38121     }
38122     return 1;
38123   }else{
38124     return 0;
38125   }
38126 }
38127
38128 /*
38129 ** Check to see if element iRowid was inserted into the rowset as
38130 ** part of any insert batch prior to iBatch.  Return 1 or 0.
38131 **
38132 ** If this is the first test of a new batch and if there exist entires
38133 ** on pRowSet->pEntry, then sort those entires into the forest at
38134 ** pRowSet->pForest so that they can be tested.
38135 */
38136 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){
38137   struct RowSetEntry *p, *pTree;
38138
38139   /* This routine is never called after sqlite3RowSetNext() */
38140   assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
38141
38142   /* Sort entries into the forest on the first test of a new batch 
38143   */
38144   if( iBatch!=pRowSet->iBatch ){
38145     p = pRowSet->pEntry;
38146     if( p ){
38147       struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
38148       if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){
38149         p = rowSetEntrySort(p);
38150       }
38151       for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
38152         ppPrevTree = &pTree->pRight;
38153         if( pTree->pLeft==0 ){
38154           pTree->pLeft = rowSetListToTree(p);
38155           break;
38156         }else{
38157           struct RowSetEntry *pAux, *pTail;
38158           rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
38159           pTree->pLeft = 0;
38160           p = rowSetEntryMerge(pAux, p);
38161         }
38162       }
38163       if( pTree==0 ){
38164         *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
38165         if( pTree ){
38166           pTree->v = 0;
38167           pTree->pRight = 0;
38168           pTree->pLeft = rowSetListToTree(p);
38169         }
38170       }
38171       pRowSet->pEntry = 0;
38172       pRowSet->pLast = 0;
38173       pRowSet->rsFlags |= ROWSET_SORTED;
38174     }
38175     pRowSet->iBatch = iBatch;
38176   }
38177
38178   /* Test to see if the iRowid value appears anywhere in the forest.
38179   ** Return 1 if it does and 0 if not.
38180   */
38181   for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
38182     p = pTree->pLeft;
38183     while( p ){
38184       if( p->v<iRowid ){
38185         p = p->pRight;
38186       }else if( p->v>iRowid ){
38187         p = p->pLeft;
38188       }else{
38189         return 1;
38190       }
38191     }
38192   }
38193   return 0;
38194 }
38195
38196 /************** End of rowset.c **********************************************/
38197 /************** Begin file pager.c *******************************************/
38198 /*
38199 ** 2001 September 15
38200 **
38201 ** The author disclaims copyright to this source code.  In place of
38202 ** a legal notice, here is a blessing:
38203 **
38204 **    May you do good and not evil.
38205 **    May you find forgiveness for yourself and forgive others.
38206 **    May you share freely, never taking more than you give.
38207 **
38208 *************************************************************************
38209 ** This is the implementation of the page cache subsystem or "pager".
38210 ** 
38211 ** The pager is used to access a database disk file.  It implements
38212 ** atomic commit and rollback through the use of a journal file that
38213 ** is separate from the database file.  The pager also implements file
38214 ** locking to prevent two processes from writing the same database
38215 ** file simultaneously, or one process from reading the database while
38216 ** another is writing.
38217 */
38218 #ifndef SQLITE_OMIT_DISKIO
38219 /************** Include wal.h in the middle of pager.c ***********************/
38220 /************** Begin file wal.h *********************************************/
38221 /*
38222 ** 2010 February 1
38223 **
38224 ** The author disclaims copyright to this source code.  In place of
38225 ** a legal notice, here is a blessing:
38226 **
38227 **    May you do good and not evil.
38228 **    May you find forgiveness for yourself and forgive others.
38229 **    May you share freely, never taking more than you give.
38230 **
38231 *************************************************************************
38232 ** This header file defines the interface to the write-ahead logging 
38233 ** system. Refer to the comments below and the header comment attached to 
38234 ** the implementation of each function in log.c for further details.
38235 */
38236
38237 #ifndef _WAL_H_
38238 #define _WAL_H_
38239
38240
38241 /* Additional values that can be added to the sync_flags argument of
38242 ** sqlite3WalFrames():
38243 */
38244 #define WAL_SYNC_TRANSACTIONS  0x20   /* Sync at the end of each transaction */
38245 #define SQLITE_SYNC_MASK       0x13   /* Mask off the SQLITE_SYNC_* values */
38246
38247 #ifdef SQLITE_OMIT_WAL
38248 # define sqlite3WalOpen(x,y,z)                   0
38249 # define sqlite3WalLimit(x,y)
38250 # define sqlite3WalClose(w,x,y,z)                0
38251 # define sqlite3WalBeginReadTransaction(y,z)     0
38252 # define sqlite3WalEndReadTransaction(z)
38253 # define sqlite3WalDbsize(y)                     0
38254 # define sqlite3WalBeginWriteTransaction(y)      0
38255 # define sqlite3WalEndWriteTransaction(x)        0
38256 # define sqlite3WalUndo(x,y,z)                   0
38257 # define sqlite3WalSavepoint(y,z)
38258 # define sqlite3WalSavepointUndo(y,z)            0
38259 # define sqlite3WalFrames(u,v,w,x,y,z)           0
38260 # define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
38261 # define sqlite3WalCallback(z)                   0
38262 # define sqlite3WalExclusiveMode(y,z)            0
38263 # define sqlite3WalHeapMemory(z)                 0
38264 # define sqlite3WalFramesize(z)                  0
38265 # define sqlite3WalFindFrame(x,y,z)              0
38266 #else
38267
38268 #define WAL_SAVEPOINT_NDATA 4
38269
38270 /* Connection to a write-ahead log (WAL) file. 
38271 ** There is one object of this type for each pager. 
38272 */
38273 typedef struct Wal Wal;
38274
38275 /* Open and close a connection to a write-ahead log. */
38276 SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
38277 SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
38278
38279 /* Set the limiting size of a WAL file. */
38280 SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
38281
38282 /* Used by readers to open (lock) and close (unlock) a snapshot.  A 
38283 ** snapshot is like a read-transaction.  It is the state of the database
38284 ** at an instant in time.  sqlite3WalOpenSnapshot gets a read lock and
38285 ** preserves the current state even if the other threads or processes
38286 ** write to or checkpoint the WAL.  sqlite3WalCloseSnapshot() closes the
38287 ** transaction and releases the lock.
38288 */
38289 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
38290 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
38291
38292 /* Read a page from the write-ahead log, if it is present. */
38293 SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);
38294 SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);
38295
38296 /* If the WAL is not empty, return the size of the database. */
38297 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
38298
38299 /* Obtain or release the WRITER lock. */
38300 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
38301 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
38302
38303 /* Undo any frames written (but not committed) to the log */
38304 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
38305
38306 /* Return an integer that records the current (uncommitted) write
38307 ** position in the WAL */
38308 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
38309
38310 /* Move the write position of the WAL back to iFrame.  Called in
38311 ** response to a ROLLBACK TO command. */
38312 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
38313
38314 /* Write a frame or frames to the log. */
38315 SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
38316
38317 /* Copy pages from the log to the database file */ 
38318 SQLITE_PRIVATE int sqlite3WalCheckpoint(
38319   Wal *pWal,                      /* Write-ahead log connection */
38320   int eMode,                      /* One of PASSIVE, FULL and RESTART */
38321   int (*xBusy)(void*),            /* Function to call when busy */
38322   void *pBusyArg,                 /* Context argument for xBusyHandler */
38323   int sync_flags,                 /* Flags to sync db file with (or 0) */
38324   int nBuf,                       /* Size of buffer nBuf */
38325   u8 *zBuf,                       /* Temporary buffer to use */
38326   int *pnLog,                     /* OUT: Number of frames in WAL */
38327   int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
38328 );
38329
38330 /* Return the value to pass to a sqlite3_wal_hook callback, the
38331 ** number of frames in the WAL at the point of the last commit since
38332 ** sqlite3WalCallback() was called.  If no commits have occurred since
38333 ** the last call, then return 0.
38334 */
38335 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
38336
38337 /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
38338 ** by the pager layer on the database file.
38339 */
38340 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
38341
38342 /* Return true if the argument is non-NULL and the WAL module is using
38343 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
38344 ** WAL module is using shared-memory, return false. 
38345 */
38346 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
38347
38348 #ifdef SQLITE_ENABLE_ZIPVFS
38349 /* If the WAL file is not empty, return the number of bytes of content
38350 ** stored in each frame (i.e. the db page-size when the WAL was created).
38351 */
38352 SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
38353 #endif
38354
38355 #endif /* ifndef SQLITE_OMIT_WAL */
38356 #endif /* _WAL_H_ */
38357
38358 /************** End of wal.h *************************************************/
38359 /************** Continuing where we left off in pager.c **********************/
38360
38361
38362 /******************* NOTES ON THE DESIGN OF THE PAGER ************************
38363 **
38364 ** This comment block describes invariants that hold when using a rollback
38365 ** journal.  These invariants do not apply for journal_mode=WAL,
38366 ** journal_mode=MEMORY, or journal_mode=OFF.
38367 **
38368 ** Within this comment block, a page is deemed to have been synced
38369 ** automatically as soon as it is written when PRAGMA synchronous=OFF.
38370 ** Otherwise, the page is not synced until the xSync method of the VFS
38371 ** is called successfully on the file containing the page.
38372 **
38373 ** Definition:  A page of the database file is said to be "overwriteable" if
38374 ** one or more of the following are true about the page:
38375 ** 
38376 **     (a)  The original content of the page as it was at the beginning of
38377 **          the transaction has been written into the rollback journal and
38378 **          synced.
38379 ** 
38380 **     (b)  The page was a freelist leaf page at the start of the transaction.
38381 ** 
38382 **     (c)  The page number is greater than the largest page that existed in
38383 **          the database file at the start of the transaction.
38384 ** 
38385 ** (1) A page of the database file is never overwritten unless one of the
38386 **     following are true:
38387 ** 
38388 **     (a) The page and all other pages on the same sector are overwriteable.
38389 ** 
38390 **     (b) The atomic page write optimization is enabled, and the entire
38391 **         transaction other than the update of the transaction sequence
38392 **         number consists of a single page change.
38393 ** 
38394 ** (2) The content of a page written into the rollback journal exactly matches
38395 **     both the content in the database when the rollback journal was written
38396 **     and the content in the database at the beginning of the current
38397 **     transaction.
38398 ** 
38399 ** (3) Writes to the database file are an integer multiple of the page size
38400 **     in length and are aligned on a page boundary.
38401 ** 
38402 ** (4) Reads from the database file are either aligned on a page boundary and
38403 **     an integer multiple of the page size in length or are taken from the
38404 **     first 100 bytes of the database file.
38405 ** 
38406 ** (5) All writes to the database file are synced prior to the rollback journal
38407 **     being deleted, truncated, or zeroed.
38408 ** 
38409 ** (6) If a master journal file is used, then all writes to the database file
38410 **     are synced prior to the master journal being deleted.
38411 ** 
38412 ** Definition: Two databases (or the same database at two points it time)
38413 ** are said to be "logically equivalent" if they give the same answer to
38414 ** all queries.  Note in particular the content of freelist leaf
38415 ** pages can be changed arbitarily without effecting the logical equivalence
38416 ** of the database.
38417 ** 
38418 ** (7) At any time, if any subset, including the empty set and the total set,
38419 **     of the unsynced changes to a rollback journal are removed and the 
38420 **     journal is rolled back, the resulting database file will be logical
38421 **     equivalent to the database file at the beginning of the transaction.
38422 ** 
38423 ** (8) When a transaction is rolled back, the xTruncate method of the VFS
38424 **     is called to restore the database file to the same size it was at
38425 **     the beginning of the transaction.  (In some VFSes, the xTruncate
38426 **     method is a no-op, but that does not change the fact the SQLite will
38427 **     invoke it.)
38428 ** 
38429 ** (9) Whenever the database file is modified, at least one bit in the range
38430 **     of bytes from 24 through 39 inclusive will be changed prior to releasing
38431 **     the EXCLUSIVE lock, thus signaling other connections on the same
38432 **     database to flush their caches.
38433 **
38434 ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
38435 **      than one billion transactions.
38436 **
38437 ** (11) A database file is well-formed at the beginning and at the conclusion
38438 **      of every transaction.
38439 **
38440 ** (12) An EXCLUSIVE lock is held on the database file when writing to
38441 **      the database file.
38442 **
38443 ** (13) A SHARED lock is held on the database file while reading any
38444 **      content out of the database file.
38445 **
38446 ******************************************************************************/
38447
38448 /*
38449 ** Macros for troubleshooting.  Normally turned off
38450 */
38451 #if 0
38452 int sqlite3PagerTrace=1;  /* True to enable tracing */
38453 #define sqlite3DebugPrintf printf
38454 #define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
38455 #else
38456 #define PAGERTRACE(X)
38457 #endif
38458
38459 /*
38460 ** The following two macros are used within the PAGERTRACE() macros above
38461 ** to print out file-descriptors. 
38462 **
38463 ** PAGERID() takes a pointer to a Pager struct as its argument. The
38464 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
38465 ** struct as its argument.
38466 */
38467 #define PAGERID(p) ((int)(p->fd))
38468 #define FILEHANDLEID(fd) ((int)fd)
38469
38470 /*
38471 ** The Pager.eState variable stores the current 'state' of a pager. A
38472 ** pager may be in any one of the seven states shown in the following
38473 ** state diagram.
38474 **
38475 **                            OPEN <------+------+
38476 **                              |         |      |
38477 **                              V         |      |
38478 **               +---------> READER-------+      |
38479 **               |              |                |
38480 **               |              V                |
38481 **               |<-------WRITER_LOCKED------> ERROR
38482 **               |              |                ^  
38483 **               |              V                |
38484 **               |<------WRITER_CACHEMOD-------->|
38485 **               |              |                |
38486 **               |              V                |
38487 **               |<-------WRITER_DBMOD---------->|
38488 **               |              |                |
38489 **               |              V                |
38490 **               +<------WRITER_FINISHED-------->+
38491 **
38492 **
38493 ** List of state transitions and the C [function] that performs each:
38494 ** 
38495 **   OPEN              -> READER              [sqlite3PagerSharedLock]
38496 **   READER            -> OPEN                [pager_unlock]
38497 **
38498 **   READER            -> WRITER_LOCKED       [sqlite3PagerBegin]
38499 **   WRITER_LOCKED     -> WRITER_CACHEMOD     [pager_open_journal]
38500 **   WRITER_CACHEMOD   -> WRITER_DBMOD        [syncJournal]
38501 **   WRITER_DBMOD      -> WRITER_FINISHED     [sqlite3PagerCommitPhaseOne]
38502 **   WRITER_***        -> READER              [pager_end_transaction]
38503 **
38504 **   WRITER_***        -> ERROR               [pager_error]
38505 **   ERROR             -> OPEN                [pager_unlock]
38506 ** 
38507 **
38508 **  OPEN:
38509 **
38510 **    The pager starts up in this state. Nothing is guaranteed in this
38511 **    state - the file may or may not be locked and the database size is
38512 **    unknown. The database may not be read or written.
38513 **
38514 **    * No read or write transaction is active.
38515 **    * Any lock, or no lock at all, may be held on the database file.
38516 **    * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
38517 **
38518 **  READER:
38519 **
38520 **    In this state all the requirements for reading the database in 
38521 **    rollback (non-WAL) mode are met. Unless the pager is (or recently
38522 **    was) in exclusive-locking mode, a user-level read transaction is 
38523 **    open. The database size is known in this state.
38524 **
38525 **    A connection running with locking_mode=normal enters this state when
38526 **    it opens a read-transaction on the database and returns to state
38527 **    OPEN after the read-transaction is completed. However a connection
38528 **    running in locking_mode=exclusive (including temp databases) remains in
38529 **    this state even after the read-transaction is closed. The only way
38530 **    a locking_mode=exclusive connection can transition from READER to OPEN
38531 **    is via the ERROR state (see below).
38532 ** 
38533 **    * A read transaction may be active (but a write-transaction cannot).
38534 **    * A SHARED or greater lock is held on the database file.
38535 **    * The dbSize variable may be trusted (even if a user-level read 
38536 **      transaction is not active). The dbOrigSize and dbFileSize variables
38537 **      may not be trusted at this point.
38538 **    * If the database is a WAL database, then the WAL connection is open.
38539 **    * Even if a read-transaction is not open, it is guaranteed that 
38540 **      there is no hot-journal in the file-system.
38541 **
38542 **  WRITER_LOCKED:
38543 **
38544 **    The pager moves to this state from READER when a write-transaction
38545 **    is first opened on the database. In WRITER_LOCKED state, all locks 
38546 **    required to start a write-transaction are held, but no actual 
38547 **    modifications to the cache or database have taken place.
38548 **
38549 **    In rollback mode, a RESERVED or (if the transaction was opened with 
38550 **    BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
38551 **    moving to this state, but the journal file is not written to or opened 
38552 **    to in this state. If the transaction is committed or rolled back while 
38553 **    in WRITER_LOCKED state, all that is required is to unlock the database 
38554 **    file.
38555 **
38556 **    IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
38557 **    If the connection is running with locking_mode=exclusive, an attempt
38558 **    is made to obtain an EXCLUSIVE lock on the database file.
38559 **
38560 **    * A write transaction is active.
38561 **    * If the connection is open in rollback-mode, a RESERVED or greater 
38562 **      lock is held on the database file.
38563 **    * If the connection is open in WAL-mode, a WAL write transaction
38564 **      is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
38565 **      called).
38566 **    * The dbSize, dbOrigSize and dbFileSize variables are all valid.
38567 **    * The contents of the pager cache have not been modified.
38568 **    * The journal file may or may not be open.
38569 **    * Nothing (not even the first header) has been written to the journal.
38570 **
38571 **  WRITER_CACHEMOD:
38572 **
38573 **    A pager moves from WRITER_LOCKED state to this state when a page is
38574 **    first modified by the upper layer. In rollback mode the journal file
38575 **    is opened (if it is not already open) and a header written to the
38576 **    start of it. The database file on disk has not been modified.
38577 **
38578 **    * A write transaction is active.
38579 **    * A RESERVED or greater lock is held on the database file.
38580 **    * The journal file is open and the first header has been written 
38581 **      to it, but the header has not been synced to disk.
38582 **    * The contents of the page cache have been modified.
38583 **
38584 **  WRITER_DBMOD:
38585 **
38586 **    The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
38587 **    when it modifies the contents of the database file. WAL connections
38588 **    never enter this state (since they do not modify the database file,
38589 **    just the log file).
38590 **
38591 **    * A write transaction is active.
38592 **    * An EXCLUSIVE or greater lock is held on the database file.
38593 **    * The journal file is open and the first header has been written 
38594 **      and synced to disk.
38595 **    * The contents of the page cache have been modified (and possibly
38596 **      written to disk).
38597 **
38598 **  WRITER_FINISHED:
38599 **
38600 **    It is not possible for a WAL connection to enter this state.
38601 **
38602 **    A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
38603 **    state after the entire transaction has been successfully written into the
38604 **    database file. In this state the transaction may be committed simply
38605 **    by finalizing the journal file. Once in WRITER_FINISHED state, it is 
38606 **    not possible to modify the database further. At this point, the upper 
38607 **    layer must either commit or rollback the transaction.
38608 **
38609 **    * A write transaction is active.
38610 **    * An EXCLUSIVE or greater lock is held on the database file.
38611 **    * All writing and syncing of journal and database data has finished.
38612 **      If no error occurred, all that remains is to finalize the journal to
38613 **      commit the transaction. If an error did occur, the caller will need
38614 **      to rollback the transaction. 
38615 **
38616 **  ERROR:
38617 **
38618 **    The ERROR state is entered when an IO or disk-full error (including
38619 **    SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it 
38620 **    difficult to be sure that the in-memory pager state (cache contents, 
38621 **    db size etc.) are consistent with the contents of the file-system.
38622 **
38623 **    Temporary pager files may enter the ERROR state, but in-memory pagers
38624 **    cannot.
38625 **
38626 **    For example, if an IO error occurs while performing a rollback, 
38627 **    the contents of the page-cache may be left in an inconsistent state.
38628 **    At this point it would be dangerous to change back to READER state
38629 **    (as usually happens after a rollback). Any subsequent readers might
38630 **    report database corruption (due to the inconsistent cache), and if
38631 **    they upgrade to writers, they may inadvertently corrupt the database
38632 **    file. To avoid this hazard, the pager switches into the ERROR state
38633 **    instead of READER following such an error.
38634 **
38635 **    Once it has entered the ERROR state, any attempt to use the pager
38636 **    to read or write data returns an error. Eventually, once all 
38637 **    outstanding transactions have been abandoned, the pager is able to
38638 **    transition back to OPEN state, discarding the contents of the 
38639 **    page-cache and any other in-memory state at the same time. Everything
38640 **    is reloaded from disk (and, if necessary, hot-journal rollback peformed)
38641 **    when a read-transaction is next opened on the pager (transitioning
38642 **    the pager into READER state). At that point the system has recovered 
38643 **    from the error.
38644 **
38645 **    Specifically, the pager jumps into the ERROR state if:
38646 **
38647 **      1. An error occurs while attempting a rollback. This happens in
38648 **         function sqlite3PagerRollback().
38649 **
38650 **      2. An error occurs while attempting to finalize a journal file
38651 **         following a commit in function sqlite3PagerCommitPhaseTwo().
38652 **
38653 **      3. An error occurs while attempting to write to the journal or
38654 **         database file in function pagerStress() in order to free up
38655 **         memory.
38656 **
38657 **    In other cases, the error is returned to the b-tree layer. The b-tree
38658 **    layer then attempts a rollback operation. If the error condition 
38659 **    persists, the pager enters the ERROR state via condition (1) above.
38660 **
38661 **    Condition (3) is necessary because it can be triggered by a read-only
38662 **    statement executed within a transaction. In this case, if the error
38663 **    code were simply returned to the user, the b-tree layer would not
38664 **    automatically attempt a rollback, as it assumes that an error in a
38665 **    read-only statement cannot leave the pager in an internally inconsistent 
38666 **    state.
38667 **
38668 **    * The Pager.errCode variable is set to something other than SQLITE_OK.
38669 **    * There are one or more outstanding references to pages (after the
38670 **      last reference is dropped the pager should move back to OPEN state).
38671 **    * The pager is not an in-memory pager.
38672 **    
38673 **
38674 ** Notes:
38675 **
38676 **   * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
38677 **     connection is open in WAL mode. A WAL connection is always in one
38678 **     of the first four states.
38679 **
38680 **   * Normally, a connection open in exclusive mode is never in PAGER_OPEN
38681 **     state. There are two exceptions: immediately after exclusive-mode has
38682 **     been turned on (and before any read or write transactions are 
38683 **     executed), and when the pager is leaving the "error state".
38684 **
38685 **   * See also: assert_pager_state().
38686 */
38687 #define PAGER_OPEN                  0
38688 #define PAGER_READER                1
38689 #define PAGER_WRITER_LOCKED         2
38690 #define PAGER_WRITER_CACHEMOD       3
38691 #define PAGER_WRITER_DBMOD          4
38692 #define PAGER_WRITER_FINISHED       5
38693 #define PAGER_ERROR                 6
38694
38695 /*
38696 ** The Pager.eLock variable is almost always set to one of the 
38697 ** following locking-states, according to the lock currently held on
38698 ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
38699 ** This variable is kept up to date as locks are taken and released by
38700 ** the pagerLockDb() and pagerUnlockDb() wrappers.
38701 **
38702 ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
38703 ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
38704 ** the operation was successful. In these circumstances pagerLockDb() and
38705 ** pagerUnlockDb() take a conservative approach - eLock is always updated
38706 ** when unlocking the file, and only updated when locking the file if the
38707 ** VFS call is successful. This way, the Pager.eLock variable may be set
38708 ** to a less exclusive (lower) value than the lock that is actually held
38709 ** at the system level, but it is never set to a more exclusive value.
38710 **
38711 ** This is usually safe. If an xUnlock fails or appears to fail, there may 
38712 ** be a few redundant xLock() calls or a lock may be held for longer than
38713 ** required, but nothing really goes wrong.
38714 **
38715 ** The exception is when the database file is unlocked as the pager moves
38716 ** from ERROR to OPEN state. At this point there may be a hot-journal file 
38717 ** in the file-system that needs to be rolled back (as part of a OPEN->SHARED
38718 ** transition, by the same pager or any other). If the call to xUnlock()
38719 ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
38720 ** can confuse the call to xCheckReservedLock() call made later as part
38721 ** of hot-journal detection.
38722 **
38723 ** xCheckReservedLock() is defined as returning true "if there is a RESERVED 
38724 ** lock held by this process or any others". So xCheckReservedLock may 
38725 ** return true because the caller itself is holding an EXCLUSIVE lock (but
38726 ** doesn't know it because of a previous error in xUnlock). If this happens
38727 ** a hot-journal may be mistaken for a journal being created by an active
38728 ** transaction in another process, causing SQLite to read from the database
38729 ** without rolling it back.
38730 **
38731 ** To work around this, if a call to xUnlock() fails when unlocking the
38732 ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
38733 ** is only changed back to a real locking state after a successful call
38734 ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
38735 ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK 
38736 ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
38737 ** lock on the database file before attempting to roll it back. See function
38738 ** PagerSharedLock() for more detail.
38739 **
38740 ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in 
38741 ** PAGER_OPEN state.
38742 */
38743 #define UNKNOWN_LOCK                (EXCLUSIVE_LOCK+1)
38744
38745 /*
38746 ** A macro used for invoking the codec if there is one
38747 */
38748 #ifdef SQLITE_HAS_CODEC
38749 # define CODEC1(P,D,N,X,E) \
38750     if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
38751 # define CODEC2(P,D,N,X,E,O) \
38752     if( P->xCodec==0 ){ O=(char*)D; }else \
38753     if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
38754 #else
38755 # define CODEC1(P,D,N,X,E)   /* NO-OP */
38756 # define CODEC2(P,D,N,X,E,O) O=(char*)D
38757 #endif
38758
38759 /*
38760 ** The maximum allowed sector size. 64KiB. If the xSectorsize() method 
38761 ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
38762 ** This could conceivably cause corruption following a power failure on
38763 ** such a system. This is currently an undocumented limit.
38764 */
38765 #define MAX_SECTOR_SIZE 0x10000
38766
38767 /*
38768 ** An instance of the following structure is allocated for each active
38769 ** savepoint and statement transaction in the system. All such structures
38770 ** are stored in the Pager.aSavepoint[] array, which is allocated and
38771 ** resized using sqlite3Realloc().
38772 **
38773 ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
38774 ** set to 0. If a journal-header is written into the main journal while
38775 ** the savepoint is active, then iHdrOffset is set to the byte offset 
38776 ** immediately following the last journal record written into the main
38777 ** journal before the journal-header. This is required during savepoint
38778 ** rollback (see pagerPlaybackSavepoint()).
38779 */
38780 typedef struct PagerSavepoint PagerSavepoint;
38781 struct PagerSavepoint {
38782   i64 iOffset;                 /* Starting offset in main journal */
38783   i64 iHdrOffset;              /* See above */
38784   Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
38785   Pgno nOrig;                  /* Original number of pages in file */
38786   Pgno iSubRec;                /* Index of first record in sub-journal */
38787 #ifndef SQLITE_OMIT_WAL
38788   u32 aWalData[WAL_SAVEPOINT_NDATA];        /* WAL savepoint context */
38789 #endif
38790 };
38791
38792 /*
38793 ** A open page cache is an instance of struct Pager. A description of
38794 ** some of the more important member variables follows:
38795 **
38796 ** eState
38797 **
38798 **   The current 'state' of the pager object. See the comment and state
38799 **   diagram above for a description of the pager state.
38800 **
38801 ** eLock
38802 **
38803 **   For a real on-disk database, the current lock held on the database file -
38804 **   NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
38805 **
38806 **   For a temporary or in-memory database (neither of which require any
38807 **   locks), this variable is always set to EXCLUSIVE_LOCK. Since such
38808 **   databases always have Pager.exclusiveMode==1, this tricks the pager
38809 **   logic into thinking that it already has all the locks it will ever
38810 **   need (and no reason to release them).
38811 **
38812 **   In some (obscure) circumstances, this variable may also be set to
38813 **   UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
38814 **   details.
38815 **
38816 ** changeCountDone
38817 **
38818 **   This boolean variable is used to make sure that the change-counter 
38819 **   (the 4-byte header field at byte offset 24 of the database file) is 
38820 **   not updated more often than necessary. 
38821 **
38822 **   It is set to true when the change-counter field is updated, which 
38823 **   can only happen if an exclusive lock is held on the database file.
38824 **   It is cleared (set to false) whenever an exclusive lock is 
38825 **   relinquished on the database file. Each time a transaction is committed,
38826 **   The changeCountDone flag is inspected. If it is true, the work of
38827 **   updating the change-counter is omitted for the current transaction.
38828 **
38829 **   This mechanism means that when running in exclusive mode, a connection 
38830 **   need only update the change-counter once, for the first transaction
38831 **   committed.
38832 **
38833 ** setMaster
38834 **
38835 **   When PagerCommitPhaseOne() is called to commit a transaction, it may
38836 **   (or may not) specify a master-journal name to be written into the 
38837 **   journal file before it is synced to disk.
38838 **
38839 **   Whether or not a journal file contains a master-journal pointer affects 
38840 **   the way in which the journal file is finalized after the transaction is 
38841 **   committed or rolled back when running in "journal_mode=PERSIST" mode.
38842 **   If a journal file does not contain a master-journal pointer, it is
38843 **   finalized by overwriting the first journal header with zeroes. If
38844 **   it does contain a master-journal pointer the journal file is finalized 
38845 **   by truncating it to zero bytes, just as if the connection were 
38846 **   running in "journal_mode=truncate" mode.
38847 **
38848 **   Journal files that contain master journal pointers cannot be finalized
38849 **   simply by overwriting the first journal-header with zeroes, as the
38850 **   master journal pointer could interfere with hot-journal rollback of any
38851 **   subsequently interrupted transaction that reuses the journal file.
38852 **
38853 **   The flag is cleared as soon as the journal file is finalized (either
38854 **   by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
38855 **   journal file from being successfully finalized, the setMaster flag
38856 **   is cleared anyway (and the pager will move to ERROR state).
38857 **
38858 ** doNotSpill, doNotSyncSpill
38859 **
38860 **   These two boolean variables control the behavior of cache-spills
38861 **   (calls made by the pcache module to the pagerStress() routine to
38862 **   write cached data to the file-system in order to free up memory).
38863 **
38864 **   When doNotSpill is non-zero, writing to the database from pagerStress()
38865 **   is disabled altogether. This is done in a very obscure case that
38866 **   comes up during savepoint rollback that requires the pcache module
38867 **   to allocate a new page to prevent the journal file from being written
38868 **   while it is being traversed by code in pager_playback().
38869 ** 
38870 **   If doNotSyncSpill is non-zero, writing to the database from pagerStress()
38871 **   is permitted, but syncing the journal file is not. This flag is set
38872 **   by sqlite3PagerWrite() when the file-system sector-size is larger than
38873 **   the database page-size in order to prevent a journal sync from happening 
38874 **   in between the journalling of two pages on the same sector. 
38875 **
38876 ** subjInMemory
38877 **
38878 **   This is a boolean variable. If true, then any required sub-journal
38879 **   is opened as an in-memory journal file. If false, then in-memory
38880 **   sub-journals are only used for in-memory pager files.
38881 **
38882 **   This variable is updated by the upper layer each time a new 
38883 **   write-transaction is opened.
38884 **
38885 ** dbSize, dbOrigSize, dbFileSize
38886 **
38887 **   Variable dbSize is set to the number of pages in the database file.
38888 **   It is valid in PAGER_READER and higher states (all states except for
38889 **   OPEN and ERROR). 
38890 **
38891 **   dbSize is set based on the size of the database file, which may be 
38892 **   larger than the size of the database (the value stored at offset
38893 **   28 of the database header by the btree). If the size of the file
38894 **   is not an integer multiple of the page-size, the value stored in
38895 **   dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
38896 **   Except, any file that is greater than 0 bytes in size is considered
38897 **   to have at least one page. (i.e. a 1KB file with 2K page-size leads
38898 **   to dbSize==1).
38899 **
38900 **   During a write-transaction, if pages with page-numbers greater than
38901 **   dbSize are modified in the cache, dbSize is updated accordingly.
38902 **   Similarly, if the database is truncated using PagerTruncateImage(), 
38903 **   dbSize is updated.
38904 **
38905 **   Variables dbOrigSize and dbFileSize are valid in states 
38906 **   PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
38907 **   variable at the start of the transaction. It is used during rollback,
38908 **   and to determine whether or not pages need to be journalled before
38909 **   being modified.
38910 **
38911 **   Throughout a write-transaction, dbFileSize contains the size of
38912 **   the file on disk in pages. It is set to a copy of dbSize when the
38913 **   write-transaction is first opened, and updated when VFS calls are made
38914 **   to write or truncate the database file on disk. 
38915 **
38916 **   The only reason the dbFileSize variable is required is to suppress 
38917 **   unnecessary calls to xTruncate() after committing a transaction. If, 
38918 **   when a transaction is committed, the dbFileSize variable indicates 
38919 **   that the database file is larger than the database image (Pager.dbSize), 
38920 **   pager_truncate() is called. The pager_truncate() call uses xFilesize()
38921 **   to measure the database file on disk, and then truncates it if required.
38922 **   dbFileSize is not used when rolling back a transaction. In this case
38923 **   pager_truncate() is called unconditionally (which means there may be
38924 **   a call to xFilesize() that is not strictly required). In either case,
38925 **   pager_truncate() may cause the file to become smaller or larger.
38926 **
38927 ** dbHintSize
38928 **
38929 **   The dbHintSize variable is used to limit the number of calls made to
38930 **   the VFS xFileControl(FCNTL_SIZE_HINT) method. 
38931 **
38932 **   dbHintSize is set to a copy of the dbSize variable when a
38933 **   write-transaction is opened (at the same time as dbFileSize and
38934 **   dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
38935 **   dbHintSize is increased to the number of pages that correspond to the
38936 **   size-hint passed to the method call. See pager_write_pagelist() for 
38937 **   details.
38938 **
38939 ** errCode
38940 **
38941 **   The Pager.errCode variable is only ever used in PAGER_ERROR state. It
38942 **   is set to zero in all other states. In PAGER_ERROR state, Pager.errCode 
38943 **   is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX 
38944 **   sub-codes.
38945 */
38946 struct Pager {
38947   sqlite3_vfs *pVfs;          /* OS functions to use for IO */
38948   u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
38949   u8 journalMode;             /* One of the PAGER_JOURNALMODE_* values */
38950   u8 useJournal;              /* Use a rollback journal on this file */
38951   u8 noSync;                  /* Do not sync the journal if true */
38952   u8 fullSync;                /* Do extra syncs of the journal for robustness */
38953   u8 ckptSyncFlags;           /* SYNC_NORMAL or SYNC_FULL for checkpoint */
38954   u8 walSyncFlags;            /* SYNC_NORMAL or SYNC_FULL for wal writes */
38955   u8 syncFlags;               /* SYNC_NORMAL or SYNC_FULL otherwise */
38956   u8 tempFile;                /* zFilename is a temporary file */
38957   u8 readOnly;                /* True for a read-only database */
38958   u8 memDb;                   /* True to inhibit all file I/O */
38959
38960   /**************************************************************************
38961   ** The following block contains those class members that change during
38962   ** routine opertion.  Class members not in this block are either fixed
38963   ** when the pager is first created or else only change when there is a
38964   ** significant mode change (such as changing the page_size, locking_mode,
38965   ** or the journal_mode).  From another view, these class members describe
38966   ** the "state" of the pager, while other class members describe the
38967   ** "configuration" of the pager.
38968   */
38969   u8 eState;                  /* Pager state (OPEN, READER, WRITER_LOCKED..) */
38970   u8 eLock;                   /* Current lock held on database file */
38971   u8 changeCountDone;         /* Set after incrementing the change-counter */
38972   u8 setMaster;               /* True if a m-j name has been written to jrnl */
38973   u8 doNotSpill;              /* Do not spill the cache when non-zero */
38974   u8 doNotSyncSpill;          /* Do not do a spill that requires jrnl sync */
38975   u8 subjInMemory;            /* True to use in-memory sub-journals */
38976   Pgno dbSize;                /* Number of pages in the database */
38977   Pgno dbOrigSize;            /* dbSize before the current transaction */
38978   Pgno dbFileSize;            /* Number of pages in the database file */
38979   Pgno dbHintSize;            /* Value passed to FCNTL_SIZE_HINT call */
38980   int errCode;                /* One of several kinds of errors */
38981   int nRec;                   /* Pages journalled since last j-header written */
38982   u32 cksumInit;              /* Quasi-random value added to every checksum */
38983   u32 nSubRec;                /* Number of records written to sub-journal */
38984   Bitvec *pInJournal;         /* One bit for each page in the database file */
38985   sqlite3_file *fd;           /* File descriptor for database */
38986   sqlite3_file *jfd;          /* File descriptor for main journal */
38987   sqlite3_file *sjfd;         /* File descriptor for sub-journal */
38988   i64 journalOff;             /* Current write offset in the journal file */
38989   i64 journalHdr;             /* Byte offset to previous journal header */
38990   sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
38991   PagerSavepoint *aSavepoint; /* Array of active savepoints */
38992   int nSavepoint;             /* Number of elements in aSavepoint[] */
38993   char dbFileVers[16];        /* Changes whenever database file changes */
38994
38995   u8 bUseFetch;               /* True to use xFetch() */
38996   int nMmapOut;               /* Number of mmap pages currently outstanding */
38997   sqlite3_int64 szMmap;       /* Desired maximum mmap size */
38998   PgHdr *pMmapFreelist;       /* List of free mmap page headers (pDirty) */
38999   /*
39000   ** End of the routinely-changing class members
39001   ***************************************************************************/
39002
39003   u16 nExtra;                 /* Add this many bytes to each in-memory page */
39004   i16 nReserve;               /* Number of unused bytes at end of each page */
39005   u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
39006   u32 sectorSize;             /* Assumed sector size during rollback */
39007   int pageSize;               /* Number of bytes in a page */
39008   Pgno mxPgno;                /* Maximum allowed size of the database */
39009   i64 journalSizeLimit;       /* Size limit for persistent journal files */
39010   char *zFilename;            /* Name of the database file */
39011   char *zJournal;             /* Name of the journal file */
39012   int (*xBusyHandler)(void*); /* Function to call when busy */
39013   void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
39014   int aStat[3];               /* Total cache hits, misses and writes */
39015 #ifdef SQLITE_TEST
39016   int nRead;                  /* Database pages read */
39017 #endif
39018   void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
39019 #ifdef SQLITE_HAS_CODEC
39020   void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
39021   void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
39022   void (*xCodecFree)(void*);             /* Destructor for the codec */
39023   void *pCodec;               /* First argument to xCodec... methods */
39024 #endif
39025   char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
39026   PCache *pPCache;            /* Pointer to page cache object */
39027 #ifndef SQLITE_OMIT_WAL
39028   Wal *pWal;                  /* Write-ahead log used by "journal_mode=wal" */
39029   char *zWal;                 /* File name for write-ahead log */
39030 #endif
39031 };
39032
39033 /*
39034 ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
39035 ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS 
39036 ** or CACHE_WRITE to sqlite3_db_status().
39037 */
39038 #define PAGER_STAT_HIT   0
39039 #define PAGER_STAT_MISS  1
39040 #define PAGER_STAT_WRITE 2
39041
39042 /*
39043 ** The following global variables hold counters used for
39044 ** testing purposes only.  These variables do not exist in
39045 ** a non-testing build.  These variables are not thread-safe.
39046 */
39047 #ifdef SQLITE_TEST
39048 SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
39049 SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
39050 SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
39051 # define PAGER_INCR(v)  v++
39052 #else
39053 # define PAGER_INCR(v)
39054 #endif
39055
39056
39057
39058 /*
39059 ** Journal files begin with the following magic string.  The data
39060 ** was obtained from /dev/random.  It is used only as a sanity check.
39061 **
39062 ** Since version 2.8.0, the journal format contains additional sanity
39063 ** checking information.  If the power fails while the journal is being
39064 ** written, semi-random garbage data might appear in the journal
39065 ** file after power is restored.  If an attempt is then made
39066 ** to roll the journal back, the database could be corrupted.  The additional
39067 ** sanity checking data is an attempt to discover the garbage in the
39068 ** journal and ignore it.
39069 **
39070 ** The sanity checking information for the new journal format consists
39071 ** of a 32-bit checksum on each page of data.  The checksum covers both
39072 ** the page number and the pPager->pageSize bytes of data for the page.
39073 ** This cksum is initialized to a 32-bit random value that appears in the
39074 ** journal file right after the header.  The random initializer is important,
39075 ** because garbage data that appears at the end of a journal is likely
39076 ** data that was once in other files that have now been deleted.  If the
39077 ** garbage data came from an obsolete journal file, the checksums might
39078 ** be correct.  But by initializing the checksum to random value which
39079 ** is different for every journal, we minimize that risk.
39080 */
39081 static const unsigned char aJournalMagic[] = {
39082   0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
39083 };
39084
39085 /*
39086 ** The size of the of each page record in the journal is given by
39087 ** the following macro.
39088 */
39089 #define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
39090
39091 /*
39092 ** The journal header size for this pager. This is usually the same 
39093 ** size as a single disk sector. See also setSectorSize().
39094 */
39095 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
39096
39097 /*
39098 ** The macro MEMDB is true if we are dealing with an in-memory database.
39099 ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
39100 ** the value of MEMDB will be a constant and the compiler will optimize
39101 ** out code that would never execute.
39102 */
39103 #ifdef SQLITE_OMIT_MEMORYDB
39104 # define MEMDB 0
39105 #else
39106 # define MEMDB pPager->memDb
39107 #endif
39108
39109 /*
39110 ** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
39111 ** interfaces to access the database using memory-mapped I/O.
39112 */
39113 #if SQLITE_MAX_MMAP_SIZE>0
39114 # define USEFETCH(x) ((x)->bUseFetch)
39115 #else
39116 # define USEFETCH(x) 0
39117 #endif
39118
39119 /*
39120 ** The maximum legal page number is (2^31 - 1).
39121 */
39122 #define PAGER_MAX_PGNO 2147483647
39123
39124 /*
39125 ** The argument to this macro is a file descriptor (type sqlite3_file*).
39126 ** Return 0 if it is not open, or non-zero (but not 1) if it is.
39127 **
39128 ** This is so that expressions can be written as:
39129 **
39130 **   if( isOpen(pPager->jfd) ){ ...
39131 **
39132 ** instead of
39133 **
39134 **   if( pPager->jfd->pMethods ){ ...
39135 */
39136 #define isOpen(pFd) ((pFd)->pMethods)
39137
39138 /*
39139 ** Return true if this pager uses a write-ahead log instead of the usual
39140 ** rollback journal. Otherwise false.
39141 */
39142 #ifndef SQLITE_OMIT_WAL
39143 static int pagerUseWal(Pager *pPager){
39144   return (pPager->pWal!=0);
39145 }
39146 #else
39147 # define pagerUseWal(x) 0
39148 # define pagerRollbackWal(x) 0
39149 # define pagerWalFrames(v,w,x,y) 0
39150 # define pagerOpenWalIfPresent(z) SQLITE_OK
39151 # define pagerBeginReadTransaction(z) SQLITE_OK
39152 #endif
39153
39154 #ifndef NDEBUG 
39155 /*
39156 ** Usage:
39157 **
39158 **   assert( assert_pager_state(pPager) );
39159 **
39160 ** This function runs many asserts to try to find inconsistencies in
39161 ** the internal state of the Pager object.
39162 */
39163 static int assert_pager_state(Pager *p){
39164   Pager *pPager = p;
39165
39166   /* State must be valid. */
39167   assert( p->eState==PAGER_OPEN
39168        || p->eState==PAGER_READER
39169        || p->eState==PAGER_WRITER_LOCKED
39170        || p->eState==PAGER_WRITER_CACHEMOD
39171        || p->eState==PAGER_WRITER_DBMOD
39172        || p->eState==PAGER_WRITER_FINISHED
39173        || p->eState==PAGER_ERROR
39174   );
39175
39176   /* Regardless of the current state, a temp-file connection always behaves
39177   ** as if it has an exclusive lock on the database file. It never updates
39178   ** the change-counter field, so the changeCountDone flag is always set.
39179   */
39180   assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
39181   assert( p->tempFile==0 || pPager->changeCountDone );
39182
39183   /* If the useJournal flag is clear, the journal-mode must be "OFF". 
39184   ** And if the journal-mode is "OFF", the journal file must not be open.
39185   */
39186   assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
39187   assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
39188
39189   /* Check that MEMDB implies noSync. And an in-memory journal. Since 
39190   ** this means an in-memory pager performs no IO at all, it cannot encounter 
39191   ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing 
39192   ** a journal file. (although the in-memory journal implementation may 
39193   ** return SQLITE_IOERR_NOMEM while the journal file is being written). It 
39194   ** is therefore not possible for an in-memory pager to enter the ERROR 
39195   ** state.
39196   */
39197   if( MEMDB ){
39198     assert( p->noSync );
39199     assert( p->journalMode==PAGER_JOURNALMODE_OFF 
39200          || p->journalMode==PAGER_JOURNALMODE_MEMORY 
39201     );
39202     assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
39203     assert( pagerUseWal(p)==0 );
39204   }
39205
39206   /* If changeCountDone is set, a RESERVED lock or greater must be held
39207   ** on the file.
39208   */
39209   assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
39210   assert( p->eLock!=PENDING_LOCK );
39211
39212   switch( p->eState ){
39213     case PAGER_OPEN:
39214       assert( !MEMDB );
39215       assert( pPager->errCode==SQLITE_OK );
39216       assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
39217       break;
39218
39219     case PAGER_READER:
39220       assert( pPager->errCode==SQLITE_OK );
39221       assert( p->eLock!=UNKNOWN_LOCK );
39222       assert( p->eLock>=SHARED_LOCK );
39223       break;
39224
39225     case PAGER_WRITER_LOCKED:
39226       assert( p->eLock!=UNKNOWN_LOCK );
39227       assert( pPager->errCode==SQLITE_OK );
39228       if( !pagerUseWal(pPager) ){
39229         assert( p->eLock>=RESERVED_LOCK );
39230       }
39231       assert( pPager->dbSize==pPager->dbOrigSize );
39232       assert( pPager->dbOrigSize==pPager->dbFileSize );
39233       assert( pPager->dbOrigSize==pPager->dbHintSize );
39234       assert( pPager->setMaster==0 );
39235       break;
39236
39237     case PAGER_WRITER_CACHEMOD:
39238       assert( p->eLock!=UNKNOWN_LOCK );
39239       assert( pPager->errCode==SQLITE_OK );
39240       if( !pagerUseWal(pPager) ){
39241         /* It is possible that if journal_mode=wal here that neither the
39242         ** journal file nor the WAL file are open. This happens during
39243         ** a rollback transaction that switches from journal_mode=off
39244         ** to journal_mode=wal.
39245         */
39246         assert( p->eLock>=RESERVED_LOCK );
39247         assert( isOpen(p->jfd) 
39248              || p->journalMode==PAGER_JOURNALMODE_OFF 
39249              || p->journalMode==PAGER_JOURNALMODE_WAL 
39250         );
39251       }
39252       assert( pPager->dbOrigSize==pPager->dbFileSize );
39253       assert( pPager->dbOrigSize==pPager->dbHintSize );
39254       break;
39255
39256     case PAGER_WRITER_DBMOD:
39257       assert( p->eLock==EXCLUSIVE_LOCK );
39258       assert( pPager->errCode==SQLITE_OK );
39259       assert( !pagerUseWal(pPager) );
39260       assert( p->eLock>=EXCLUSIVE_LOCK );
39261       assert( isOpen(p->jfd) 
39262            || p->journalMode==PAGER_JOURNALMODE_OFF 
39263            || p->journalMode==PAGER_JOURNALMODE_WAL 
39264       );
39265       assert( pPager->dbOrigSize<=pPager->dbHintSize );
39266       break;
39267
39268     case PAGER_WRITER_FINISHED:
39269       assert( p->eLock==EXCLUSIVE_LOCK );
39270       assert( pPager->errCode==SQLITE_OK );
39271       assert( !pagerUseWal(pPager) );
39272       assert( isOpen(p->jfd) 
39273            || p->journalMode==PAGER_JOURNALMODE_OFF 
39274            || p->journalMode==PAGER_JOURNALMODE_WAL 
39275       );
39276       break;
39277
39278     case PAGER_ERROR:
39279       /* There must be at least one outstanding reference to the pager if
39280       ** in ERROR state. Otherwise the pager should have already dropped
39281       ** back to OPEN state.
39282       */
39283       assert( pPager->errCode!=SQLITE_OK );
39284       assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
39285       break;
39286   }
39287
39288   return 1;
39289 }
39290 #endif /* ifndef NDEBUG */
39291
39292 #ifdef SQLITE_DEBUG 
39293 /*
39294 ** Return a pointer to a human readable string in a static buffer
39295 ** containing the state of the Pager object passed as an argument. This
39296 ** is intended to be used within debuggers. For example, as an alternative
39297 ** to "print *pPager" in gdb:
39298 **
39299 ** (gdb) printf "%s", print_pager_state(pPager)
39300 */
39301 static char *print_pager_state(Pager *p){
39302   static char zRet[1024];
39303
39304   sqlite3_snprintf(1024, zRet,
39305       "Filename:      %s\n"
39306       "State:         %s errCode=%d\n"
39307       "Lock:          %s\n"
39308       "Locking mode:  locking_mode=%s\n"
39309       "Journal mode:  journal_mode=%s\n"
39310       "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
39311       "Journal:       journalOff=%lld journalHdr=%lld\n"
39312       "Size:          dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
39313       , p->zFilename
39314       , p->eState==PAGER_OPEN            ? "OPEN" :
39315         p->eState==PAGER_READER          ? "READER" :
39316         p->eState==PAGER_WRITER_LOCKED   ? "WRITER_LOCKED" :
39317         p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
39318         p->eState==PAGER_WRITER_DBMOD    ? "WRITER_DBMOD" :
39319         p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
39320         p->eState==PAGER_ERROR           ? "ERROR" : "?error?"
39321       , (int)p->errCode
39322       , p->eLock==NO_LOCK         ? "NO_LOCK" :
39323         p->eLock==RESERVED_LOCK   ? "RESERVED" :
39324         p->eLock==EXCLUSIVE_LOCK  ? "EXCLUSIVE" :
39325         p->eLock==SHARED_LOCK     ? "SHARED" :
39326         p->eLock==UNKNOWN_LOCK    ? "UNKNOWN" : "?error?"
39327       , p->exclusiveMode ? "exclusive" : "normal"
39328       , p->journalMode==PAGER_JOURNALMODE_MEMORY   ? "memory" :
39329         p->journalMode==PAGER_JOURNALMODE_OFF      ? "off" :
39330         p->journalMode==PAGER_JOURNALMODE_DELETE   ? "delete" :
39331         p->journalMode==PAGER_JOURNALMODE_PERSIST  ? "persist" :
39332         p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
39333         p->journalMode==PAGER_JOURNALMODE_WAL      ? "wal" : "?error?"
39334       , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
39335       , p->journalOff, p->journalHdr
39336       , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
39337   );
39338
39339   return zRet;
39340 }
39341 #endif
39342
39343 /*
39344 ** Return true if it is necessary to write page *pPg into the sub-journal.
39345 ** A page needs to be written into the sub-journal if there exists one
39346 ** or more open savepoints for which:
39347 **
39348 **   * The page-number is less than or equal to PagerSavepoint.nOrig, and
39349 **   * The bit corresponding to the page-number is not set in
39350 **     PagerSavepoint.pInSavepoint.
39351 */
39352 static int subjRequiresPage(PgHdr *pPg){
39353   Pgno pgno = pPg->pgno;
39354   Pager *pPager = pPg->pPager;
39355   int i;
39356   for(i=0; i<pPager->nSavepoint; i++){
39357     PagerSavepoint *p = &pPager->aSavepoint[i];
39358     if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
39359       return 1;
39360     }
39361   }
39362   return 0;
39363 }
39364
39365 /*
39366 ** Return true if the page is already in the journal file.
39367 */
39368 static int pageInJournal(PgHdr *pPg){
39369   return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
39370 }
39371
39372 /*
39373 ** Read a 32-bit integer from the given file descriptor.  Store the integer
39374 ** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
39375 ** error code is something goes wrong.
39376 **
39377 ** All values are stored on disk as big-endian.
39378 */
39379 static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
39380   unsigned char ac[4];
39381   int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
39382   if( rc==SQLITE_OK ){
39383     *pRes = sqlite3Get4byte(ac);
39384   }
39385   return rc;
39386 }
39387
39388 /*
39389 ** Write a 32-bit integer into a string buffer in big-endian byte order.
39390 */
39391 #define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
39392
39393
39394 /*
39395 ** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
39396 ** on success or an error code is something goes wrong.
39397 */
39398 static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
39399   char ac[4];
39400   put32bits(ac, val);
39401   return sqlite3OsWrite(fd, ac, 4, offset);
39402 }
39403
39404 /*
39405 ** Unlock the database file to level eLock, which must be either NO_LOCK
39406 ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
39407 ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
39408 **
39409 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
39410 ** called, do not modify it. See the comment above the #define of 
39411 ** UNKNOWN_LOCK for an explanation of this.
39412 */
39413 static int pagerUnlockDb(Pager *pPager, int eLock){
39414   int rc = SQLITE_OK;
39415
39416   assert( !pPager->exclusiveMode || pPager->eLock==eLock );
39417   assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
39418   assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
39419   if( isOpen(pPager->fd) ){
39420     assert( pPager->eLock>=eLock );
39421     rc = sqlite3OsUnlock(pPager->fd, eLock);
39422     if( pPager->eLock!=UNKNOWN_LOCK ){
39423       pPager->eLock = (u8)eLock;
39424     }
39425     IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
39426   }
39427   return rc;
39428 }
39429
39430 /*
39431 ** Lock the database file to level eLock, which must be either SHARED_LOCK,
39432 ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
39433 ** Pager.eLock variable to the new locking state. 
39434 **
39435 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is 
39436 ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK. 
39437 ** See the comment above the #define of UNKNOWN_LOCK for an explanation 
39438 ** of this.
39439 */
39440 static int pagerLockDb(Pager *pPager, int eLock){
39441   int rc = SQLITE_OK;
39442
39443   assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
39444   if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
39445     rc = sqlite3OsLock(pPager->fd, eLock);
39446     if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
39447       pPager->eLock = (u8)eLock;
39448       IOTRACE(("LOCK %p %d\n", pPager, eLock))
39449     }
39450   }
39451   return rc;
39452 }
39453
39454 /*
39455 ** This function determines whether or not the atomic-write optimization
39456 ** can be used with this pager. The optimization can be used if:
39457 **
39458 **  (a) the value returned by OsDeviceCharacteristics() indicates that
39459 **      a database page may be written atomically, and
39460 **  (b) the value returned by OsSectorSize() is less than or equal
39461 **      to the page size.
39462 **
39463 ** The optimization is also always enabled for temporary files. It is
39464 ** an error to call this function if pPager is opened on an in-memory
39465 ** database.
39466 **
39467 ** If the optimization cannot be used, 0 is returned. If it can be used,
39468 ** then the value returned is the size of the journal file when it
39469 ** contains rollback data for exactly one page.
39470 */
39471 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
39472 static int jrnlBufferSize(Pager *pPager){
39473   assert( !MEMDB );
39474   if( !pPager->tempFile ){
39475     int dc;                           /* Device characteristics */
39476     int nSector;                      /* Sector size */
39477     int szPage;                       /* Page size */
39478
39479     assert( isOpen(pPager->fd) );
39480     dc = sqlite3OsDeviceCharacteristics(pPager->fd);
39481     nSector = pPager->sectorSize;
39482     szPage = pPager->pageSize;
39483
39484     assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
39485     assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
39486     if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
39487       return 0;
39488     }
39489   }
39490
39491   return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
39492 }
39493 #endif
39494
39495 /*
39496 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
39497 ** on the cache using a hash function.  This is used for testing
39498 ** and debugging only.
39499 */
39500 #ifdef SQLITE_CHECK_PAGES
39501 /*
39502 ** Return a 32-bit hash of the page data for pPage.
39503 */
39504 static u32 pager_datahash(int nByte, unsigned char *pData){
39505   u32 hash = 0;
39506   int i;
39507   for(i=0; i<nByte; i++){
39508     hash = (hash*1039) + pData[i];
39509   }
39510   return hash;
39511 }
39512 static u32 pager_pagehash(PgHdr *pPage){
39513   return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
39514 }
39515 static void pager_set_pagehash(PgHdr *pPage){
39516   pPage->pageHash = pager_pagehash(pPage);
39517 }
39518
39519 /*
39520 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
39521 ** is defined, and NDEBUG is not defined, an assert() statement checks
39522 ** that the page is either dirty or still matches the calculated page-hash.
39523 */
39524 #define CHECK_PAGE(x) checkPage(x)
39525 static void checkPage(PgHdr *pPg){
39526   Pager *pPager = pPg->pPager;
39527   assert( pPager->eState!=PAGER_ERROR );
39528   assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
39529 }
39530
39531 #else
39532 #define pager_datahash(X,Y)  0
39533 #define pager_pagehash(X)  0
39534 #define pager_set_pagehash(X)
39535 #define CHECK_PAGE(x)
39536 #endif  /* SQLITE_CHECK_PAGES */
39537
39538 /*
39539 ** When this is called the journal file for pager pPager must be open.
39540 ** This function attempts to read a master journal file name from the 
39541 ** end of the file and, if successful, copies it into memory supplied 
39542 ** by the caller. See comments above writeMasterJournal() for the format
39543 ** used to store a master journal file name at the end of a journal file.
39544 **
39545 ** zMaster must point to a buffer of at least nMaster bytes allocated by
39546 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
39547 ** enough space to write the master journal name). If the master journal
39548 ** name in the journal is longer than nMaster bytes (including a
39549 ** nul-terminator), then this is handled as if no master journal name
39550 ** were present in the journal.
39551 **
39552 ** If a master journal file name is present at the end of the journal
39553 ** file, then it is copied into the buffer pointed to by zMaster. A
39554 ** nul-terminator byte is appended to the buffer following the master
39555 ** journal file name.
39556 **
39557 ** If it is determined that no master journal file name is present 
39558 ** zMaster[0] is set to 0 and SQLITE_OK returned.
39559 **
39560 ** If an error occurs while reading from the journal file, an SQLite
39561 ** error code is returned.
39562 */
39563 static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
39564   int rc;                    /* Return code */
39565   u32 len;                   /* Length in bytes of master journal name */
39566   i64 szJ;                   /* Total size in bytes of journal file pJrnl */
39567   u32 cksum;                 /* MJ checksum value read from journal */
39568   u32 u;                     /* Unsigned loop counter */
39569   unsigned char aMagic[8];   /* A buffer to hold the magic header */
39570   zMaster[0] = '\0';
39571
39572   if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
39573    || szJ<16
39574    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
39575    || len>=nMaster 
39576    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
39577    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
39578    || memcmp(aMagic, aJournalMagic, 8)
39579    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
39580   ){
39581     return rc;
39582   }
39583
39584   /* See if the checksum matches the master journal name */
39585   for(u=0; u<len; u++){
39586     cksum -= zMaster[u];
39587   }
39588   if( cksum ){
39589     /* If the checksum doesn't add up, then one or more of the disk sectors
39590     ** containing the master journal filename is corrupted. This means
39591     ** definitely roll back, so just return SQLITE_OK and report a (nul)
39592     ** master-journal filename.
39593     */
39594     len = 0;
39595   }
39596   zMaster[len] = '\0';
39597    
39598   return SQLITE_OK;
39599 }
39600
39601 /*
39602 ** Return the offset of the sector boundary at or immediately 
39603 ** following the value in pPager->journalOff, assuming a sector 
39604 ** size of pPager->sectorSize bytes.
39605 **
39606 ** i.e for a sector size of 512:
39607 **
39608 **   Pager.journalOff          Return value
39609 **   ---------------------------------------
39610 **   0                         0
39611 **   512                       512
39612 **   100                       512
39613 **   2000                      2048
39614 ** 
39615 */
39616 static i64 journalHdrOffset(Pager *pPager){
39617   i64 offset = 0;
39618   i64 c = pPager->journalOff;
39619   if( c ){
39620     offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
39621   }
39622   assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
39623   assert( offset>=c );
39624   assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
39625   return offset;
39626 }
39627
39628 /*
39629 ** The journal file must be open when this function is called.
39630 **
39631 ** This function is a no-op if the journal file has not been written to
39632 ** within the current transaction (i.e. if Pager.journalOff==0).
39633 **
39634 ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
39635 ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
39636 ** zero the 28-byte header at the start of the journal file. In either case, 
39637 ** if the pager is not in no-sync mode, sync the journal file immediately 
39638 ** after writing or truncating it.
39639 **
39640 ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
39641 ** following the truncation or zeroing described above the size of the 
39642 ** journal file in bytes is larger than this value, then truncate the
39643 ** journal file to Pager.journalSizeLimit bytes. The journal file does
39644 ** not need to be synced following this operation.
39645 **
39646 ** If an IO error occurs, abandon processing and return the IO error code.
39647 ** Otherwise, return SQLITE_OK.
39648 */
39649 static int zeroJournalHdr(Pager *pPager, int doTruncate){
39650   int rc = SQLITE_OK;                               /* Return code */
39651   assert( isOpen(pPager->jfd) );
39652   if( pPager->journalOff ){
39653     const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
39654
39655     IOTRACE(("JZEROHDR %p\n", pPager))
39656     if( doTruncate || iLimit==0 ){
39657       rc = sqlite3OsTruncate(pPager->jfd, 0);
39658     }else{
39659       static const char zeroHdr[28] = {0};
39660       rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
39661     }
39662     if( rc==SQLITE_OK && !pPager->noSync ){
39663       rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
39664     }
39665
39666     /* At this point the transaction is committed but the write lock 
39667     ** is still held on the file. If there is a size limit configured for 
39668     ** the persistent journal and the journal file currently consumes more
39669     ** space than that limit allows for, truncate it now. There is no need
39670     ** to sync the file following this operation.
39671     */
39672     if( rc==SQLITE_OK && iLimit>0 ){
39673       i64 sz;
39674       rc = sqlite3OsFileSize(pPager->jfd, &sz);
39675       if( rc==SQLITE_OK && sz>iLimit ){
39676         rc = sqlite3OsTruncate(pPager->jfd, iLimit);
39677       }
39678     }
39679   }
39680   return rc;
39681 }
39682
39683 /*
39684 ** The journal file must be open when this routine is called. A journal
39685 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
39686 ** current location.
39687 **
39688 ** The format for the journal header is as follows:
39689 ** - 8 bytes: Magic identifying journal format.
39690 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
39691 ** - 4 bytes: Random number used for page hash.
39692 ** - 4 bytes: Initial database page count.
39693 ** - 4 bytes: Sector size used by the process that wrote this journal.
39694 ** - 4 bytes: Database page size.
39695 ** 
39696 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
39697 */
39698 static int writeJournalHdr(Pager *pPager){
39699   int rc = SQLITE_OK;                 /* Return code */
39700   char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
39701   u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
39702   u32 nWrite;                         /* Bytes of header sector written */
39703   int ii;                             /* Loop counter */
39704
39705   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
39706
39707   if( nHeader>JOURNAL_HDR_SZ(pPager) ){
39708     nHeader = JOURNAL_HDR_SZ(pPager);
39709   }
39710
39711   /* If there are active savepoints and any of them were created 
39712   ** since the most recent journal header was written, update the 
39713   ** PagerSavepoint.iHdrOffset fields now.
39714   */
39715   for(ii=0; ii<pPager->nSavepoint; ii++){
39716     if( pPager->aSavepoint[ii].iHdrOffset==0 ){
39717       pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
39718     }
39719   }
39720
39721   pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
39722
39723   /* 
39724   ** Write the nRec Field - the number of page records that follow this
39725   ** journal header. Normally, zero is written to this value at this time.
39726   ** After the records are added to the journal (and the journal synced, 
39727   ** if in full-sync mode), the zero is overwritten with the true number
39728   ** of records (see syncJournal()).
39729   **
39730   ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
39731   ** reading the journal this value tells SQLite to assume that the
39732   ** rest of the journal file contains valid page records. This assumption
39733   ** is dangerous, as if a failure occurred whilst writing to the journal
39734   ** file it may contain some garbage data. There are two scenarios
39735   ** where this risk can be ignored:
39736   **
39737   **   * When the pager is in no-sync mode. Corruption can follow a
39738   **     power failure in this case anyway.
39739   **
39740   **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
39741   **     that garbage data is never appended to the journal file.
39742   */
39743   assert( isOpen(pPager->fd) || pPager->noSync );
39744   if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
39745    || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND) 
39746   ){
39747     memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
39748     put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
39749   }else{
39750     memset(zHeader, 0, sizeof(aJournalMagic)+4);
39751   }
39752
39753   /* The random check-hash initializer */ 
39754   sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
39755   put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
39756   /* The initial database size */
39757   put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
39758   /* The assumed sector size for this process */
39759   put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
39760
39761   /* The page size */
39762   put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
39763
39764   /* Initializing the tail of the buffer is not necessary.  Everything
39765   ** works find if the following memset() is omitted.  But initializing
39766   ** the memory prevents valgrind from complaining, so we are willing to
39767   ** take the performance hit.
39768   */
39769   memset(&zHeader[sizeof(aJournalMagic)+20], 0,
39770          nHeader-(sizeof(aJournalMagic)+20));
39771
39772   /* In theory, it is only necessary to write the 28 bytes that the 
39773   ** journal header consumes to the journal file here. Then increment the 
39774   ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next 
39775   ** record is written to the following sector (leaving a gap in the file
39776   ** that will be implicitly filled in by the OS).
39777   **
39778   ** However it has been discovered that on some systems this pattern can 
39779   ** be significantly slower than contiguously writing data to the file,
39780   ** even if that means explicitly writing data to the block of 
39781   ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
39782   ** is done. 
39783   **
39784   ** The loop is required here in case the sector-size is larger than the 
39785   ** database page size. Since the zHeader buffer is only Pager.pageSize
39786   ** bytes in size, more than one call to sqlite3OsWrite() may be required
39787   ** to populate the entire journal header sector.
39788   */ 
39789   for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
39790     IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
39791     rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
39792     assert( pPager->journalHdr <= pPager->journalOff );
39793     pPager->journalOff += nHeader;
39794   }
39795
39796   return rc;
39797 }
39798
39799 /*
39800 ** The journal file must be open when this is called. A journal header file
39801 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
39802 ** file. The current location in the journal file is given by
39803 ** pPager->journalOff. See comments above function writeJournalHdr() for
39804 ** a description of the journal header format.
39805 **
39806 ** If the header is read successfully, *pNRec is set to the number of
39807 ** page records following this header and *pDbSize is set to the size of the
39808 ** database before the transaction began, in pages. Also, pPager->cksumInit
39809 ** is set to the value read from the journal header. SQLITE_OK is returned
39810 ** in this case.
39811 **
39812 ** If the journal header file appears to be corrupted, SQLITE_DONE is
39813 ** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
39814 ** cannot be read from the journal file an error code is returned.
39815 */
39816 static int readJournalHdr(
39817   Pager *pPager,               /* Pager object */
39818   int isHot,
39819   i64 journalSize,             /* Size of the open journal file in bytes */
39820   u32 *pNRec,                  /* OUT: Value read from the nRec field */
39821   u32 *pDbSize                 /* OUT: Value of original database size field */
39822 ){
39823   int rc;                      /* Return code */
39824   unsigned char aMagic[8];     /* A buffer to hold the magic header */
39825   i64 iHdrOff;                 /* Offset of journal header being read */
39826
39827   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
39828
39829   /* Advance Pager.journalOff to the start of the next sector. If the
39830   ** journal file is too small for there to be a header stored at this
39831   ** point, return SQLITE_DONE.
39832   */
39833   pPager->journalOff = journalHdrOffset(pPager);
39834   if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
39835     return SQLITE_DONE;
39836   }
39837   iHdrOff = pPager->journalOff;
39838
39839   /* Read in the first 8 bytes of the journal header. If they do not match
39840   ** the  magic string found at the start of each journal header, return
39841   ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
39842   ** proceed.
39843   */
39844   if( isHot || iHdrOff!=pPager->journalHdr ){
39845     rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
39846     if( rc ){
39847       return rc;
39848     }
39849     if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
39850       return SQLITE_DONE;
39851     }
39852   }
39853
39854   /* Read the first three 32-bit fields of the journal header: The nRec
39855   ** field, the checksum-initializer and the database size at the start
39856   ** of the transaction. Return an error code if anything goes wrong.
39857   */
39858   if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
39859    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
39860    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
39861   ){
39862     return rc;
39863   }
39864
39865   if( pPager->journalOff==0 ){
39866     u32 iPageSize;               /* Page-size field of journal header */
39867     u32 iSectorSize;             /* Sector-size field of journal header */
39868
39869     /* Read the page-size and sector-size journal header fields. */
39870     if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
39871      || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
39872     ){
39873       return rc;
39874     }
39875
39876     /* Versions of SQLite prior to 3.5.8 set the page-size field of the
39877     ** journal header to zero. In this case, assume that the Pager.pageSize
39878     ** variable is already set to the correct page size.
39879     */
39880     if( iPageSize==0 ){
39881       iPageSize = pPager->pageSize;
39882     }
39883
39884     /* Check that the values read from the page-size and sector-size fields
39885     ** are within range. To be 'in range', both values need to be a power
39886     ** of two greater than or equal to 512 or 32, and not greater than their 
39887     ** respective compile time maximum limits.
39888     */
39889     if( iPageSize<512                  || iSectorSize<32
39890      || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
39891      || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0 
39892     ){
39893       /* If the either the page-size or sector-size in the journal-header is 
39894       ** invalid, then the process that wrote the journal-header must have 
39895       ** crashed before the header was synced. In this case stop reading 
39896       ** the journal file here.
39897       */
39898       return SQLITE_DONE;
39899     }
39900
39901     /* Update the page-size to match the value read from the journal. 
39902     ** Use a testcase() macro to make sure that malloc failure within 
39903     ** PagerSetPagesize() is tested.
39904     */
39905     rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
39906     testcase( rc!=SQLITE_OK );
39907
39908     /* Update the assumed sector-size to match the value used by 
39909     ** the process that created this journal. If this journal was
39910     ** created by a process other than this one, then this routine
39911     ** is being called from within pager_playback(). The local value
39912     ** of Pager.sectorSize is restored at the end of that routine.
39913     */
39914     pPager->sectorSize = iSectorSize;
39915   }
39916
39917   pPager->journalOff += JOURNAL_HDR_SZ(pPager);
39918   return rc;
39919 }
39920
39921
39922 /*
39923 ** Write the supplied master journal name into the journal file for pager
39924 ** pPager at the current location. The master journal name must be the last
39925 ** thing written to a journal file. If the pager is in full-sync mode, the
39926 ** journal file descriptor is advanced to the next sector boundary before
39927 ** anything is written. The format is:
39928 **
39929 **   + 4 bytes: PAGER_MJ_PGNO.
39930 **   + N bytes: Master journal filename in utf-8.
39931 **   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
39932 **   + 4 bytes: Master journal name checksum.
39933 **   + 8 bytes: aJournalMagic[].
39934 **
39935 ** The master journal page checksum is the sum of the bytes in the master
39936 ** journal name, where each byte is interpreted as a signed 8-bit integer.
39937 **
39938 ** If zMaster is a NULL pointer (occurs for a single database transaction), 
39939 ** this call is a no-op.
39940 */
39941 static int writeMasterJournal(Pager *pPager, const char *zMaster){
39942   int rc;                          /* Return code */
39943   int nMaster;                     /* Length of string zMaster */
39944   i64 iHdrOff;                     /* Offset of header in journal file */
39945   i64 jrnlSize;                    /* Size of journal file on disk */
39946   u32 cksum = 0;                   /* Checksum of string zMaster */
39947
39948   assert( pPager->setMaster==0 );
39949   assert( !pagerUseWal(pPager) );
39950
39951   if( !zMaster 
39952    || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
39953    || pPager->journalMode==PAGER_JOURNALMODE_OFF 
39954   ){
39955     return SQLITE_OK;
39956   }
39957   pPager->setMaster = 1;
39958   assert( isOpen(pPager->jfd) );
39959   assert( pPager->journalHdr <= pPager->journalOff );
39960
39961   /* Calculate the length in bytes and the checksum of zMaster */
39962   for(nMaster=0; zMaster[nMaster]; nMaster++){
39963     cksum += zMaster[nMaster];
39964   }
39965
39966   /* If in full-sync mode, advance to the next disk sector before writing
39967   ** the master journal name. This is in case the previous page written to
39968   ** the journal has already been synced.
39969   */
39970   if( pPager->fullSync ){
39971     pPager->journalOff = journalHdrOffset(pPager);
39972   }
39973   iHdrOff = pPager->journalOff;
39974
39975   /* Write the master journal data to the end of the journal file. If
39976   ** an error occurs, return the error code to the caller.
39977   */
39978   if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
39979    || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
39980    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
39981    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
39982    || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
39983   ){
39984     return rc;
39985   }
39986   pPager->journalOff += (nMaster+20);
39987
39988   /* If the pager is in peristent-journal mode, then the physical 
39989   ** journal-file may extend past the end of the master-journal name
39990   ** and 8 bytes of magic data just written to the file. This is 
39991   ** dangerous because the code to rollback a hot-journal file
39992   ** will not be able to find the master-journal name to determine 
39993   ** whether or not the journal is hot. 
39994   **
39995   ** Easiest thing to do in this scenario is to truncate the journal 
39996   ** file to the required size.
39997   */ 
39998   if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
39999    && jrnlSize>pPager->journalOff
40000   ){
40001     rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
40002   }
40003   return rc;
40004 }
40005
40006 /*
40007 ** Find a page in the hash table given its page number. Return
40008 ** a pointer to the page or NULL if the requested page is not 
40009 ** already in memory.
40010 */
40011 static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
40012   PgHdr *p;                         /* Return value */
40013
40014   /* It is not possible for a call to PcacheFetch() with createFlag==0 to
40015   ** fail, since no attempt to allocate dynamic memory will be made.
40016   */
40017   (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
40018   return p;
40019 }
40020
40021 /*
40022 ** Discard the entire contents of the in-memory page-cache.
40023 */
40024 static void pager_reset(Pager *pPager){
40025   sqlite3BackupRestart(pPager->pBackup);
40026   sqlite3PcacheClear(pPager->pPCache);
40027 }
40028
40029 /*
40030 ** Free all structures in the Pager.aSavepoint[] array and set both
40031 ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
40032 ** if it is open and the pager is not in exclusive mode.
40033 */
40034 static void releaseAllSavepoints(Pager *pPager){
40035   int ii;               /* Iterator for looping through Pager.aSavepoint */
40036   for(ii=0; ii<pPager->nSavepoint; ii++){
40037     sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
40038   }
40039   if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
40040     sqlite3OsClose(pPager->sjfd);
40041   }
40042   sqlite3_free(pPager->aSavepoint);
40043   pPager->aSavepoint = 0;
40044   pPager->nSavepoint = 0;
40045   pPager->nSubRec = 0;
40046 }
40047
40048 /*
40049 ** Set the bit number pgno in the PagerSavepoint.pInSavepoint 
40050 ** bitvecs of all open savepoints. Return SQLITE_OK if successful
40051 ** or SQLITE_NOMEM if a malloc failure occurs.
40052 */
40053 static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
40054   int ii;                   /* Loop counter */
40055   int rc = SQLITE_OK;       /* Result code */
40056
40057   for(ii=0; ii<pPager->nSavepoint; ii++){
40058     PagerSavepoint *p = &pPager->aSavepoint[ii];
40059     if( pgno<=p->nOrig ){
40060       rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
40061       testcase( rc==SQLITE_NOMEM );
40062       assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
40063     }
40064   }
40065   return rc;
40066 }
40067
40068 /*
40069 ** This function is a no-op if the pager is in exclusive mode and not
40070 ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
40071 ** state.
40072 **
40073 ** If the pager is not in exclusive-access mode, the database file is
40074 ** completely unlocked. If the file is unlocked and the file-system does
40075 ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
40076 ** closed (if it is open).
40077 **
40078 ** If the pager is in ERROR state when this function is called, the 
40079 ** contents of the pager cache are discarded before switching back to 
40080 ** the OPEN state. Regardless of whether the pager is in exclusive-mode
40081 ** or not, any journal file left in the file-system will be treated
40082 ** as a hot-journal and rolled back the next time a read-transaction
40083 ** is opened (by this or by any other connection).
40084 */
40085 static void pager_unlock(Pager *pPager){
40086
40087   assert( pPager->eState==PAGER_READER 
40088        || pPager->eState==PAGER_OPEN 
40089        || pPager->eState==PAGER_ERROR 
40090   );
40091
40092   sqlite3BitvecDestroy(pPager->pInJournal);
40093   pPager->pInJournal = 0;
40094   releaseAllSavepoints(pPager);
40095
40096   if( pagerUseWal(pPager) ){
40097     assert( !isOpen(pPager->jfd) );
40098     sqlite3WalEndReadTransaction(pPager->pWal);
40099     pPager->eState = PAGER_OPEN;
40100   }else if( !pPager->exclusiveMode ){
40101     int rc;                       /* Error code returned by pagerUnlockDb() */
40102     int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
40103
40104     /* If the operating system support deletion of open files, then
40105     ** close the journal file when dropping the database lock.  Otherwise
40106     ** another connection with journal_mode=delete might delete the file
40107     ** out from under us.
40108     */
40109     assert( (PAGER_JOURNALMODE_MEMORY   & 5)!=1 );
40110     assert( (PAGER_JOURNALMODE_OFF      & 5)!=1 );
40111     assert( (PAGER_JOURNALMODE_WAL      & 5)!=1 );
40112     assert( (PAGER_JOURNALMODE_DELETE   & 5)!=1 );
40113     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
40114     assert( (PAGER_JOURNALMODE_PERSIST  & 5)==1 );
40115     if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
40116      || 1!=(pPager->journalMode & 5)
40117     ){
40118       sqlite3OsClose(pPager->jfd);
40119     }
40120
40121     /* If the pager is in the ERROR state and the call to unlock the database
40122     ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
40123     ** above the #define for UNKNOWN_LOCK for an explanation of why this
40124     ** is necessary.
40125     */
40126     rc = pagerUnlockDb(pPager, NO_LOCK);
40127     if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
40128       pPager->eLock = UNKNOWN_LOCK;
40129     }
40130
40131     /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
40132     ** without clearing the error code. This is intentional - the error
40133     ** code is cleared and the cache reset in the block below.
40134     */
40135     assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
40136     pPager->changeCountDone = 0;
40137     pPager->eState = PAGER_OPEN;
40138   }
40139
40140   /* If Pager.errCode is set, the contents of the pager cache cannot be
40141   ** trusted. Now that there are no outstanding references to the pager,
40142   ** it can safely move back to PAGER_OPEN state. This happens in both
40143   ** normal and exclusive-locking mode.
40144   */
40145   if( pPager->errCode ){
40146     assert( !MEMDB );
40147     pager_reset(pPager);
40148     pPager->changeCountDone = pPager->tempFile;
40149     pPager->eState = PAGER_OPEN;
40150     pPager->errCode = SQLITE_OK;
40151   }
40152
40153   pPager->journalOff = 0;
40154   pPager->journalHdr = 0;
40155   pPager->setMaster = 0;
40156 }
40157
40158 /*
40159 ** This function is called whenever an IOERR or FULL error that requires
40160 ** the pager to transition into the ERROR state may ahve occurred.
40161 ** The first argument is a pointer to the pager structure, the second 
40162 ** the error-code about to be returned by a pager API function. The 
40163 ** value returned is a copy of the second argument to this function. 
40164 **
40165 ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
40166 ** IOERR sub-codes, the pager enters the ERROR state and the error code
40167 ** is stored in Pager.errCode. While the pager remains in the ERROR state,
40168 ** all major API calls on the Pager will immediately return Pager.errCode.
40169 **
40170 ** The ERROR state indicates that the contents of the pager-cache 
40171 ** cannot be trusted. This state can be cleared by completely discarding 
40172 ** the contents of the pager-cache. If a transaction was active when
40173 ** the persistent error occurred, then the rollback journal may need
40174 ** to be replayed to restore the contents of the database file (as if
40175 ** it were a hot-journal).
40176 */
40177 static int pager_error(Pager *pPager, int rc){
40178   int rc2 = rc & 0xff;
40179   assert( rc==SQLITE_OK || !MEMDB );
40180   assert(
40181        pPager->errCode==SQLITE_FULL ||
40182        pPager->errCode==SQLITE_OK ||
40183        (pPager->errCode & 0xff)==SQLITE_IOERR
40184   );
40185   if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
40186     pPager->errCode = rc;
40187     pPager->eState = PAGER_ERROR;
40188   }
40189   return rc;
40190 }
40191
40192 static int pager_truncate(Pager *pPager, Pgno nPage);
40193
40194 /*
40195 ** This routine ends a transaction. A transaction is usually ended by 
40196 ** either a COMMIT or a ROLLBACK operation. This routine may be called 
40197 ** after rollback of a hot-journal, or if an error occurs while opening
40198 ** the journal file or writing the very first journal-header of a
40199 ** database transaction.
40200 ** 
40201 ** This routine is never called in PAGER_ERROR state. If it is called
40202 ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
40203 ** exclusive than a RESERVED lock, it is a no-op.
40204 **
40205 ** Otherwise, any active savepoints are released.
40206 **
40207 ** If the journal file is open, then it is "finalized". Once a journal 
40208 ** file has been finalized it is not possible to use it to roll back a 
40209 ** transaction. Nor will it be considered to be a hot-journal by this
40210 ** or any other database connection. Exactly how a journal is finalized
40211 ** depends on whether or not the pager is running in exclusive mode and
40212 ** the current journal-mode (Pager.journalMode value), as follows:
40213 **
40214 **   journalMode==MEMORY
40215 **     Journal file descriptor is simply closed. This destroys an 
40216 **     in-memory journal.
40217 **
40218 **   journalMode==TRUNCATE
40219 **     Journal file is truncated to zero bytes in size.
40220 **
40221 **   journalMode==PERSIST
40222 **     The first 28 bytes of the journal file are zeroed. This invalidates
40223 **     the first journal header in the file, and hence the entire journal
40224 **     file. An invalid journal file cannot be rolled back.
40225 **
40226 **   journalMode==DELETE
40227 **     The journal file is closed and deleted using sqlite3OsDelete().
40228 **
40229 **     If the pager is running in exclusive mode, this method of finalizing
40230 **     the journal file is never used. Instead, if the journalMode is
40231 **     DELETE and the pager is in exclusive mode, the method described under
40232 **     journalMode==PERSIST is used instead.
40233 **
40234 ** After the journal is finalized, the pager moves to PAGER_READER state.
40235 ** If running in non-exclusive rollback mode, the lock on the file is 
40236 ** downgraded to a SHARED_LOCK.
40237 **
40238 ** SQLITE_OK is returned if no error occurs. If an error occurs during
40239 ** any of the IO operations to finalize the journal file or unlock the
40240 ** database then the IO error code is returned to the user. If the 
40241 ** operation to finalize the journal file fails, then the code still
40242 ** tries to unlock the database file if not in exclusive mode. If the
40243 ** unlock operation fails as well, then the first error code related
40244 ** to the first error encountered (the journal finalization one) is
40245 ** returned.
40246 */
40247 static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
40248   int rc = SQLITE_OK;      /* Error code from journal finalization operation */
40249   int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
40250
40251   /* Do nothing if the pager does not have an open write transaction
40252   ** or at least a RESERVED lock. This function may be called when there
40253   ** is no write-transaction active but a RESERVED or greater lock is
40254   ** held under two circumstances:
40255   **
40256   **   1. After a successful hot-journal rollback, it is called with
40257   **      eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
40258   **
40259   **   2. If a connection with locking_mode=exclusive holding an EXCLUSIVE 
40260   **      lock switches back to locking_mode=normal and then executes a
40261   **      read-transaction, this function is called with eState==PAGER_READER 
40262   **      and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
40263   */
40264   assert( assert_pager_state(pPager) );
40265   assert( pPager->eState!=PAGER_ERROR );
40266   if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
40267     return SQLITE_OK;
40268   }
40269
40270   releaseAllSavepoints(pPager);
40271   assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
40272   if( isOpen(pPager->jfd) ){
40273     assert( !pagerUseWal(pPager) );
40274
40275     /* Finalize the journal file. */
40276     if( sqlite3IsMemJournal(pPager->jfd) ){
40277       assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
40278       sqlite3OsClose(pPager->jfd);
40279     }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
40280       if( pPager->journalOff==0 ){
40281         rc = SQLITE_OK;
40282       }else{
40283         rc = sqlite3OsTruncate(pPager->jfd, 0);
40284       }
40285       pPager->journalOff = 0;
40286     }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
40287       || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
40288     ){
40289       rc = zeroJournalHdr(pPager, hasMaster);
40290       pPager->journalOff = 0;
40291     }else{
40292       /* This branch may be executed with Pager.journalMode==MEMORY if
40293       ** a hot-journal was just rolled back. In this case the journal
40294       ** file should be closed and deleted. If this connection writes to
40295       ** the database file, it will do so using an in-memory journal. 
40296       */
40297       int bDelete = (!pPager->tempFile && sqlite3JournalExists(pPager->jfd));
40298       assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE 
40299            || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
40300            || pPager->journalMode==PAGER_JOURNALMODE_WAL 
40301       );
40302       sqlite3OsClose(pPager->jfd);
40303       if( bDelete ){
40304         rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
40305       }
40306     }
40307   }
40308
40309 #ifdef SQLITE_CHECK_PAGES
40310   sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
40311   if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
40312     PgHdr *p = pager_lookup(pPager, 1);
40313     if( p ){
40314       p->pageHash = 0;
40315       sqlite3PagerUnref(p);
40316     }
40317   }
40318 #endif
40319
40320   sqlite3BitvecDestroy(pPager->pInJournal);
40321   pPager->pInJournal = 0;
40322   pPager->nRec = 0;
40323   sqlite3PcacheCleanAll(pPager->pPCache);
40324   sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
40325
40326   if( pagerUseWal(pPager) ){
40327     /* Drop the WAL write-lock, if any. Also, if the connection was in 
40328     ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE 
40329     ** lock held on the database file.
40330     */
40331     rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
40332     assert( rc2==SQLITE_OK );
40333   }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
40334     /* This branch is taken when committing a transaction in rollback-journal
40335     ** mode if the database file on disk is larger than the database image.
40336     ** At this point the journal has been finalized and the transaction 
40337     ** successfully committed, but the EXCLUSIVE lock is still held on the
40338     ** file. So it is safe to truncate the database file to its minimum
40339     ** required size.  */
40340     assert( pPager->eLock==EXCLUSIVE_LOCK );
40341     rc = pager_truncate(pPager, pPager->dbSize);
40342   }
40343
40344   if( !pPager->exclusiveMode 
40345    && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
40346   ){
40347     rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
40348     pPager->changeCountDone = 0;
40349   }
40350   pPager->eState = PAGER_READER;
40351   pPager->setMaster = 0;
40352
40353   return (rc==SQLITE_OK?rc2:rc);
40354 }
40355
40356 /*
40357 ** Execute a rollback if a transaction is active and unlock the 
40358 ** database file. 
40359 **
40360 ** If the pager has already entered the ERROR state, do not attempt 
40361 ** the rollback at this time. Instead, pager_unlock() is called. The
40362 ** call to pager_unlock() will discard all in-memory pages, unlock
40363 ** the database file and move the pager back to OPEN state. If this 
40364 ** means that there is a hot-journal left in the file-system, the next 
40365 ** connection to obtain a shared lock on the pager (which may be this one) 
40366 ** will roll it back.
40367 **
40368 ** If the pager has not already entered the ERROR state, but an IO or
40369 ** malloc error occurs during a rollback, then this will itself cause 
40370 ** the pager to enter the ERROR state. Which will be cleared by the
40371 ** call to pager_unlock(), as described above.
40372 */
40373 static void pagerUnlockAndRollback(Pager *pPager){
40374   if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
40375     assert( assert_pager_state(pPager) );
40376     if( pPager->eState>=PAGER_WRITER_LOCKED ){
40377       sqlite3BeginBenignMalloc();
40378       sqlite3PagerRollback(pPager);
40379       sqlite3EndBenignMalloc();
40380     }else if( !pPager->exclusiveMode ){
40381       assert( pPager->eState==PAGER_READER );
40382       pager_end_transaction(pPager, 0, 0);
40383     }
40384   }
40385   pager_unlock(pPager);
40386 }
40387
40388 /*
40389 ** Parameter aData must point to a buffer of pPager->pageSize bytes
40390 ** of data. Compute and return a checksum based ont the contents of the 
40391 ** page of data and the current value of pPager->cksumInit.
40392 **
40393 ** This is not a real checksum. It is really just the sum of the 
40394 ** random initial value (pPager->cksumInit) and every 200th byte
40395 ** of the page data, starting with byte offset (pPager->pageSize%200).
40396 ** Each byte is interpreted as an 8-bit unsigned integer.
40397 **
40398 ** Changing the formula used to compute this checksum results in an
40399 ** incompatible journal file format.
40400 **
40401 ** If journal corruption occurs due to a power failure, the most likely 
40402 ** scenario is that one end or the other of the record will be changed. 
40403 ** It is much less likely that the two ends of the journal record will be
40404 ** correct and the middle be corrupt.  Thus, this "checksum" scheme,
40405 ** though fast and simple, catches the mostly likely kind of corruption.
40406 */
40407 static u32 pager_cksum(Pager *pPager, const u8 *aData){
40408   u32 cksum = pPager->cksumInit;         /* Checksum value to return */
40409   int i = pPager->pageSize-200;          /* Loop counter */
40410   while( i>0 ){
40411     cksum += aData[i];
40412     i -= 200;
40413   }
40414   return cksum;
40415 }
40416
40417 /*
40418 ** Report the current page size and number of reserved bytes back
40419 ** to the codec.
40420 */
40421 #ifdef SQLITE_HAS_CODEC
40422 static void pagerReportSize(Pager *pPager){
40423   if( pPager->xCodecSizeChng ){
40424     pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
40425                            (int)pPager->nReserve);
40426   }
40427 }
40428 #else
40429 # define pagerReportSize(X)     /* No-op if we do not support a codec */
40430 #endif
40431
40432 /*
40433 ** Read a single page from either the journal file (if isMainJrnl==1) or
40434 ** from the sub-journal (if isMainJrnl==0) and playback that page.
40435 ** The page begins at offset *pOffset into the file. The *pOffset
40436 ** value is increased to the start of the next page in the journal.
40437 **
40438 ** The main rollback journal uses checksums - the statement journal does 
40439 ** not.
40440 **
40441 ** If the page number of the page record read from the (sub-)journal file
40442 ** is greater than the current value of Pager.dbSize, then playback is
40443 ** skipped and SQLITE_OK is returned.
40444 **
40445 ** If pDone is not NULL, then it is a record of pages that have already
40446 ** been played back.  If the page at *pOffset has already been played back
40447 ** (if the corresponding pDone bit is set) then skip the playback.
40448 ** Make sure the pDone bit corresponding to the *pOffset page is set
40449 ** prior to returning.
40450 **
40451 ** If the page record is successfully read from the (sub-)journal file
40452 ** and played back, then SQLITE_OK is returned. If an IO error occurs
40453 ** while reading the record from the (sub-)journal file or while writing
40454 ** to the database file, then the IO error code is returned. If data
40455 ** is successfully read from the (sub-)journal file but appears to be
40456 ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
40457 ** two circumstances:
40458 ** 
40459 **   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
40460 **   * If the record is being rolled back from the main journal file
40461 **     and the checksum field does not match the record content.
40462 **
40463 ** Neither of these two scenarios are possible during a savepoint rollback.
40464 **
40465 ** If this is a savepoint rollback, then memory may have to be dynamically
40466 ** allocated by this function. If this is the case and an allocation fails,
40467 ** SQLITE_NOMEM is returned.
40468 */
40469 static int pager_playback_one_page(
40470   Pager *pPager,                /* The pager being played back */
40471   i64 *pOffset,                 /* Offset of record to playback */
40472   Bitvec *pDone,                /* Bitvec of pages already played back */
40473   int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
40474   int isSavepnt                 /* True for a savepoint rollback */
40475 ){
40476   int rc;
40477   PgHdr *pPg;                   /* An existing page in the cache */
40478   Pgno pgno;                    /* The page number of a page in journal */
40479   u32 cksum;                    /* Checksum used for sanity checking */
40480   char *aData;                  /* Temporary storage for the page */
40481   sqlite3_file *jfd;            /* The file descriptor for the journal file */
40482   int isSynced;                 /* True if journal page is synced */
40483
40484   assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
40485   assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
40486   assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
40487   assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
40488
40489   aData = pPager->pTmpSpace;
40490   assert( aData );         /* Temp storage must have already been allocated */
40491   assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
40492
40493   /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction 
40494   ** or savepoint rollback done at the request of the caller) or this is
40495   ** a hot-journal rollback. If it is a hot-journal rollback, the pager
40496   ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
40497   ** only reads from the main journal, not the sub-journal.
40498   */
40499   assert( pPager->eState>=PAGER_WRITER_CACHEMOD
40500        || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
40501   );
40502   assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
40503
40504   /* Read the page number and page data from the journal or sub-journal
40505   ** file. Return an error code to the caller if an IO error occurs.
40506   */
40507   jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
40508   rc = read32bits(jfd, *pOffset, &pgno);
40509   if( rc!=SQLITE_OK ) return rc;
40510   rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
40511   if( rc!=SQLITE_OK ) return rc;
40512   *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
40513
40514   /* Sanity checking on the page.  This is more important that I originally
40515   ** thought.  If a power failure occurs while the journal is being written,
40516   ** it could cause invalid data to be written into the journal.  We need to
40517   ** detect this invalid data (with high probability) and ignore it.
40518   */
40519   if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
40520     assert( !isSavepnt );
40521     return SQLITE_DONE;
40522   }
40523   if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
40524     return SQLITE_OK;
40525   }
40526   if( isMainJrnl ){
40527     rc = read32bits(jfd, (*pOffset)-4, &cksum);
40528     if( rc ) return rc;
40529     if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
40530       return SQLITE_DONE;
40531     }
40532   }
40533
40534   /* If this page has already been played by before during the current
40535   ** rollback, then don't bother to play it back again.
40536   */
40537   if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
40538     return rc;
40539   }
40540
40541   /* When playing back page 1, restore the nReserve setting
40542   */
40543   if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
40544     pPager->nReserve = ((u8*)aData)[20];
40545     pagerReportSize(pPager);
40546   }
40547
40548   /* If the pager is in CACHEMOD state, then there must be a copy of this
40549   ** page in the pager cache. In this case just update the pager cache,
40550   ** not the database file. The page is left marked dirty in this case.
40551   **
40552   ** An exception to the above rule: If the database is in no-sync mode
40553   ** and a page is moved during an incremental vacuum then the page may
40554   ** not be in the pager cache. Later: if a malloc() or IO error occurs
40555   ** during a Movepage() call, then the page may not be in the cache
40556   ** either. So the condition described in the above paragraph is not
40557   ** assert()able.
40558   **
40559   ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
40560   ** pager cache if it exists and the main file. The page is then marked 
40561   ** not dirty. Since this code is only executed in PAGER_OPEN state for
40562   ** a hot-journal rollback, it is guaranteed that the page-cache is empty
40563   ** if the pager is in OPEN state.
40564   **
40565   ** Ticket #1171:  The statement journal might contain page content that is
40566   ** different from the page content at the start of the transaction.
40567   ** This occurs when a page is changed prior to the start of a statement
40568   ** then changed again within the statement.  When rolling back such a
40569   ** statement we must not write to the original database unless we know
40570   ** for certain that original page contents are synced into the main rollback
40571   ** journal.  Otherwise, a power loss might leave modified data in the
40572   ** database file without an entry in the rollback journal that can
40573   ** restore the database to its original form.  Two conditions must be
40574   ** met before writing to the database files. (1) the database must be
40575   ** locked.  (2) we know that the original page content is fully synced
40576   ** in the main journal either because the page is not in cache or else
40577   ** the page is marked as needSync==0.
40578   **
40579   ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
40580   ** is possible to fail a statement on a database that does not yet exist.
40581   ** Do not attempt to write if database file has never been opened.
40582   */
40583   if( pagerUseWal(pPager) ){
40584     pPg = 0;
40585   }else{
40586     pPg = pager_lookup(pPager, pgno);
40587   }
40588   assert( pPg || !MEMDB );
40589   assert( pPager->eState!=PAGER_OPEN || pPg==0 );
40590   PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
40591            PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
40592            (isMainJrnl?"main-journal":"sub-journal")
40593   ));
40594   if( isMainJrnl ){
40595     isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
40596   }else{
40597     isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
40598   }
40599   if( isOpen(pPager->fd)
40600    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
40601    && isSynced
40602   ){
40603     i64 ofst = (pgno-1)*(i64)pPager->pageSize;
40604     testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
40605     assert( !pagerUseWal(pPager) );
40606     rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
40607     if( pgno>pPager->dbFileSize ){
40608       pPager->dbFileSize = pgno;
40609     }
40610     if( pPager->pBackup ){
40611       CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
40612       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
40613       CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
40614     }
40615   }else if( !isMainJrnl && pPg==0 ){
40616     /* If this is a rollback of a savepoint and data was not written to
40617     ** the database and the page is not in-memory, there is a potential
40618     ** problem. When the page is next fetched by the b-tree layer, it 
40619     ** will be read from the database file, which may or may not be 
40620     ** current. 
40621     **
40622     ** There are a couple of different ways this can happen. All are quite
40623     ** obscure. When running in synchronous mode, this can only happen 
40624     ** if the page is on the free-list at the start of the transaction, then
40625     ** populated, then moved using sqlite3PagerMovepage().
40626     **
40627     ** The solution is to add an in-memory page to the cache containing
40628     ** the data just read from the sub-journal. Mark the page as dirty 
40629     ** and if the pager requires a journal-sync, then mark the page as 
40630     ** requiring a journal-sync before it is written.
40631     */
40632     assert( isSavepnt );
40633     assert( pPager->doNotSpill==0 );
40634     pPager->doNotSpill++;
40635     rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
40636     assert( pPager->doNotSpill==1 );
40637     pPager->doNotSpill--;
40638     if( rc!=SQLITE_OK ) return rc;
40639     pPg->flags &= ~PGHDR_NEED_READ;
40640     sqlite3PcacheMakeDirty(pPg);
40641   }
40642   if( pPg ){
40643     /* No page should ever be explicitly rolled back that is in use, except
40644     ** for page 1 which is held in use in order to keep the lock on the
40645     ** database active. However such a page may be rolled back as a result
40646     ** of an internal error resulting in an automatic call to
40647     ** sqlite3PagerRollback().
40648     */
40649     void *pData;
40650     pData = pPg->pData;
40651     memcpy(pData, (u8*)aData, pPager->pageSize);
40652     pPager->xReiniter(pPg);
40653     if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
40654       /* If the contents of this page were just restored from the main 
40655       ** journal file, then its content must be as they were when the 
40656       ** transaction was first opened. In this case we can mark the page
40657       ** as clean, since there will be no need to write it out to the
40658       ** database.
40659       **
40660       ** There is one exception to this rule. If the page is being rolled
40661       ** back as part of a savepoint (or statement) rollback from an 
40662       ** unsynced portion of the main journal file, then it is not safe
40663       ** to mark the page as clean. This is because marking the page as
40664       ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
40665       ** already in the journal file (recorded in Pager.pInJournal) and
40666       ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
40667       ** again within this transaction, it will be marked as dirty but
40668       ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
40669       ** be written out into the database file before its journal file
40670       ** segment is synced. If a crash occurs during or following this,
40671       ** database corruption may ensue.
40672       */
40673       assert( !pagerUseWal(pPager) );
40674       sqlite3PcacheMakeClean(pPg);
40675     }
40676     pager_set_pagehash(pPg);
40677
40678     /* If this was page 1, then restore the value of Pager.dbFileVers.
40679     ** Do this before any decoding. */
40680     if( pgno==1 ){
40681       memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
40682     }
40683
40684     /* Decode the page just read from disk */
40685     CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
40686     sqlite3PcacheRelease(pPg);
40687   }
40688   return rc;
40689 }
40690
40691 /*
40692 ** Parameter zMaster is the name of a master journal file. A single journal
40693 ** file that referred to the master journal file has just been rolled back.
40694 ** This routine checks if it is possible to delete the master journal file,
40695 ** and does so if it is.
40696 **
40697 ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not 
40698 ** available for use within this function.
40699 **
40700 ** When a master journal file is created, it is populated with the names 
40701 ** of all of its child journals, one after another, formatted as utf-8 
40702 ** encoded text. The end of each child journal file is marked with a 
40703 ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
40704 ** file for a transaction involving two databases might be:
40705 **
40706 **   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
40707 **
40708 ** A master journal file may only be deleted once all of its child 
40709 ** journals have been rolled back.
40710 **
40711 ** This function reads the contents of the master-journal file into 
40712 ** memory and loops through each of the child journal names. For
40713 ** each child journal, it checks if:
40714 **
40715 **   * if the child journal exists, and if so
40716 **   * if the child journal contains a reference to master journal 
40717 **     file zMaster
40718 **
40719 ** If a child journal can be found that matches both of the criteria
40720 ** above, this function returns without doing anything. Otherwise, if
40721 ** no such child journal can be found, file zMaster is deleted from
40722 ** the file-system using sqlite3OsDelete().
40723 **
40724 ** If an IO error within this function, an error code is returned. This
40725 ** function allocates memory by calling sqlite3Malloc(). If an allocation
40726 ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors 
40727 ** occur, SQLITE_OK is returned.
40728 **
40729 ** TODO: This function allocates a single block of memory to load
40730 ** the entire contents of the master journal file. This could be
40731 ** a couple of kilobytes or so - potentially larger than the page 
40732 ** size.
40733 */
40734 static int pager_delmaster(Pager *pPager, const char *zMaster){
40735   sqlite3_vfs *pVfs = pPager->pVfs;
40736   int rc;                   /* Return code */
40737   sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
40738   sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
40739   char *zMasterJournal = 0; /* Contents of master journal file */
40740   i64 nMasterJournal;       /* Size of master journal file */
40741   char *zJournal;           /* Pointer to one journal within MJ file */
40742   char *zMasterPtr;         /* Space to hold MJ filename from a journal file */
40743   int nMasterPtr;           /* Amount of space allocated to zMasterPtr[] */
40744
40745   /* Allocate space for both the pJournal and pMaster file descriptors.
40746   ** If successful, open the master journal file for reading.
40747   */
40748   pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
40749   pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
40750   if( !pMaster ){
40751     rc = SQLITE_NOMEM;
40752   }else{
40753     const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
40754     rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
40755   }
40756   if( rc!=SQLITE_OK ) goto delmaster_out;
40757
40758   /* Load the entire master journal file into space obtained from
40759   ** sqlite3_malloc() and pointed to by zMasterJournal.   Also obtain
40760   ** sufficient space (in zMasterPtr) to hold the names of master
40761   ** journal files extracted from regular rollback-journals.
40762   */
40763   rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
40764   if( rc!=SQLITE_OK ) goto delmaster_out;
40765   nMasterPtr = pVfs->mxPathname+1;
40766   zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
40767   if( !zMasterJournal ){
40768     rc = SQLITE_NOMEM;
40769     goto delmaster_out;
40770   }
40771   zMasterPtr = &zMasterJournal[nMasterJournal+1];
40772   rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
40773   if( rc!=SQLITE_OK ) goto delmaster_out;
40774   zMasterJournal[nMasterJournal] = 0;
40775
40776   zJournal = zMasterJournal;
40777   while( (zJournal-zMasterJournal)<nMasterJournal ){
40778     int exists;
40779     rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
40780     if( rc!=SQLITE_OK ){
40781       goto delmaster_out;
40782     }
40783     if( exists ){
40784       /* One of the journals pointed to by the master journal exists.
40785       ** Open it and check if it points at the master journal. If
40786       ** so, return without deleting the master journal file.
40787       */
40788       int c;
40789       int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
40790       rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
40791       if( rc!=SQLITE_OK ){
40792         goto delmaster_out;
40793       }
40794
40795       rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
40796       sqlite3OsClose(pJournal);
40797       if( rc!=SQLITE_OK ){
40798         goto delmaster_out;
40799       }
40800
40801       c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
40802       if( c ){
40803         /* We have a match. Do not delete the master journal file. */
40804         goto delmaster_out;
40805       }
40806     }
40807     zJournal += (sqlite3Strlen30(zJournal)+1);
40808   }
40809  
40810   sqlite3OsClose(pMaster);
40811   rc = sqlite3OsDelete(pVfs, zMaster, 0);
40812
40813 delmaster_out:
40814   sqlite3_free(zMasterJournal);
40815   if( pMaster ){
40816     sqlite3OsClose(pMaster);
40817     assert( !isOpen(pJournal) );
40818     sqlite3_free(pMaster);
40819   }
40820   return rc;
40821 }
40822
40823
40824 /*
40825 ** This function is used to change the actual size of the database 
40826 ** file in the file-system. This only happens when committing a transaction,
40827 ** or rolling back a transaction (including rolling back a hot-journal).
40828 **
40829 ** If the main database file is not open, or the pager is not in either
40830 ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size 
40831 ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes). 
40832 ** If the file on disk is currently larger than nPage pages, then use the VFS
40833 ** xTruncate() method to truncate it.
40834 **
40835 ** Or, it might might be the case that the file on disk is smaller than 
40836 ** nPage pages. Some operating system implementations can get confused if 
40837 ** you try to truncate a file to some size that is larger than it 
40838 ** currently is, so detect this case and write a single zero byte to 
40839 ** the end of the new file instead.
40840 **
40841 ** If successful, return SQLITE_OK. If an IO error occurs while modifying
40842 ** the database file, return the error code to the caller.
40843 */
40844 static int pager_truncate(Pager *pPager, Pgno nPage){
40845   int rc = SQLITE_OK;
40846   assert( pPager->eState!=PAGER_ERROR );
40847   assert( pPager->eState!=PAGER_READER );
40848   
40849   if( isOpen(pPager->fd) 
40850    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN) 
40851   ){
40852     i64 currentSize, newSize;
40853     int szPage = pPager->pageSize;
40854     assert( pPager->eLock==EXCLUSIVE_LOCK );
40855     /* TODO: Is it safe to use Pager.dbFileSize here? */
40856     rc = sqlite3OsFileSize(pPager->fd, &currentSize);
40857     newSize = szPage*(i64)nPage;
40858     if( rc==SQLITE_OK && currentSize!=newSize ){
40859       if( currentSize>newSize ){
40860         rc = sqlite3OsTruncate(pPager->fd, newSize);
40861       }else if( (currentSize+szPage)<=newSize ){
40862         char *pTmp = pPager->pTmpSpace;
40863         memset(pTmp, 0, szPage);
40864         testcase( (newSize-szPage) == currentSize );
40865         testcase( (newSize-szPage) >  currentSize );
40866         rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
40867       }
40868       if( rc==SQLITE_OK ){
40869         pPager->dbFileSize = nPage;
40870       }
40871     }
40872   }
40873   return rc;
40874 }
40875
40876 /*
40877 ** Return a sanitized version of the sector-size of OS file pFile. The
40878 ** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
40879 */
40880 SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
40881   int iRet = sqlite3OsSectorSize(pFile);
40882   if( iRet<32 ){
40883     iRet = 512;
40884   }else if( iRet>MAX_SECTOR_SIZE ){
40885     assert( MAX_SECTOR_SIZE>=512 );
40886     iRet = MAX_SECTOR_SIZE;
40887   }
40888   return iRet;
40889 }
40890
40891 /*
40892 ** Set the value of the Pager.sectorSize variable for the given
40893 ** pager based on the value returned by the xSectorSize method
40894 ** of the open database file. The sector size will be used used 
40895 ** to determine the size and alignment of journal header and 
40896 ** master journal pointers within created journal files.
40897 **
40898 ** For temporary files the effective sector size is always 512 bytes.
40899 **
40900 ** Otherwise, for non-temporary files, the effective sector size is
40901 ** the value returned by the xSectorSize() method rounded up to 32 if
40902 ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
40903 ** is greater than MAX_SECTOR_SIZE.
40904 **
40905 ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
40906 ** the effective sector size to its minimum value (512).  The purpose of
40907 ** pPager->sectorSize is to define the "blast radius" of bytes that
40908 ** might change if a crash occurs while writing to a single byte in
40909 ** that range.  But with POWERSAFE_OVERWRITE, the blast radius is zero
40910 ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
40911 ** size.  For backwards compatibility of the rollback journal file format,
40912 ** we cannot reduce the effective sector size below 512.
40913 */
40914 static void setSectorSize(Pager *pPager){
40915   assert( isOpen(pPager->fd) || pPager->tempFile );
40916
40917   if( pPager->tempFile
40918    || (sqlite3OsDeviceCharacteristics(pPager->fd) & 
40919               SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
40920   ){
40921     /* Sector size doesn't matter for temporary files. Also, the file
40922     ** may not have been opened yet, in which case the OsSectorSize()
40923     ** call will segfault. */
40924     pPager->sectorSize = 512;
40925   }else{
40926     pPager->sectorSize = sqlite3SectorSize(pPager->fd);
40927   }
40928 }
40929
40930 /*
40931 ** Playback the journal and thus restore the database file to
40932 ** the state it was in before we started making changes.  
40933 **
40934 ** The journal file format is as follows: 
40935 **
40936 **  (1)  8 byte prefix.  A copy of aJournalMagic[].
40937 **  (2)  4 byte big-endian integer which is the number of valid page records
40938 **       in the journal.  If this value is 0xffffffff, then compute the
40939 **       number of page records from the journal size.
40940 **  (3)  4 byte big-endian integer which is the initial value for the 
40941 **       sanity checksum.
40942 **  (4)  4 byte integer which is the number of pages to truncate the
40943 **       database to during a rollback.
40944 **  (5)  4 byte big-endian integer which is the sector size.  The header
40945 **       is this many bytes in size.
40946 **  (6)  4 byte big-endian integer which is the page size.
40947 **  (7)  zero padding out to the next sector size.
40948 **  (8)  Zero or more pages instances, each as follows:
40949 **        +  4 byte page number.
40950 **        +  pPager->pageSize bytes of data.
40951 **        +  4 byte checksum
40952 **
40953 ** When we speak of the journal header, we mean the first 7 items above.
40954 ** Each entry in the journal is an instance of the 8th item.
40955 **
40956 ** Call the value from the second bullet "nRec".  nRec is the number of
40957 ** valid page entries in the journal.  In most cases, you can compute the
40958 ** value of nRec from the size of the journal file.  But if a power
40959 ** failure occurred while the journal was being written, it could be the
40960 ** case that the size of the journal file had already been increased but
40961 ** the extra entries had not yet made it safely to disk.  In such a case,
40962 ** the value of nRec computed from the file size would be too large.  For
40963 ** that reason, we always use the nRec value in the header.
40964 **
40965 ** If the nRec value is 0xffffffff it means that nRec should be computed
40966 ** from the file size.  This value is used when the user selects the
40967 ** no-sync option for the journal.  A power failure could lead to corruption
40968 ** in this case.  But for things like temporary table (which will be
40969 ** deleted when the power is restored) we don't care.  
40970 **
40971 ** If the file opened as the journal file is not a well-formed
40972 ** journal file then all pages up to the first corrupted page are rolled
40973 ** back (or no pages if the journal header is corrupted). The journal file
40974 ** is then deleted and SQLITE_OK returned, just as if no corruption had
40975 ** been encountered.
40976 **
40977 ** If an I/O or malloc() error occurs, the journal-file is not deleted
40978 ** and an error code is returned.
40979 **
40980 ** The isHot parameter indicates that we are trying to rollback a journal
40981 ** that might be a hot journal.  Or, it could be that the journal is 
40982 ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
40983 ** If the journal really is hot, reset the pager cache prior rolling
40984 ** back any content.  If the journal is merely persistent, no reset is
40985 ** needed.
40986 */
40987 static int pager_playback(Pager *pPager, int isHot){
40988   sqlite3_vfs *pVfs = pPager->pVfs;
40989   i64 szJ;                 /* Size of the journal file in bytes */
40990   u32 nRec;                /* Number of Records in the journal */
40991   u32 u;                   /* Unsigned loop counter */
40992   Pgno mxPg = 0;           /* Size of the original file in pages */
40993   int rc;                  /* Result code of a subroutine */
40994   int res = 1;             /* Value returned by sqlite3OsAccess() */
40995   char *zMaster = 0;       /* Name of master journal file if any */
40996   int needPagerReset;      /* True to reset page prior to first page rollback */
40997   int nPlayback = 0;       /* Total number of pages restored from journal */
40998
40999   /* Figure out how many records are in the journal.  Abort early if
41000   ** the journal is empty.
41001   */
41002   assert( isOpen(pPager->jfd) );
41003   rc = sqlite3OsFileSize(pPager->jfd, &szJ);
41004   if( rc!=SQLITE_OK ){
41005     goto end_playback;
41006   }
41007
41008   /* Read the master journal name from the journal, if it is present.
41009   ** If a master journal file name is specified, but the file is not
41010   ** present on disk, then the journal is not hot and does not need to be
41011   ** played back.
41012   **
41013   ** TODO: Technically the following is an error because it assumes that
41014   ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
41015   ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
41016   **  mxPathname is 512, which is the same as the minimum allowable value
41017   ** for pageSize.
41018   */
41019   zMaster = pPager->pTmpSpace;
41020   rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
41021   if( rc==SQLITE_OK && zMaster[0] ){
41022     rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
41023   }
41024   zMaster = 0;
41025   if( rc!=SQLITE_OK || !res ){
41026     goto end_playback;
41027   }
41028   pPager->journalOff = 0;
41029   needPagerReset = isHot;
41030
41031   /* This loop terminates either when a readJournalHdr() or 
41032   ** pager_playback_one_page() call returns SQLITE_DONE or an IO error 
41033   ** occurs. 
41034   */
41035   while( 1 ){
41036     /* Read the next journal header from the journal file.  If there are
41037     ** not enough bytes left in the journal file for a complete header, or
41038     ** it is corrupted, then a process must have failed while writing it.
41039     ** This indicates nothing more needs to be rolled back.
41040     */
41041     rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
41042     if( rc!=SQLITE_OK ){ 
41043       if( rc==SQLITE_DONE ){
41044         rc = SQLITE_OK;
41045       }
41046       goto end_playback;
41047     }
41048
41049     /* If nRec is 0xffffffff, then this journal was created by a process
41050     ** working in no-sync mode. This means that the rest of the journal
41051     ** file consists of pages, there are no more journal headers. Compute
41052     ** the value of nRec based on this assumption.
41053     */
41054     if( nRec==0xffffffff ){
41055       assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
41056       nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
41057     }
41058
41059     /* If nRec is 0 and this rollback is of a transaction created by this
41060     ** process and if this is the final header in the journal, then it means
41061     ** that this part of the journal was being filled but has not yet been
41062     ** synced to disk.  Compute the number of pages based on the remaining
41063     ** size of the file.
41064     **
41065     ** The third term of the test was added to fix ticket #2565.
41066     ** When rolling back a hot journal, nRec==0 always means that the next
41067     ** chunk of the journal contains zero pages to be rolled back.  But
41068     ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
41069     ** the journal, it means that the journal might contain additional
41070     ** pages that need to be rolled back and that the number of pages 
41071     ** should be computed based on the journal file size.
41072     */
41073     if( nRec==0 && !isHot &&
41074         pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
41075       nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
41076     }
41077
41078     /* If this is the first header read from the journal, truncate the
41079     ** database file back to its original size.
41080     */
41081     if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
41082       rc = pager_truncate(pPager, mxPg);
41083       if( rc!=SQLITE_OK ){
41084         goto end_playback;
41085       }
41086       pPager->dbSize = mxPg;
41087     }
41088
41089     /* Copy original pages out of the journal and back into the 
41090     ** database file and/or page cache.
41091     */
41092     for(u=0; u<nRec; u++){
41093       if( needPagerReset ){
41094         pager_reset(pPager);
41095         needPagerReset = 0;
41096       }
41097       rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
41098       if( rc==SQLITE_OK ){
41099         nPlayback++;
41100       }else{
41101         if( rc==SQLITE_DONE ){
41102           pPager->journalOff = szJ;
41103           break;
41104         }else if( rc==SQLITE_IOERR_SHORT_READ ){
41105           /* If the journal has been truncated, simply stop reading and
41106           ** processing the journal. This might happen if the journal was
41107           ** not completely written and synced prior to a crash.  In that
41108           ** case, the database should have never been written in the
41109           ** first place so it is OK to simply abandon the rollback. */
41110           rc = SQLITE_OK;
41111           goto end_playback;
41112         }else{
41113           /* If we are unable to rollback, quit and return the error
41114           ** code.  This will cause the pager to enter the error state
41115           ** so that no further harm will be done.  Perhaps the next
41116           ** process to come along will be able to rollback the database.
41117           */
41118           goto end_playback;
41119         }
41120       }
41121     }
41122   }
41123   /*NOTREACHED*/
41124   assert( 0 );
41125
41126 end_playback:
41127   /* Following a rollback, the database file should be back in its original
41128   ** state prior to the start of the transaction, so invoke the
41129   ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
41130   ** assertion that the transaction counter was modified.
41131   */
41132 #ifdef SQLITE_DEBUG
41133   if( pPager->fd->pMethods ){
41134     sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
41135   }
41136 #endif
41137
41138   /* If this playback is happening automatically as a result of an IO or 
41139   ** malloc error that occurred after the change-counter was updated but 
41140   ** before the transaction was committed, then the change-counter 
41141   ** modification may just have been reverted. If this happens in exclusive 
41142   ** mode, then subsequent transactions performed by the connection will not
41143   ** update the change-counter at all. This may lead to cache inconsistency
41144   ** problems for other processes at some point in the future. So, just
41145   ** in case this has happened, clear the changeCountDone flag now.
41146   */
41147   pPager->changeCountDone = pPager->tempFile;
41148
41149   if( rc==SQLITE_OK ){
41150     zMaster = pPager->pTmpSpace;
41151     rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
41152     testcase( rc!=SQLITE_OK );
41153   }
41154   if( rc==SQLITE_OK
41155    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
41156   ){
41157     rc = sqlite3PagerSync(pPager);
41158   }
41159   if( rc==SQLITE_OK ){
41160     rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
41161     testcase( rc!=SQLITE_OK );
41162   }
41163   if( rc==SQLITE_OK && zMaster[0] && res ){
41164     /* If there was a master journal and this routine will return success,
41165     ** see if it is possible to delete the master journal.
41166     */
41167     rc = pager_delmaster(pPager, zMaster);
41168     testcase( rc!=SQLITE_OK );
41169   }
41170   if( isHot && nPlayback ){
41171     sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
41172                 nPlayback, pPager->zJournal);
41173   }
41174
41175   /* The Pager.sectorSize variable may have been updated while rolling
41176   ** back a journal created by a process with a different sector size
41177   ** value. Reset it to the correct value for this process.
41178   */
41179   setSectorSize(pPager);
41180   return rc;
41181 }
41182
41183
41184 /*
41185 ** Read the content for page pPg out of the database file and into 
41186 ** pPg->pData. A shared lock or greater must be held on the database
41187 ** file before this function is called.
41188 **
41189 ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
41190 ** the value read from the database file.
41191 **
41192 ** If an IO error occurs, then the IO error is returned to the caller.
41193 ** Otherwise, SQLITE_OK is returned.
41194 */
41195 static int readDbPage(PgHdr *pPg, u32 iFrame){
41196   Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
41197   Pgno pgno = pPg->pgno;       /* Page number to read */
41198   int rc = SQLITE_OK;          /* Return code */
41199   int pgsz = pPager->pageSize; /* Number of bytes to read */
41200
41201   assert( pPager->eState>=PAGER_READER && !MEMDB );
41202   assert( isOpen(pPager->fd) );
41203
41204   if( NEVER(!isOpen(pPager->fd)) ){
41205     assert( pPager->tempFile );
41206     memset(pPg->pData, 0, pPager->pageSize);
41207     return SQLITE_OK;
41208   }
41209
41210 #ifndef SQLITE_OMIT_WAL
41211   if( iFrame ){
41212     /* Try to pull the page from the write-ahead log. */
41213     rc = sqlite3WalReadFrame(pPager->pWal, iFrame, pgsz, pPg->pData);
41214   }else
41215 #endif
41216   {
41217     i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
41218     rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
41219     if( rc==SQLITE_IOERR_SHORT_READ ){
41220       rc = SQLITE_OK;
41221     }
41222   }
41223
41224   if( pgno==1 ){
41225     if( rc ){
41226       /* If the read is unsuccessful, set the dbFileVers[] to something
41227       ** that will never be a valid file version.  dbFileVers[] is a copy
41228       ** of bytes 24..39 of the database.  Bytes 28..31 should always be
41229       ** zero or the size of the database in page. Bytes 32..35 and 35..39
41230       ** should be page numbers which are never 0xffffffff.  So filling
41231       ** pPager->dbFileVers[] with all 0xff bytes should suffice.
41232       **
41233       ** For an encrypted database, the situation is more complex:  bytes
41234       ** 24..39 of the database are white noise.  But the probability of
41235       ** white noising equaling 16 bytes of 0xff is vanishingly small so
41236       ** we should still be ok.
41237       */
41238       memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
41239     }else{
41240       u8 *dbFileVers = &((u8*)pPg->pData)[24];
41241       memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
41242     }
41243   }
41244   CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
41245
41246   PAGER_INCR(sqlite3_pager_readdb_count);
41247   PAGER_INCR(pPager->nRead);
41248   IOTRACE(("PGIN %p %d\n", pPager, pgno));
41249   PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
41250                PAGERID(pPager), pgno, pager_pagehash(pPg)));
41251
41252   return rc;
41253 }
41254
41255 /*
41256 ** Update the value of the change-counter at offsets 24 and 92 in
41257 ** the header and the sqlite version number at offset 96.
41258 **
41259 ** This is an unconditional update.  See also the pager_incr_changecounter()
41260 ** routine which only updates the change-counter if the update is actually
41261 ** needed, as determined by the pPager->changeCountDone state variable.
41262 */
41263 static void pager_write_changecounter(PgHdr *pPg){
41264   u32 change_counter;
41265
41266   /* Increment the value just read and write it back to byte 24. */
41267   change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
41268   put32bits(((char*)pPg->pData)+24, change_counter);
41269
41270   /* Also store the SQLite version number in bytes 96..99 and in
41271   ** bytes 92..95 store the change counter for which the version number
41272   ** is valid. */
41273   put32bits(((char*)pPg->pData)+92, change_counter);
41274   put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
41275 }
41276
41277 #ifndef SQLITE_OMIT_WAL
41278 /*
41279 ** This function is invoked once for each page that has already been 
41280 ** written into the log file when a WAL transaction is rolled back.
41281 ** Parameter iPg is the page number of said page. The pCtx argument 
41282 ** is actually a pointer to the Pager structure.
41283 **
41284 ** If page iPg is present in the cache, and has no outstanding references,
41285 ** it is discarded. Otherwise, if there are one or more outstanding
41286 ** references, the page content is reloaded from the database. If the
41287 ** attempt to reload content from the database is required and fails, 
41288 ** return an SQLite error code. Otherwise, SQLITE_OK.
41289 */
41290 static int pagerUndoCallback(void *pCtx, Pgno iPg){
41291   int rc = SQLITE_OK;
41292   Pager *pPager = (Pager *)pCtx;
41293   PgHdr *pPg;
41294
41295   assert( pagerUseWal(pPager) );
41296   pPg = sqlite3PagerLookup(pPager, iPg);
41297   if( pPg ){
41298     if( sqlite3PcachePageRefcount(pPg)==1 ){
41299       sqlite3PcacheDrop(pPg);
41300     }else{
41301       u32 iFrame = 0;
41302       rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
41303       if( rc==SQLITE_OK ){
41304         rc = readDbPage(pPg, iFrame);
41305       }
41306       if( rc==SQLITE_OK ){
41307         pPager->xReiniter(pPg);
41308       }
41309       sqlite3PagerUnref(pPg);
41310     }
41311   }
41312
41313   /* Normally, if a transaction is rolled back, any backup processes are
41314   ** updated as data is copied out of the rollback journal and into the
41315   ** database. This is not generally possible with a WAL database, as
41316   ** rollback involves simply truncating the log file. Therefore, if one
41317   ** or more frames have already been written to the log (and therefore 
41318   ** also copied into the backup databases) as part of this transaction,
41319   ** the backups must be restarted.
41320   */
41321   sqlite3BackupRestart(pPager->pBackup);
41322
41323   return rc;
41324 }
41325
41326 /*
41327 ** This function is called to rollback a transaction on a WAL database.
41328 */
41329 static int pagerRollbackWal(Pager *pPager){
41330   int rc;                         /* Return Code */
41331   PgHdr *pList;                   /* List of dirty pages to revert */
41332
41333   /* For all pages in the cache that are currently dirty or have already
41334   ** been written (but not committed) to the log file, do one of the 
41335   ** following:
41336   **
41337   **   + Discard the cached page (if refcount==0), or
41338   **   + Reload page content from the database (if refcount>0).
41339   */
41340   pPager->dbSize = pPager->dbOrigSize;
41341   rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
41342   pList = sqlite3PcacheDirtyList(pPager->pPCache);
41343   while( pList && rc==SQLITE_OK ){
41344     PgHdr *pNext = pList->pDirty;
41345     rc = pagerUndoCallback((void *)pPager, pList->pgno);
41346     pList = pNext;
41347   }
41348
41349   return rc;
41350 }
41351
41352 /*
41353 ** This function is a wrapper around sqlite3WalFrames(). As well as logging
41354 ** the contents of the list of pages headed by pList (connected by pDirty),
41355 ** this function notifies any active backup processes that the pages have
41356 ** changed. 
41357 **
41358 ** The list of pages passed into this routine is always sorted by page number.
41359 ** Hence, if page 1 appears anywhere on the list, it will be the first page.
41360 */ 
41361 static int pagerWalFrames(
41362   Pager *pPager,                  /* Pager object */
41363   PgHdr *pList,                   /* List of frames to log */
41364   Pgno nTruncate,                 /* Database size after this commit */
41365   int isCommit                    /* True if this is a commit */
41366 ){
41367   int rc;                         /* Return code */
41368   int nList;                      /* Number of pages in pList */
41369 #if defined(SQLITE_DEBUG) || defined(SQLITE_CHECK_PAGES)
41370   PgHdr *p;                       /* For looping over pages */
41371 #endif
41372
41373   assert( pPager->pWal );
41374   assert( pList );
41375 #ifdef SQLITE_DEBUG
41376   /* Verify that the page list is in accending order */
41377   for(p=pList; p && p->pDirty; p=p->pDirty){
41378     assert( p->pgno < p->pDirty->pgno );
41379   }
41380 #endif
41381
41382   assert( pList->pDirty==0 || isCommit );
41383   if( isCommit ){
41384     /* If a WAL transaction is being committed, there is no point in writing
41385     ** any pages with page numbers greater than nTruncate into the WAL file.
41386     ** They will never be read by any client. So remove them from the pDirty
41387     ** list here. */
41388     PgHdr *p;
41389     PgHdr **ppNext = &pList;
41390     nList = 0;
41391     for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
41392       if( p->pgno<=nTruncate ){
41393         ppNext = &p->pDirty;
41394         nList++;
41395       }
41396     }
41397     assert( pList );
41398   }else{
41399     nList = 1;
41400   }
41401   pPager->aStat[PAGER_STAT_WRITE] += nList;
41402
41403   if( pList->pgno==1 ) pager_write_changecounter(pList);
41404   rc = sqlite3WalFrames(pPager->pWal, 
41405       pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
41406   );
41407   if( rc==SQLITE_OK && pPager->pBackup ){
41408     PgHdr *p;
41409     for(p=pList; p; p=p->pDirty){
41410       sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
41411     }
41412   }
41413
41414 #ifdef SQLITE_CHECK_PAGES
41415   pList = sqlite3PcacheDirtyList(pPager->pPCache);
41416   for(p=pList; p; p=p->pDirty){
41417     pager_set_pagehash(p);
41418   }
41419 #endif
41420
41421   return rc;
41422 }
41423
41424 /*
41425 ** Begin a read transaction on the WAL.
41426 **
41427 ** This routine used to be called "pagerOpenSnapshot()" because it essentially
41428 ** makes a snapshot of the database at the current point in time and preserves
41429 ** that snapshot for use by the reader in spite of concurrently changes by
41430 ** other writers or checkpointers.
41431 */
41432 static int pagerBeginReadTransaction(Pager *pPager){
41433   int rc;                         /* Return code */
41434   int changed = 0;                /* True if cache must be reset */
41435
41436   assert( pagerUseWal(pPager) );
41437   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
41438
41439   /* sqlite3WalEndReadTransaction() was not called for the previous
41440   ** transaction in locking_mode=EXCLUSIVE.  So call it now.  If we
41441   ** are in locking_mode=NORMAL and EndRead() was previously called,
41442   ** the duplicate call is harmless.
41443   */
41444   sqlite3WalEndReadTransaction(pPager->pWal);
41445
41446   rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
41447   if( rc!=SQLITE_OK || changed ){
41448     pager_reset(pPager);
41449     if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
41450   }
41451
41452   return rc;
41453 }
41454 #endif
41455
41456 /*
41457 ** This function is called as part of the transition from PAGER_OPEN
41458 ** to PAGER_READER state to determine the size of the database file
41459 ** in pages (assuming the page size currently stored in Pager.pageSize).
41460 **
41461 ** If no error occurs, SQLITE_OK is returned and the size of the database
41462 ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
41463 ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
41464 */
41465 static int pagerPagecount(Pager *pPager, Pgno *pnPage){
41466   Pgno nPage;                     /* Value to return via *pnPage */
41467
41468   /* Query the WAL sub-system for the database size. The WalDbsize()
41469   ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
41470   ** if the database size is not available. The database size is not
41471   ** available from the WAL sub-system if the log file is empty or
41472   ** contains no valid committed transactions.
41473   */
41474   assert( pPager->eState==PAGER_OPEN );
41475   assert( pPager->eLock>=SHARED_LOCK );
41476   nPage = sqlite3WalDbsize(pPager->pWal);
41477
41478   /* If the database size was not available from the WAL sub-system,
41479   ** determine it based on the size of the database file. If the size
41480   ** of the database file is not an integer multiple of the page-size,
41481   ** round down to the nearest page. Except, any file larger than 0
41482   ** bytes in size is considered to contain at least one page.
41483   */
41484   if( nPage==0 ){
41485     i64 n = 0;                    /* Size of db file in bytes */
41486     assert( isOpen(pPager->fd) || pPager->tempFile );
41487     if( isOpen(pPager->fd) ){
41488       int rc = sqlite3OsFileSize(pPager->fd, &n);
41489       if( rc!=SQLITE_OK ){
41490         return rc;
41491       }
41492     }
41493     nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
41494   }
41495
41496   /* If the current number of pages in the file is greater than the
41497   ** configured maximum pager number, increase the allowed limit so
41498   ** that the file can be read.
41499   */
41500   if( nPage>pPager->mxPgno ){
41501     pPager->mxPgno = (Pgno)nPage;
41502   }
41503
41504   *pnPage = nPage;
41505   return SQLITE_OK;
41506 }
41507
41508 #ifndef SQLITE_OMIT_WAL
41509 /*
41510 ** Check if the *-wal file that corresponds to the database opened by pPager
41511 ** exists if the database is not empy, or verify that the *-wal file does
41512 ** not exist (by deleting it) if the database file is empty.
41513 **
41514 ** If the database is not empty and the *-wal file exists, open the pager
41515 ** in WAL mode.  If the database is empty or if no *-wal file exists and
41516 ** if no error occurs, make sure Pager.journalMode is not set to
41517 ** PAGER_JOURNALMODE_WAL.
41518 **
41519 ** Return SQLITE_OK or an error code.
41520 **
41521 ** The caller must hold a SHARED lock on the database file to call this
41522 ** function. Because an EXCLUSIVE lock on the db file is required to delete 
41523 ** a WAL on a none-empty database, this ensures there is no race condition 
41524 ** between the xAccess() below and an xDelete() being executed by some 
41525 ** other connection.
41526 */
41527 static int pagerOpenWalIfPresent(Pager *pPager){
41528   int rc = SQLITE_OK;
41529   assert( pPager->eState==PAGER_OPEN );
41530   assert( pPager->eLock>=SHARED_LOCK );
41531
41532   if( !pPager->tempFile ){
41533     int isWal;                    /* True if WAL file exists */
41534     Pgno nPage;                   /* Size of the database file */
41535
41536     rc = pagerPagecount(pPager, &nPage);
41537     if( rc ) return rc;
41538     if( nPage==0 ){
41539       rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
41540       if( rc==SQLITE_IOERR_DELETE_NOENT ) rc = SQLITE_OK;
41541       isWal = 0;
41542     }else{
41543       rc = sqlite3OsAccess(
41544           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
41545       );
41546     }
41547     if( rc==SQLITE_OK ){
41548       if( isWal ){
41549         testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
41550         rc = sqlite3PagerOpenWal(pPager, 0);
41551       }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
41552         pPager->journalMode = PAGER_JOURNALMODE_DELETE;
41553       }
41554     }
41555   }
41556   return rc;
41557 }
41558 #endif
41559
41560 /*
41561 ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
41562 ** the entire master journal file. The case pSavepoint==NULL occurs when 
41563 ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction 
41564 ** savepoint.
41565 **
41566 ** When pSavepoint is not NULL (meaning a non-transaction savepoint is 
41567 ** being rolled back), then the rollback consists of up to three stages,
41568 ** performed in the order specified:
41569 **
41570 **   * Pages are played back from the main journal starting at byte
41571 **     offset PagerSavepoint.iOffset and continuing to 
41572 **     PagerSavepoint.iHdrOffset, or to the end of the main journal
41573 **     file if PagerSavepoint.iHdrOffset is zero.
41574 **
41575 **   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
41576 **     back starting from the journal header immediately following 
41577 **     PagerSavepoint.iHdrOffset to the end of the main journal file.
41578 **
41579 **   * Pages are then played back from the sub-journal file, starting
41580 **     with the PagerSavepoint.iSubRec and continuing to the end of
41581 **     the journal file.
41582 **
41583 ** Throughout the rollback process, each time a page is rolled back, the
41584 ** corresponding bit is set in a bitvec structure (variable pDone in the
41585 ** implementation below). This is used to ensure that a page is only
41586 ** rolled back the first time it is encountered in either journal.
41587 **
41588 ** If pSavepoint is NULL, then pages are only played back from the main
41589 ** journal file. There is no need for a bitvec in this case.
41590 **
41591 ** In either case, before playback commences the Pager.dbSize variable
41592 ** is reset to the value that it held at the start of the savepoint 
41593 ** (or transaction). No page with a page-number greater than this value
41594 ** is played back. If one is encountered it is simply skipped.
41595 */
41596 static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
41597   i64 szJ;                 /* Effective size of the main journal */
41598   i64 iHdrOff;             /* End of first segment of main-journal records */
41599   int rc = SQLITE_OK;      /* Return code */
41600   Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
41601
41602   assert( pPager->eState!=PAGER_ERROR );
41603   assert( pPager->eState>=PAGER_WRITER_LOCKED );
41604
41605   /* Allocate a bitvec to use to store the set of pages rolled back */
41606   if( pSavepoint ){
41607     pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
41608     if( !pDone ){
41609       return SQLITE_NOMEM;
41610     }
41611   }
41612
41613   /* Set the database size back to the value it was before the savepoint 
41614   ** being reverted was opened.
41615   */
41616   pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
41617   pPager->changeCountDone = pPager->tempFile;
41618
41619   if( !pSavepoint && pagerUseWal(pPager) ){
41620     return pagerRollbackWal(pPager);
41621   }
41622
41623   /* Use pPager->journalOff as the effective size of the main rollback
41624   ** journal.  The actual file might be larger than this in
41625   ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
41626   ** past pPager->journalOff is off-limits to us.
41627   */
41628   szJ = pPager->journalOff;
41629   assert( pagerUseWal(pPager)==0 || szJ==0 );
41630
41631   /* Begin by rolling back records from the main journal starting at
41632   ** PagerSavepoint.iOffset and continuing to the next journal header.
41633   ** There might be records in the main journal that have a page number
41634   ** greater than the current database size (pPager->dbSize) but those
41635   ** will be skipped automatically.  Pages are added to pDone as they
41636   ** are played back.
41637   */
41638   if( pSavepoint && !pagerUseWal(pPager) ){
41639     iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
41640     pPager->journalOff = pSavepoint->iOffset;
41641     while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
41642       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
41643     }
41644     assert( rc!=SQLITE_DONE );
41645   }else{
41646     pPager->journalOff = 0;
41647   }
41648
41649   /* Continue rolling back records out of the main journal starting at
41650   ** the first journal header seen and continuing until the effective end
41651   ** of the main journal file.  Continue to skip out-of-range pages and
41652   ** continue adding pages rolled back to pDone.
41653   */
41654   while( rc==SQLITE_OK && pPager->journalOff<szJ ){
41655     u32 ii;            /* Loop counter */
41656     u32 nJRec = 0;     /* Number of Journal Records */
41657     u32 dummy;
41658     rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
41659     assert( rc!=SQLITE_DONE );
41660
41661     /*
41662     ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
41663     ** test is related to ticket #2565.  See the discussion in the
41664     ** pager_playback() function for additional information.
41665     */
41666     if( nJRec==0 
41667      && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
41668     ){
41669       nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
41670     }
41671     for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
41672       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
41673     }
41674     assert( rc!=SQLITE_DONE );
41675   }
41676   assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
41677
41678   /* Finally,  rollback pages from the sub-journal.  Page that were
41679   ** previously rolled back out of the main journal (and are hence in pDone)
41680   ** will be skipped.  Out-of-range pages are also skipped.
41681   */
41682   if( pSavepoint ){
41683     u32 ii;            /* Loop counter */
41684     i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
41685
41686     if( pagerUseWal(pPager) ){
41687       rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
41688     }
41689     for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
41690       assert( offset==(i64)ii*(4+pPager->pageSize) );
41691       rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
41692     }
41693     assert( rc!=SQLITE_DONE );
41694   }
41695
41696   sqlite3BitvecDestroy(pDone);
41697   if( rc==SQLITE_OK ){
41698     pPager->journalOff = szJ;
41699   }
41700
41701   return rc;
41702 }
41703
41704 /*
41705 ** Change the maximum number of in-memory pages that are allowed.
41706 */
41707 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
41708   sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
41709 }
41710
41711 /*
41712 ** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
41713 */
41714 static void pagerFixMaplimit(Pager *pPager){
41715 #if SQLITE_MAX_MMAP_SIZE>0
41716   sqlite3_file *fd = pPager->fd;
41717   if( isOpen(fd) ){
41718     sqlite3_int64 sz;
41719     pPager->bUseFetch = (fd->pMethods->iVersion>=3) && pPager->szMmap>0;
41720     sz = pPager->szMmap;
41721     sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
41722   }
41723 #endif
41724 }
41725
41726 /*
41727 ** Change the maximum size of any memory mapping made of the database file.
41728 */
41729 SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
41730   pPager->szMmap = szMmap;
41731   pagerFixMaplimit(pPager);
41732 }
41733
41734 /*
41735 ** Free as much memory as possible from the pager.
41736 */
41737 SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
41738   sqlite3PcacheShrink(pPager->pPCache);
41739 }
41740
41741 /*
41742 ** Adjust the robustness of the database to damage due to OS crashes
41743 ** or power failures by changing the number of syncs()s when writing
41744 ** the rollback journal.  There are three levels:
41745 **
41746 **    OFF       sqlite3OsSync() is never called.  This is the default
41747 **              for temporary and transient files.
41748 **
41749 **    NORMAL    The journal is synced once before writes begin on the
41750 **              database.  This is normally adequate protection, but
41751 **              it is theoretically possible, though very unlikely,
41752 **              that an inopertune power failure could leave the journal
41753 **              in a state which would cause damage to the database
41754 **              when it is rolled back.
41755 **
41756 **    FULL      The journal is synced twice before writes begin on the
41757 **              database (with some additional information - the nRec field
41758 **              of the journal header - being written in between the two
41759 **              syncs).  If we assume that writing a
41760 **              single disk sector is atomic, then this mode provides
41761 **              assurance that the journal will not be corrupted to the
41762 **              point of causing damage to the database during rollback.
41763 **
41764 ** The above is for a rollback-journal mode.  For WAL mode, OFF continues
41765 ** to mean that no syncs ever occur.  NORMAL means that the WAL is synced
41766 ** prior to the start of checkpoint and that the database file is synced
41767 ** at the conclusion of the checkpoint if the entire content of the WAL
41768 ** was written back into the database.  But no sync operations occur for
41769 ** an ordinary commit in NORMAL mode with WAL.  FULL means that the WAL
41770 ** file is synced following each commit operation, in addition to the
41771 ** syncs associated with NORMAL.
41772 **
41773 ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL.  The
41774 ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
41775 ** using fcntl(F_FULLFSYNC).  SQLITE_SYNC_NORMAL means to do an
41776 ** ordinary fsync() call.  There is no difference between SQLITE_SYNC_FULL
41777 ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX.  But the
41778 ** synchronous=FULL versus synchronous=NORMAL setting determines when
41779 ** the xSync primitive is called and is relevant to all platforms.
41780 **
41781 ** Numeric values associated with these states are OFF==1, NORMAL=2,
41782 ** and FULL=3.
41783 */
41784 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
41785 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(
41786   Pager *pPager,        /* The pager to set safety level for */
41787   int level,            /* PRAGMA synchronous.  1=OFF, 2=NORMAL, 3=FULL */  
41788   int bFullFsync,       /* PRAGMA fullfsync */
41789   int bCkptFullFsync    /* PRAGMA checkpoint_fullfsync */
41790 ){
41791   assert( level>=1 && level<=3 );
41792   pPager->noSync =  (level==1 || pPager->tempFile) ?1:0;
41793   pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
41794   if( pPager->noSync ){
41795     pPager->syncFlags = 0;
41796     pPager->ckptSyncFlags = 0;
41797   }else if( bFullFsync ){
41798     pPager->syncFlags = SQLITE_SYNC_FULL;
41799     pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
41800   }else if( bCkptFullFsync ){
41801     pPager->syncFlags = SQLITE_SYNC_NORMAL;
41802     pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
41803   }else{
41804     pPager->syncFlags = SQLITE_SYNC_NORMAL;
41805     pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
41806   }
41807   pPager->walSyncFlags = pPager->syncFlags;
41808   if( pPager->fullSync ){
41809     pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS;
41810   }
41811 }
41812 #endif
41813
41814 /*
41815 ** The following global variable is incremented whenever the library
41816 ** attempts to open a temporary file.  This information is used for
41817 ** testing and analysis only.  
41818 */
41819 #ifdef SQLITE_TEST
41820 SQLITE_API int sqlite3_opentemp_count = 0;
41821 #endif
41822
41823 /*
41824 ** Open a temporary file.
41825 **
41826 ** Write the file descriptor into *pFile. Return SQLITE_OK on success 
41827 ** or some other error code if we fail. The OS will automatically 
41828 ** delete the temporary file when it is closed.
41829 **
41830 ** The flags passed to the VFS layer xOpen() call are those specified
41831 ** by parameter vfsFlags ORed with the following:
41832 **
41833 **     SQLITE_OPEN_READWRITE
41834 **     SQLITE_OPEN_CREATE
41835 **     SQLITE_OPEN_EXCLUSIVE
41836 **     SQLITE_OPEN_DELETEONCLOSE
41837 */
41838 static int pagerOpentemp(
41839   Pager *pPager,        /* The pager object */
41840   sqlite3_file *pFile,  /* Write the file descriptor here */
41841   int vfsFlags          /* Flags passed through to the VFS */
41842 ){
41843   int rc;               /* Return code */
41844
41845 #ifdef SQLITE_TEST
41846   sqlite3_opentemp_count++;  /* Used for testing and analysis only */
41847 #endif
41848
41849   vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
41850             SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
41851   rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
41852   assert( rc!=SQLITE_OK || isOpen(pFile) );
41853   return rc;
41854 }
41855
41856 /*
41857 ** Set the busy handler function.
41858 **
41859 ** The pager invokes the busy-handler if sqlite3OsLock() returns 
41860 ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
41861 ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE 
41862 ** lock. It does *not* invoke the busy handler when upgrading from
41863 ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
41864 ** (which occurs during hot-journal rollback). Summary:
41865 **
41866 **   Transition                        | Invokes xBusyHandler
41867 **   --------------------------------------------------------
41868 **   NO_LOCK       -> SHARED_LOCK      | Yes
41869 **   SHARED_LOCK   -> RESERVED_LOCK    | No
41870 **   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
41871 **   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
41872 **
41873 ** If the busy-handler callback returns non-zero, the lock is 
41874 ** retried. If it returns zero, then the SQLITE_BUSY error is
41875 ** returned to the caller of the pager API function.
41876 */
41877 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
41878   Pager *pPager,                       /* Pager object */
41879   int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
41880   void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
41881 ){
41882   pPager->xBusyHandler = xBusyHandler;
41883   pPager->pBusyHandlerArg = pBusyHandlerArg;
41884
41885   if( isOpen(pPager->fd) ){
41886     void **ap = (void **)&pPager->xBusyHandler;
41887     assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
41888     assert( ap[1]==pBusyHandlerArg );
41889     sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
41890   }
41891 }
41892
41893 /*
41894 ** Change the page size used by the Pager object. The new page size 
41895 ** is passed in *pPageSize.
41896 **
41897 ** If the pager is in the error state when this function is called, it
41898 ** is a no-op. The value returned is the error state error code (i.e. 
41899 ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
41900 **
41901 ** Otherwise, if all of the following are true:
41902 **
41903 **   * the new page size (value of *pPageSize) is valid (a power 
41904 **     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
41905 **
41906 **   * there are no outstanding page references, and
41907 **
41908 **   * the database is either not an in-memory database or it is
41909 **     an in-memory database that currently consists of zero pages.
41910 **
41911 ** then the pager object page size is set to *pPageSize.
41912 **
41913 ** If the page size is changed, then this function uses sqlite3PagerMalloc() 
41914 ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt 
41915 ** fails, SQLITE_NOMEM is returned and the page size remains unchanged. 
41916 ** In all other cases, SQLITE_OK is returned.
41917 **
41918 ** If the page size is not changed, either because one of the enumerated
41919 ** conditions above is not true, the pager was in error state when this
41920 ** function was called, or because the memory allocation attempt failed, 
41921 ** then *pPageSize is set to the old, retained page size before returning.
41922 */
41923 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
41924   int rc = SQLITE_OK;
41925
41926   /* It is not possible to do a full assert_pager_state() here, as this
41927   ** function may be called from within PagerOpen(), before the state
41928   ** of the Pager object is internally consistent.
41929   **
41930   ** At one point this function returned an error if the pager was in 
41931   ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
41932   ** there is at least one outstanding page reference, this function
41933   ** is a no-op for that case anyhow.
41934   */
41935
41936   u32 pageSize = *pPageSize;
41937   assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
41938   if( (pPager->memDb==0 || pPager->dbSize==0)
41939    && sqlite3PcacheRefCount(pPager->pPCache)==0 
41940    && pageSize && pageSize!=(u32)pPager->pageSize 
41941   ){
41942     char *pNew = NULL;             /* New temp space */
41943     i64 nByte = 0;
41944
41945     if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
41946       rc = sqlite3OsFileSize(pPager->fd, &nByte);
41947     }
41948     if( rc==SQLITE_OK ){
41949       pNew = (char *)sqlite3PageMalloc(pageSize);
41950       if( !pNew ) rc = SQLITE_NOMEM;
41951     }
41952
41953     if( rc==SQLITE_OK ){
41954       pager_reset(pPager);
41955       pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
41956       pPager->pageSize = pageSize;
41957       sqlite3PageFree(pPager->pTmpSpace);
41958       pPager->pTmpSpace = pNew;
41959       sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
41960     }
41961   }
41962
41963   *pPageSize = pPager->pageSize;
41964   if( rc==SQLITE_OK ){
41965     if( nReserve<0 ) nReserve = pPager->nReserve;
41966     assert( nReserve>=0 && nReserve<1000 );
41967     pPager->nReserve = (i16)nReserve;
41968     pagerReportSize(pPager);
41969     pagerFixMaplimit(pPager);
41970   }
41971   return rc;
41972 }
41973
41974 /*
41975 ** Return a pointer to the "temporary page" buffer held internally
41976 ** by the pager.  This is a buffer that is big enough to hold the
41977 ** entire content of a database page.  This buffer is used internally
41978 ** during rollback and will be overwritten whenever a rollback
41979 ** occurs.  But other modules are free to use it too, as long as
41980 ** no rollbacks are happening.
41981 */
41982 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
41983   return pPager->pTmpSpace;
41984 }
41985
41986 /*
41987 ** Attempt to set the maximum database page count if mxPage is positive. 
41988 ** Make no changes if mxPage is zero or negative.  And never reduce the
41989 ** maximum page count below the current size of the database.
41990 **
41991 ** Regardless of mxPage, return the current maximum page count.
41992 */
41993 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
41994   if( mxPage>0 ){
41995     pPager->mxPgno = mxPage;
41996   }
41997   assert( pPager->eState!=PAGER_OPEN );      /* Called only by OP_MaxPgcnt */
41998   assert( pPager->mxPgno>=pPager->dbSize );  /* OP_MaxPgcnt enforces this */
41999   return pPager->mxPgno;
42000 }
42001
42002 /*
42003 ** The following set of routines are used to disable the simulated
42004 ** I/O error mechanism.  These routines are used to avoid simulated
42005 ** errors in places where we do not care about errors.
42006 **
42007 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
42008 ** and generate no code.
42009 */
42010 #ifdef SQLITE_TEST
42011 SQLITE_API extern int sqlite3_io_error_pending;
42012 SQLITE_API extern int sqlite3_io_error_hit;
42013 static int saved_cnt;
42014 void disable_simulated_io_errors(void){
42015   saved_cnt = sqlite3_io_error_pending;
42016   sqlite3_io_error_pending = -1;
42017 }
42018 void enable_simulated_io_errors(void){
42019   sqlite3_io_error_pending = saved_cnt;
42020 }
42021 #else
42022 # define disable_simulated_io_errors()
42023 # define enable_simulated_io_errors()
42024 #endif
42025
42026 /*
42027 ** Read the first N bytes from the beginning of the file into memory
42028 ** that pDest points to. 
42029 **
42030 ** If the pager was opened on a transient file (zFilename==""), or
42031 ** opened on a file less than N bytes in size, the output buffer is
42032 ** zeroed and SQLITE_OK returned. The rationale for this is that this 
42033 ** function is used to read database headers, and a new transient or
42034 ** zero sized database has a header than consists entirely of zeroes.
42035 **
42036 ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
42037 ** the error code is returned to the caller and the contents of the
42038 ** output buffer undefined.
42039 */
42040 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
42041   int rc = SQLITE_OK;
42042   memset(pDest, 0, N);
42043   assert( isOpen(pPager->fd) || pPager->tempFile );
42044
42045   /* This routine is only called by btree immediately after creating
42046   ** the Pager object.  There has not been an opportunity to transition
42047   ** to WAL mode yet.
42048   */
42049   assert( !pagerUseWal(pPager) );
42050
42051   if( isOpen(pPager->fd) ){
42052     IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
42053     rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
42054     if( rc==SQLITE_IOERR_SHORT_READ ){
42055       rc = SQLITE_OK;
42056     }
42057   }
42058   return rc;
42059 }
42060
42061 /*
42062 ** This function may only be called when a read-transaction is open on
42063 ** the pager. It returns the total number of pages in the database.
42064 **
42065 ** However, if the file is between 1 and <page-size> bytes in size, then 
42066 ** this is considered a 1 page file.
42067 */
42068 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
42069   assert( pPager->eState>=PAGER_READER );
42070   assert( pPager->eState!=PAGER_WRITER_FINISHED );
42071   *pnPage = (int)pPager->dbSize;
42072 }
42073
42074
42075 /*
42076 ** Try to obtain a lock of type locktype on the database file. If
42077 ** a similar or greater lock is already held, this function is a no-op
42078 ** (returning SQLITE_OK immediately).
42079 **
42080 ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke 
42081 ** the busy callback if the lock is currently not available. Repeat 
42082 ** until the busy callback returns false or until the attempt to 
42083 ** obtain the lock succeeds.
42084 **
42085 ** Return SQLITE_OK on success and an error code if we cannot obtain
42086 ** the lock. If the lock is obtained successfully, set the Pager.state 
42087 ** variable to locktype before returning.
42088 */
42089 static int pager_wait_on_lock(Pager *pPager, int locktype){
42090   int rc;                              /* Return code */
42091
42092   /* Check that this is either a no-op (because the requested lock is 
42093   ** already held, or one of the transistions that the busy-handler
42094   ** may be invoked during, according to the comment above
42095   ** sqlite3PagerSetBusyhandler().
42096   */
42097   assert( (pPager->eLock>=locktype)
42098        || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
42099        || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
42100   );
42101
42102   do {
42103     rc = pagerLockDb(pPager, locktype);
42104   }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
42105   return rc;
42106 }
42107
42108 /*
42109 ** Function assertTruncateConstraint(pPager) checks that one of the 
42110 ** following is true for all dirty pages currently in the page-cache:
42111 **
42112 **   a) The page number is less than or equal to the size of the 
42113 **      current database image, in pages, OR
42114 **
42115 **   b) if the page content were written at this time, it would not
42116 **      be necessary to write the current content out to the sub-journal
42117 **      (as determined by function subjRequiresPage()).
42118 **
42119 ** If the condition asserted by this function were not true, and the
42120 ** dirty page were to be discarded from the cache via the pagerStress()
42121 ** routine, pagerStress() would not write the current page content to
42122 ** the database file. If a savepoint transaction were rolled back after
42123 ** this happened, the correct behavior would be to restore the current
42124 ** content of the page. However, since this content is not present in either
42125 ** the database file or the portion of the rollback journal and 
42126 ** sub-journal rolled back the content could not be restored and the
42127 ** database image would become corrupt. It is therefore fortunate that 
42128 ** this circumstance cannot arise.
42129 */
42130 #if defined(SQLITE_DEBUG)
42131 static void assertTruncateConstraintCb(PgHdr *pPg){
42132   assert( pPg->flags&PGHDR_DIRTY );
42133   assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
42134 }
42135 static void assertTruncateConstraint(Pager *pPager){
42136   sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
42137 }
42138 #else
42139 # define assertTruncateConstraint(pPager)
42140 #endif
42141
42142 /*
42143 ** Truncate the in-memory database file image to nPage pages. This 
42144 ** function does not actually modify the database file on disk. It 
42145 ** just sets the internal state of the pager object so that the 
42146 ** truncation will be done when the current transaction is committed.
42147 **
42148 ** This function is only called right before committing a transaction.
42149 ** Once this function has been called, the transaction must either be
42150 ** rolled back or committed. It is not safe to call this function and
42151 ** then continue writing to the database.
42152 */
42153 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
42154   assert( pPager->dbSize>=nPage );
42155   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
42156   pPager->dbSize = nPage;
42157
42158   /* At one point the code here called assertTruncateConstraint() to
42159   ** ensure that all pages being truncated away by this operation are,
42160   ** if one or more savepoints are open, present in the savepoint 
42161   ** journal so that they can be restored if the savepoint is rolled
42162   ** back. This is no longer necessary as this function is now only
42163   ** called right before committing a transaction. So although the 
42164   ** Pager object may still have open savepoints (Pager.nSavepoint!=0), 
42165   ** they cannot be rolled back. So the assertTruncateConstraint() call
42166   ** is no longer correct. */
42167 }
42168
42169
42170 /*
42171 ** This function is called before attempting a hot-journal rollback. It
42172 ** syncs the journal file to disk, then sets pPager->journalHdr to the
42173 ** size of the journal file so that the pager_playback() routine knows
42174 ** that the entire journal file has been synced.
42175 **
42176 ** Syncing a hot-journal to disk before attempting to roll it back ensures 
42177 ** that if a power-failure occurs during the rollback, the process that
42178 ** attempts rollback following system recovery sees the same journal
42179 ** content as this process.
42180 **
42181 ** If everything goes as planned, SQLITE_OK is returned. Otherwise, 
42182 ** an SQLite error code.
42183 */
42184 static int pagerSyncHotJournal(Pager *pPager){
42185   int rc = SQLITE_OK;
42186   if( !pPager->noSync ){
42187     rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
42188   }
42189   if( rc==SQLITE_OK ){
42190     rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
42191   }
42192   return rc;
42193 }
42194
42195 /*
42196 ** Obtain a reference to a memory mapped page object for page number pgno. 
42197 ** The new object will use the pointer pData, obtained from xFetch().
42198 ** If successful, set *ppPage to point to the new page reference
42199 ** and return SQLITE_OK. Otherwise, return an SQLite error code and set
42200 ** *ppPage to zero.
42201 **
42202 ** Page references obtained by calling this function should be released
42203 ** by calling pagerReleaseMapPage().
42204 */
42205 static int pagerAcquireMapPage(
42206   Pager *pPager,                  /* Pager object */
42207   Pgno pgno,                      /* Page number */
42208   void *pData,                    /* xFetch()'d data for this page */
42209   PgHdr **ppPage                  /* OUT: Acquired page object */
42210 ){
42211   PgHdr *p;                       /* Memory mapped page to return */
42212
42213   if( pPager->pMmapFreelist ){
42214     *ppPage = p = pPager->pMmapFreelist;
42215     pPager->pMmapFreelist = p->pDirty;
42216     p->pDirty = 0;
42217     memset(p->pExtra, 0, pPager->nExtra);
42218   }else{
42219     *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
42220     if( p==0 ){
42221       sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
42222       return SQLITE_NOMEM;
42223     }
42224     p->pExtra = (void *)&p[1];
42225     p->flags = PGHDR_MMAP;
42226     p->nRef = 1;
42227     p->pPager = pPager;
42228   }
42229
42230   assert( p->pExtra==(void *)&p[1] );
42231   assert( p->pPage==0 );
42232   assert( p->flags==PGHDR_MMAP );
42233   assert( p->pPager==pPager );
42234   assert( p->nRef==1 );
42235
42236   p->pgno = pgno;
42237   p->pData = pData;
42238   pPager->nMmapOut++;
42239
42240   return SQLITE_OK;
42241 }
42242
42243 /*
42244 ** Release a reference to page pPg. pPg must have been returned by an 
42245 ** earlier call to pagerAcquireMapPage().
42246 */
42247 static void pagerReleaseMapPage(PgHdr *pPg){
42248   Pager *pPager = pPg->pPager;
42249   pPager->nMmapOut--;
42250   pPg->pDirty = pPager->pMmapFreelist;
42251   pPager->pMmapFreelist = pPg;
42252
42253   assert( pPager->fd->pMethods->iVersion>=3 );
42254   sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
42255 }
42256
42257 /*
42258 ** Free all PgHdr objects stored in the Pager.pMmapFreelist list.
42259 */
42260 static void pagerFreeMapHdrs(Pager *pPager){
42261   PgHdr *p;
42262   PgHdr *pNext;
42263   for(p=pPager->pMmapFreelist; p; p=pNext){
42264     pNext = p->pDirty;
42265     sqlite3_free(p);
42266   }
42267 }
42268
42269
42270 /*
42271 ** Shutdown the page cache.  Free all memory and close all files.
42272 **
42273 ** If a transaction was in progress when this routine is called, that
42274 ** transaction is rolled back.  All outstanding pages are invalidated
42275 ** and their memory is freed.  Any attempt to use a page associated
42276 ** with this page cache after this function returns will likely
42277 ** result in a coredump.
42278 **
42279 ** This function always succeeds. If a transaction is active an attempt
42280 ** is made to roll it back. If an error occurs during the rollback 
42281 ** a hot journal may be left in the filesystem but no error is returned
42282 ** to the caller.
42283 */
42284 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
42285   u8 *pTmp = (u8 *)pPager->pTmpSpace;
42286
42287   assert( assert_pager_state(pPager) );
42288   disable_simulated_io_errors();
42289   sqlite3BeginBenignMalloc();
42290   pagerFreeMapHdrs(pPager);
42291   /* pPager->errCode = 0; */
42292   pPager->exclusiveMode = 0;
42293 #ifndef SQLITE_OMIT_WAL
42294   sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
42295   pPager->pWal = 0;
42296 #endif
42297   pager_reset(pPager);
42298   if( MEMDB ){
42299     pager_unlock(pPager);
42300   }else{
42301     /* If it is open, sync the journal file before calling UnlockAndRollback.
42302     ** If this is not done, then an unsynced portion of the open journal 
42303     ** file may be played back into the database. If a power failure occurs 
42304     ** while this is happening, the database could become corrupt.
42305     **
42306     ** If an error occurs while trying to sync the journal, shift the pager
42307     ** into the ERROR state. This causes UnlockAndRollback to unlock the
42308     ** database and close the journal file without attempting to roll it
42309     ** back or finalize it. The next database user will have to do hot-journal
42310     ** rollback before accessing the database file.
42311     */
42312     if( isOpen(pPager->jfd) ){
42313       pager_error(pPager, pagerSyncHotJournal(pPager));
42314     }
42315     pagerUnlockAndRollback(pPager);
42316   }
42317   sqlite3EndBenignMalloc();
42318   enable_simulated_io_errors();
42319   PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
42320   IOTRACE(("CLOSE %p\n", pPager))
42321   sqlite3OsClose(pPager->jfd);
42322   sqlite3OsClose(pPager->fd);
42323   sqlite3PageFree(pTmp);
42324   sqlite3PcacheClose(pPager->pPCache);
42325
42326 #ifdef SQLITE_HAS_CODEC
42327   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
42328 #endif
42329
42330   assert( !pPager->aSavepoint && !pPager->pInJournal );
42331   assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
42332
42333   sqlite3_free(pPager);
42334   return SQLITE_OK;
42335 }
42336
42337 #if !defined(NDEBUG) || defined(SQLITE_TEST)
42338 /*
42339 ** Return the page number for page pPg.
42340 */
42341 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
42342   return pPg->pgno;
42343 }
42344 #endif
42345
42346 /*
42347 ** Increment the reference count for page pPg.
42348 */
42349 SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
42350   sqlite3PcacheRef(pPg);
42351 }
42352
42353 /*
42354 ** Sync the journal. In other words, make sure all the pages that have
42355 ** been written to the journal have actually reached the surface of the
42356 ** disk and can be restored in the event of a hot-journal rollback.
42357 **
42358 ** If the Pager.noSync flag is set, then this function is a no-op.
42359 ** Otherwise, the actions required depend on the journal-mode and the 
42360 ** device characteristics of the file-system, as follows:
42361 **
42362 **   * If the journal file is an in-memory journal file, no action need
42363 **     be taken.
42364 **
42365 **   * Otherwise, if the device does not support the SAFE_APPEND property,
42366 **     then the nRec field of the most recently written journal header
42367 **     is updated to contain the number of journal records that have
42368 **     been written following it. If the pager is operating in full-sync
42369 **     mode, then the journal file is synced before this field is updated.
42370 **
42371 **   * If the device does not support the SEQUENTIAL property, then 
42372 **     journal file is synced.
42373 **
42374 ** Or, in pseudo-code:
42375 **
42376 **   if( NOT <in-memory journal> ){
42377 **     if( NOT SAFE_APPEND ){
42378 **       if( <full-sync mode> ) xSync(<journal file>);
42379 **       <update nRec field>
42380 **     } 
42381 **     if( NOT SEQUENTIAL ) xSync(<journal file>);
42382 **   }
42383 **
42384 ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every 
42385 ** page currently held in memory before returning SQLITE_OK. If an IO
42386 ** error is encountered, then the IO error code is returned to the caller.
42387 */
42388 static int syncJournal(Pager *pPager, int newHdr){
42389   int rc;                         /* Return code */
42390
42391   assert( pPager->eState==PAGER_WRITER_CACHEMOD
42392        || pPager->eState==PAGER_WRITER_DBMOD
42393   );
42394   assert( assert_pager_state(pPager) );
42395   assert( !pagerUseWal(pPager) );
42396
42397   rc = sqlite3PagerExclusiveLock(pPager);
42398   if( rc!=SQLITE_OK ) return rc;
42399
42400   if( !pPager->noSync ){
42401     assert( !pPager->tempFile );
42402     if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
42403       const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
42404       assert( isOpen(pPager->jfd) );
42405
42406       if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
42407         /* This block deals with an obscure problem. If the last connection
42408         ** that wrote to this database was operating in persistent-journal
42409         ** mode, then the journal file may at this point actually be larger
42410         ** than Pager.journalOff bytes. If the next thing in the journal
42411         ** file happens to be a journal-header (written as part of the
42412         ** previous connection's transaction), and a crash or power-failure 
42413         ** occurs after nRec is updated but before this connection writes 
42414         ** anything else to the journal file (or commits/rolls back its 
42415         ** transaction), then SQLite may become confused when doing the 
42416         ** hot-journal rollback following recovery. It may roll back all
42417         ** of this connections data, then proceed to rolling back the old,
42418         ** out-of-date data that follows it. Database corruption.
42419         **
42420         ** To work around this, if the journal file does appear to contain
42421         ** a valid header following Pager.journalOff, then write a 0x00
42422         ** byte to the start of it to prevent it from being recognized.
42423         **
42424         ** Variable iNextHdrOffset is set to the offset at which this
42425         ** problematic header will occur, if it exists. aMagic is used 
42426         ** as a temporary buffer to inspect the first couple of bytes of
42427         ** the potential journal header.
42428         */
42429         i64 iNextHdrOffset;
42430         u8 aMagic[8];
42431         u8 zHeader[sizeof(aJournalMagic)+4];
42432
42433         memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
42434         put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
42435
42436         iNextHdrOffset = journalHdrOffset(pPager);
42437         rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
42438         if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
42439           static const u8 zerobyte = 0;
42440           rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
42441         }
42442         if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
42443           return rc;
42444         }
42445
42446         /* Write the nRec value into the journal file header. If in
42447         ** full-synchronous mode, sync the journal first. This ensures that
42448         ** all data has really hit the disk before nRec is updated to mark
42449         ** it as a candidate for rollback.
42450         **
42451         ** This is not required if the persistent media supports the
42452         ** SAFE_APPEND property. Because in this case it is not possible 
42453         ** for garbage data to be appended to the file, the nRec field
42454         ** is populated with 0xFFFFFFFF when the journal header is written
42455         ** and never needs to be updated.
42456         */
42457         if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
42458           PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
42459           IOTRACE(("JSYNC %p\n", pPager))
42460           rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
42461           if( rc!=SQLITE_OK ) return rc;
42462         }
42463         IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
42464         rc = sqlite3OsWrite(
42465             pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
42466         );
42467         if( rc!=SQLITE_OK ) return rc;
42468       }
42469       if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
42470         PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
42471         IOTRACE(("JSYNC %p\n", pPager))
42472         rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags| 
42473           (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
42474         );
42475         if( rc!=SQLITE_OK ) return rc;
42476       }
42477
42478       pPager->journalHdr = pPager->journalOff;
42479       if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
42480         pPager->nRec = 0;
42481         rc = writeJournalHdr(pPager);
42482         if( rc!=SQLITE_OK ) return rc;
42483       }
42484     }else{
42485       pPager->journalHdr = pPager->journalOff;
42486     }
42487   }
42488
42489   /* Unless the pager is in noSync mode, the journal file was just 
42490   ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on 
42491   ** all pages.
42492   */
42493   sqlite3PcacheClearSyncFlags(pPager->pPCache);
42494   pPager->eState = PAGER_WRITER_DBMOD;
42495   assert( assert_pager_state(pPager) );
42496   return SQLITE_OK;
42497 }
42498
42499 /*
42500 ** The argument is the first in a linked list of dirty pages connected
42501 ** by the PgHdr.pDirty pointer. This function writes each one of the
42502 ** in-memory pages in the list to the database file. The argument may
42503 ** be NULL, representing an empty list. In this case this function is
42504 ** a no-op.
42505 **
42506 ** The pager must hold at least a RESERVED lock when this function
42507 ** is called. Before writing anything to the database file, this lock
42508 ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
42509 ** SQLITE_BUSY is returned and no data is written to the database file.
42510 ** 
42511 ** If the pager is a temp-file pager and the actual file-system file
42512 ** is not yet open, it is created and opened before any data is 
42513 ** written out.
42514 **
42515 ** Once the lock has been upgraded and, if necessary, the file opened,
42516 ** the pages are written out to the database file in list order. Writing
42517 ** a page is skipped if it meets either of the following criteria:
42518 **
42519 **   * The page number is greater than Pager.dbSize, or
42520 **   * The PGHDR_DONT_WRITE flag is set on the page.
42521 **
42522 ** If writing out a page causes the database file to grow, Pager.dbFileSize
42523 ** is updated accordingly. If page 1 is written out, then the value cached
42524 ** in Pager.dbFileVers[] is updated to match the new value stored in
42525 ** the database file.
42526 **
42527 ** If everything is successful, SQLITE_OK is returned. If an IO error 
42528 ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
42529 ** be obtained, SQLITE_BUSY is returned.
42530 */
42531 static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
42532   int rc = SQLITE_OK;                  /* Return code */
42533
42534   /* This function is only called for rollback pagers in WRITER_DBMOD state. */
42535   assert( !pagerUseWal(pPager) );
42536   assert( pPager->eState==PAGER_WRITER_DBMOD );
42537   assert( pPager->eLock==EXCLUSIVE_LOCK );
42538
42539   /* If the file is a temp-file has not yet been opened, open it now. It
42540   ** is not possible for rc to be other than SQLITE_OK if this branch
42541   ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
42542   */
42543   if( !isOpen(pPager->fd) ){
42544     assert( pPager->tempFile && rc==SQLITE_OK );
42545     rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
42546   }
42547
42548   /* Before the first write, give the VFS a hint of what the final
42549   ** file size will be.
42550   */
42551   assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
42552   if( rc==SQLITE_OK 
42553    && (pList->pDirty ? pPager->dbSize : pList->pgno+1)>pPager->dbHintSize 
42554   ){
42555     sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
42556     sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
42557     pPager->dbHintSize = pPager->dbSize;
42558   }
42559
42560   while( rc==SQLITE_OK && pList ){
42561     Pgno pgno = pList->pgno;
42562
42563     /* If there are dirty pages in the page cache with page numbers greater
42564     ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
42565     ** make the file smaller (presumably by auto-vacuum code). Do not write
42566     ** any such pages to the file.
42567     **
42568     ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
42569     ** set (set by sqlite3PagerDontWrite()).
42570     */
42571     if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
42572       i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
42573       char *pData;                                   /* Data to write */    
42574
42575       assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
42576       if( pList->pgno==1 ) pager_write_changecounter(pList);
42577
42578       /* Encode the database */
42579       CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
42580
42581       /* Write out the page data. */
42582       rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
42583
42584       /* If page 1 was just written, update Pager.dbFileVers to match
42585       ** the value now stored in the database file. If writing this 
42586       ** page caused the database file to grow, update dbFileSize. 
42587       */
42588       if( pgno==1 ){
42589         memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
42590       }
42591       if( pgno>pPager->dbFileSize ){
42592         pPager->dbFileSize = pgno;
42593       }
42594       pPager->aStat[PAGER_STAT_WRITE]++;
42595
42596       /* Update any backup objects copying the contents of this pager. */
42597       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
42598
42599       PAGERTRACE(("STORE %d page %d hash(%08x)\n",
42600                    PAGERID(pPager), pgno, pager_pagehash(pList)));
42601       IOTRACE(("PGOUT %p %d\n", pPager, pgno));
42602       PAGER_INCR(sqlite3_pager_writedb_count);
42603     }else{
42604       PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
42605     }
42606     pager_set_pagehash(pList);
42607     pList = pList->pDirty;
42608   }
42609
42610   return rc;
42611 }
42612
42613 /*
42614 ** Ensure that the sub-journal file is open. If it is already open, this 
42615 ** function is a no-op.
42616 **
42617 ** SQLITE_OK is returned if everything goes according to plan. An 
42618 ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen() 
42619 ** fails.
42620 */
42621 static int openSubJournal(Pager *pPager){
42622   int rc = SQLITE_OK;
42623   if( !isOpen(pPager->sjfd) ){
42624     if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
42625       sqlite3MemJournalOpen(pPager->sjfd);
42626     }else{
42627       rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
42628     }
42629   }
42630   return rc;
42631 }
42632
42633 /*
42634 ** Append a record of the current state of page pPg to the sub-journal. 
42635 ** It is the callers responsibility to use subjRequiresPage() to check 
42636 ** that it is really required before calling this function.
42637 **
42638 ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
42639 ** for all open savepoints before returning.
42640 **
42641 ** This function returns SQLITE_OK if everything is successful, an IO
42642 ** error code if the attempt to write to the sub-journal fails, or 
42643 ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
42644 ** bitvec.
42645 */
42646 static int subjournalPage(PgHdr *pPg){
42647   int rc = SQLITE_OK;
42648   Pager *pPager = pPg->pPager;
42649   if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
42650
42651     /* Open the sub-journal, if it has not already been opened */
42652     assert( pPager->useJournal );
42653     assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
42654     assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
42655     assert( pagerUseWal(pPager) 
42656          || pageInJournal(pPg) 
42657          || pPg->pgno>pPager->dbOrigSize 
42658     );
42659     rc = openSubJournal(pPager);
42660
42661     /* If the sub-journal was opened successfully (or was already open),
42662     ** write the journal record into the file.  */
42663     if( rc==SQLITE_OK ){
42664       void *pData = pPg->pData;
42665       i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
42666       char *pData2;
42667   
42668       CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
42669       PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
42670       rc = write32bits(pPager->sjfd, offset, pPg->pgno);
42671       if( rc==SQLITE_OK ){
42672         rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
42673       }
42674     }
42675   }
42676   if( rc==SQLITE_OK ){
42677     pPager->nSubRec++;
42678     assert( pPager->nSavepoint>0 );
42679     rc = addToSavepointBitvecs(pPager, pPg->pgno);
42680   }
42681   return rc;
42682 }
42683
42684 /*
42685 ** This function is called by the pcache layer when it has reached some
42686 ** soft memory limit. The first argument is a pointer to a Pager object
42687 ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
42688 ** database). The second argument is a reference to a page that is 
42689 ** currently dirty but has no outstanding references. The page
42690 ** is always associated with the Pager object passed as the first 
42691 ** argument.
42692 **
42693 ** The job of this function is to make pPg clean by writing its contents
42694 ** out to the database file, if possible. This may involve syncing the
42695 ** journal file. 
42696 **
42697 ** If successful, sqlite3PcacheMakeClean() is called on the page and
42698 ** SQLITE_OK returned. If an IO error occurs while trying to make the
42699 ** page clean, the IO error code is returned. If the page cannot be
42700 ** made clean for some other reason, but no error occurs, then SQLITE_OK
42701 ** is returned by sqlite3PcacheMakeClean() is not called.
42702 */
42703 static int pagerStress(void *p, PgHdr *pPg){
42704   Pager *pPager = (Pager *)p;
42705   int rc = SQLITE_OK;
42706
42707   assert( pPg->pPager==pPager );
42708   assert( pPg->flags&PGHDR_DIRTY );
42709
42710   /* The doNotSyncSpill flag is set during times when doing a sync of
42711   ** journal (and adding a new header) is not allowed.  This occurs
42712   ** during calls to sqlite3PagerWrite() while trying to journal multiple
42713   ** pages belonging to the same sector.
42714   **
42715   ** The doNotSpill flag inhibits all cache spilling regardless of whether
42716   ** or not a sync is required.  This is set during a rollback.
42717   **
42718   ** Spilling is also prohibited when in an error state since that could
42719   ** lead to database corruption.   In the current implementaton it 
42720   ** is impossible for sqlite3PcacheFetch() to be called with createFlag==1
42721   ** while in the error state, hence it is impossible for this routine to
42722   ** be called in the error state.  Nevertheless, we include a NEVER()
42723   ** test for the error state as a safeguard against future changes.
42724   */
42725   if( NEVER(pPager->errCode) ) return SQLITE_OK;
42726   if( pPager->doNotSpill ) return SQLITE_OK;
42727   if( pPager->doNotSyncSpill && (pPg->flags & PGHDR_NEED_SYNC)!=0 ){
42728     return SQLITE_OK;
42729   }
42730
42731   pPg->pDirty = 0;
42732   if( pagerUseWal(pPager) ){
42733     /* Write a single frame for this page to the log. */
42734     if( subjRequiresPage(pPg) ){ 
42735       rc = subjournalPage(pPg); 
42736     }
42737     if( rc==SQLITE_OK ){
42738       rc = pagerWalFrames(pPager, pPg, 0, 0);
42739     }
42740   }else{
42741   
42742     /* Sync the journal file if required. */
42743     if( pPg->flags&PGHDR_NEED_SYNC 
42744      || pPager->eState==PAGER_WRITER_CACHEMOD
42745     ){
42746       rc = syncJournal(pPager, 1);
42747     }
42748   
42749     /* If the page number of this page is larger than the current size of
42750     ** the database image, it may need to be written to the sub-journal.
42751     ** This is because the call to pager_write_pagelist() below will not
42752     ** actually write data to the file in this case.
42753     **
42754     ** Consider the following sequence of events:
42755     **
42756     **   BEGIN;
42757     **     <journal page X>
42758     **     <modify page X>
42759     **     SAVEPOINT sp;
42760     **       <shrink database file to Y pages>
42761     **       pagerStress(page X)
42762     **     ROLLBACK TO sp;
42763     **
42764     ** If (X>Y), then when pagerStress is called page X will not be written
42765     ** out to the database file, but will be dropped from the cache. Then,
42766     ** following the "ROLLBACK TO sp" statement, reading page X will read
42767     ** data from the database file. This will be the copy of page X as it
42768     ** was when the transaction started, not as it was when "SAVEPOINT sp"
42769     ** was executed.
42770     **
42771     ** The solution is to write the current data for page X into the 
42772     ** sub-journal file now (if it is not already there), so that it will
42773     ** be restored to its current value when the "ROLLBACK TO sp" is 
42774     ** executed.
42775     */
42776     if( NEVER(
42777         rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
42778     ) ){
42779       rc = subjournalPage(pPg);
42780     }
42781   
42782     /* Write the contents of the page out to the database file. */
42783     if( rc==SQLITE_OK ){
42784       assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
42785       rc = pager_write_pagelist(pPager, pPg);
42786     }
42787   }
42788
42789   /* Mark the page as clean. */
42790   if( rc==SQLITE_OK ){
42791     PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
42792     sqlite3PcacheMakeClean(pPg);
42793   }
42794
42795   return pager_error(pPager, rc); 
42796 }
42797
42798
42799 /*
42800 ** Allocate and initialize a new Pager object and put a pointer to it
42801 ** in *ppPager. The pager should eventually be freed by passing it
42802 ** to sqlite3PagerClose().
42803 **
42804 ** The zFilename argument is the path to the database file to open.
42805 ** If zFilename is NULL then a randomly-named temporary file is created
42806 ** and used as the file to be cached. Temporary files are be deleted
42807 ** automatically when they are closed. If zFilename is ":memory:" then 
42808 ** all information is held in cache. It is never written to disk. 
42809 ** This can be used to implement an in-memory database.
42810 **
42811 ** The nExtra parameter specifies the number of bytes of space allocated
42812 ** along with each page reference. This space is available to the user
42813 ** via the sqlite3PagerGetExtra() API.
42814 **
42815 ** The flags argument is used to specify properties that affect the
42816 ** operation of the pager. It should be passed some bitwise combination
42817 ** of the PAGER_* flags.
42818 **
42819 ** The vfsFlags parameter is a bitmask to pass to the flags parameter
42820 ** of the xOpen() method of the supplied VFS when opening files. 
42821 **
42822 ** If the pager object is allocated and the specified file opened 
42823 ** successfully, SQLITE_OK is returned and *ppPager set to point to
42824 ** the new pager object. If an error occurs, *ppPager is set to NULL
42825 ** and error code returned. This function may return SQLITE_NOMEM
42826 ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or 
42827 ** various SQLITE_IO_XXX errors.
42828 */
42829 SQLITE_PRIVATE int sqlite3PagerOpen(
42830   sqlite3_vfs *pVfs,       /* The virtual file system to use */
42831   Pager **ppPager,         /* OUT: Return the Pager structure here */
42832   const char *zFilename,   /* Name of the database file to open */
42833   int nExtra,              /* Extra bytes append to each in-memory page */
42834   int flags,               /* flags controlling this file */
42835   int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
42836   void (*xReinit)(DbPage*) /* Function to reinitialize pages */
42837 ){
42838   u8 *pPtr;
42839   Pager *pPager = 0;       /* Pager object to allocate and return */
42840   int rc = SQLITE_OK;      /* Return code */
42841   int tempFile = 0;        /* True for temp files (incl. in-memory files) */
42842   int memDb = 0;           /* True if this is an in-memory file */
42843   int readOnly = 0;        /* True if this is a read-only file */
42844   int journalFileSize;     /* Bytes to allocate for each journal fd */
42845   char *zPathname = 0;     /* Full path to database file */
42846   int nPathname = 0;       /* Number of bytes in zPathname */
42847   int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
42848   int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
42849   u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
42850   const char *zUri = 0;    /* URI args to copy */
42851   int nUri = 0;            /* Number of bytes of URI args at *zUri */
42852
42853   /* Figure out how much space is required for each journal file-handle
42854   ** (there are two of them, the main journal and the sub-journal). This
42855   ** is the maximum space required for an in-memory journal file handle 
42856   ** and a regular journal file-handle. Note that a "regular journal-handle"
42857   ** may be a wrapper capable of caching the first portion of the journal
42858   ** file in memory to implement the atomic-write optimization (see 
42859   ** source file journal.c).
42860   */
42861   if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
42862     journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
42863   }else{
42864     journalFileSize = ROUND8(sqlite3MemJournalSize());
42865   }
42866
42867   /* Set the output variable to NULL in case an error occurs. */
42868   *ppPager = 0;
42869
42870 #ifndef SQLITE_OMIT_MEMORYDB
42871   if( flags & PAGER_MEMORY ){
42872     memDb = 1;
42873     if( zFilename && zFilename[0] ){
42874       zPathname = sqlite3DbStrDup(0, zFilename);
42875       if( zPathname==0  ) return SQLITE_NOMEM;
42876       nPathname = sqlite3Strlen30(zPathname);
42877       zFilename = 0;
42878     }
42879   }
42880 #endif
42881
42882   /* Compute and store the full pathname in an allocated buffer pointed
42883   ** to by zPathname, length nPathname. Or, if this is a temporary file,
42884   ** leave both nPathname and zPathname set to 0.
42885   */
42886   if( zFilename && zFilename[0] ){
42887     const char *z;
42888     nPathname = pVfs->mxPathname+1;
42889     zPathname = sqlite3DbMallocRaw(0, nPathname*2);
42890     if( zPathname==0 ){
42891       return SQLITE_NOMEM;
42892     }
42893     zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
42894     rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
42895     nPathname = sqlite3Strlen30(zPathname);
42896     z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
42897     while( *z ){
42898       z += sqlite3Strlen30(z)+1;
42899       z += sqlite3Strlen30(z)+1;
42900     }
42901     nUri = (int)(&z[1] - zUri);
42902     assert( nUri>=0 );
42903     if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
42904       /* This branch is taken when the journal path required by
42905       ** the database being opened will be more than pVfs->mxPathname
42906       ** bytes in length. This means the database cannot be opened,
42907       ** as it will not be possible to open the journal file or even
42908       ** check for a hot-journal before reading.
42909       */
42910       rc = SQLITE_CANTOPEN_BKPT;
42911     }
42912     if( rc!=SQLITE_OK ){
42913       sqlite3DbFree(0, zPathname);
42914       return rc;
42915     }
42916   }
42917
42918   /* Allocate memory for the Pager structure, PCache object, the
42919   ** three file descriptors, the database file name and the journal 
42920   ** file name. The layout in memory is as follows:
42921   **
42922   **     Pager object                    (sizeof(Pager) bytes)
42923   **     PCache object                   (sqlite3PcacheSize() bytes)
42924   **     Database file handle            (pVfs->szOsFile bytes)
42925   **     Sub-journal file handle         (journalFileSize bytes)
42926   **     Main journal file handle        (journalFileSize bytes)
42927   **     Database file name              (nPathname+1 bytes)
42928   **     Journal file name               (nPathname+8+1 bytes)
42929   */
42930   pPtr = (u8 *)sqlite3MallocZero(
42931     ROUND8(sizeof(*pPager)) +      /* Pager structure */
42932     ROUND8(pcacheSize) +           /* PCache object */
42933     ROUND8(pVfs->szOsFile) +       /* The main db file */
42934     journalFileSize * 2 +          /* The two journal files */ 
42935     nPathname + 1 + nUri +         /* zFilename */
42936     nPathname + 8 + 2              /* zJournal */
42937 #ifndef SQLITE_OMIT_WAL
42938     + nPathname + 4 + 2            /* zWal */
42939 #endif
42940   );
42941   assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
42942   if( !pPtr ){
42943     sqlite3DbFree(0, zPathname);
42944     return SQLITE_NOMEM;
42945   }
42946   pPager =              (Pager*)(pPtr);
42947   pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
42948   pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
42949   pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
42950   pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
42951   pPager->zFilename =    (char*)(pPtr += journalFileSize);
42952   assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
42953
42954   /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
42955   if( zPathname ){
42956     assert( nPathname>0 );
42957     pPager->zJournal =   (char*)(pPtr += nPathname + 1 + nUri);
42958     memcpy(pPager->zFilename, zPathname, nPathname);
42959     if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
42960     memcpy(pPager->zJournal, zPathname, nPathname);
42961     memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
42962     sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
42963 #ifndef SQLITE_OMIT_WAL
42964     pPager->zWal = &pPager->zJournal[nPathname+8+1];
42965     memcpy(pPager->zWal, zPathname, nPathname);
42966     memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
42967     sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
42968 #endif
42969     sqlite3DbFree(0, zPathname);
42970   }
42971   pPager->pVfs = pVfs;
42972   pPager->vfsFlags = vfsFlags;
42973
42974   /* Open the pager file.
42975   */
42976   if( zFilename && zFilename[0] ){
42977     int fout = 0;                    /* VFS flags returned by xOpen() */
42978     rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
42979     assert( !memDb );
42980     readOnly = (fout&SQLITE_OPEN_READONLY);
42981
42982     /* If the file was successfully opened for read/write access,
42983     ** choose a default page size in case we have to create the
42984     ** database file. The default page size is the maximum of:
42985     **
42986     **    + SQLITE_DEFAULT_PAGE_SIZE,
42987     **    + The value returned by sqlite3OsSectorSize()
42988     **    + The largest page size that can be written atomically.
42989     */
42990     if( rc==SQLITE_OK && !readOnly ){
42991       setSectorSize(pPager);
42992       assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
42993       if( szPageDflt<pPager->sectorSize ){
42994         if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
42995           szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
42996         }else{
42997           szPageDflt = (u32)pPager->sectorSize;
42998         }
42999       }
43000 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
43001       {
43002         int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
43003         int ii;
43004         assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
43005         assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
43006         assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
43007         for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
43008           if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
43009             szPageDflt = ii;
43010           }
43011         }
43012       }
43013 #endif
43014     }
43015   }else{
43016     /* If a temporary file is requested, it is not opened immediately.
43017     ** In this case we accept the default page size and delay actually
43018     ** opening the file until the first call to OsWrite().
43019     **
43020     ** This branch is also run for an in-memory database. An in-memory
43021     ** database is the same as a temp-file that is never written out to
43022     ** disk and uses an in-memory rollback journal.
43023     */ 
43024     tempFile = 1;
43025     pPager->eState = PAGER_READER;
43026     pPager->eLock = EXCLUSIVE_LOCK;
43027     readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
43028   }
43029
43030   /* The following call to PagerSetPagesize() serves to set the value of 
43031   ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
43032   */
43033   if( rc==SQLITE_OK ){
43034     assert( pPager->memDb==0 );
43035     rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
43036     testcase( rc!=SQLITE_OK );
43037   }
43038
43039   /* If an error occurred in either of the blocks above, free the 
43040   ** Pager structure and close the file.
43041   */
43042   if( rc!=SQLITE_OK ){
43043     assert( !pPager->pTmpSpace );
43044     sqlite3OsClose(pPager->fd);
43045     sqlite3_free(pPager);
43046     return rc;
43047   }
43048
43049   /* Initialize the PCache object. */
43050   assert( nExtra<1000 );
43051   nExtra = ROUND8(nExtra);
43052   sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
43053                     !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
43054
43055   PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
43056   IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
43057
43058   pPager->useJournal = (u8)useJournal;
43059   /* pPager->stmtOpen = 0; */
43060   /* pPager->stmtInUse = 0; */
43061   /* pPager->nRef = 0; */
43062   /* pPager->stmtSize = 0; */
43063   /* pPager->stmtJSize = 0; */
43064   /* pPager->nPage = 0; */
43065   pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
43066   /* pPager->state = PAGER_UNLOCK; */
43067 #if 0
43068   assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
43069 #endif
43070   /* pPager->errMask = 0; */
43071   pPager->tempFile = (u8)tempFile;
43072   assert( tempFile==PAGER_LOCKINGMODE_NORMAL 
43073           || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
43074   assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
43075   pPager->exclusiveMode = (u8)tempFile; 
43076   pPager->changeCountDone = pPager->tempFile;
43077   pPager->memDb = (u8)memDb;
43078   pPager->readOnly = (u8)readOnly;
43079   assert( useJournal || pPager->tempFile );
43080   pPager->noSync = pPager->tempFile;
43081   if( pPager->noSync ){
43082     assert( pPager->fullSync==0 );
43083     assert( pPager->syncFlags==0 );
43084     assert( pPager->walSyncFlags==0 );
43085     assert( pPager->ckptSyncFlags==0 );
43086   }else{
43087     pPager->fullSync = 1;
43088     pPager->syncFlags = SQLITE_SYNC_NORMAL;
43089     pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS;
43090     pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
43091   }
43092   /* pPager->pFirst = 0; */
43093   /* pPager->pFirstSynced = 0; */
43094   /* pPager->pLast = 0; */
43095   pPager->nExtra = (u16)nExtra;
43096   pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
43097   assert( isOpen(pPager->fd) || tempFile );
43098   setSectorSize(pPager);
43099   if( !useJournal ){
43100     pPager->journalMode = PAGER_JOURNALMODE_OFF;
43101   }else if( memDb ){
43102     pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
43103   }
43104   /* pPager->xBusyHandler = 0; */
43105   /* pPager->pBusyHandlerArg = 0; */
43106   pPager->xReiniter = xReinit;
43107   /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
43108   /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
43109
43110   *ppPager = pPager;
43111   return SQLITE_OK;
43112 }
43113
43114
43115
43116 /*
43117 ** This function is called after transitioning from PAGER_UNLOCK to
43118 ** PAGER_SHARED state. It tests if there is a hot journal present in
43119 ** the file-system for the given pager. A hot journal is one that 
43120 ** needs to be played back. According to this function, a hot-journal
43121 ** file exists if the following criteria are met:
43122 **
43123 **   * The journal file exists in the file system, and
43124 **   * No process holds a RESERVED or greater lock on the database file, and
43125 **   * The database file itself is greater than 0 bytes in size, and
43126 **   * The first byte of the journal file exists and is not 0x00.
43127 **
43128 ** If the current size of the database file is 0 but a journal file
43129 ** exists, that is probably an old journal left over from a prior
43130 ** database with the same name. In this case the journal file is
43131 ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
43132 ** is returned.
43133 **
43134 ** This routine does not check if there is a master journal filename
43135 ** at the end of the file. If there is, and that master journal file
43136 ** does not exist, then the journal file is not really hot. In this
43137 ** case this routine will return a false-positive. The pager_playback()
43138 ** routine will discover that the journal file is not really hot and 
43139 ** will not roll it back. 
43140 **
43141 ** If a hot-journal file is found to exist, *pExists is set to 1 and 
43142 ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
43143 ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
43144 ** to determine whether or not a hot-journal file exists, the IO error
43145 ** code is returned and the value of *pExists is undefined.
43146 */
43147 static int hasHotJournal(Pager *pPager, int *pExists){
43148   sqlite3_vfs * const pVfs = pPager->pVfs;
43149   int rc = SQLITE_OK;           /* Return code */
43150   int exists = 1;               /* True if a journal file is present */
43151   int jrnlOpen = !!isOpen(pPager->jfd);
43152
43153   assert( pPager->useJournal );
43154   assert( isOpen(pPager->fd) );
43155   assert( pPager->eState==PAGER_OPEN );
43156
43157   assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
43158     SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
43159   ));
43160
43161   *pExists = 0;
43162   if( !jrnlOpen ){
43163     rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
43164   }
43165   if( rc==SQLITE_OK && exists ){
43166     int locked = 0;             /* True if some process holds a RESERVED lock */
43167
43168     /* Race condition here:  Another process might have been holding the
43169     ** the RESERVED lock and have a journal open at the sqlite3OsAccess() 
43170     ** call above, but then delete the journal and drop the lock before
43171     ** we get to the following sqlite3OsCheckReservedLock() call.  If that
43172     ** is the case, this routine might think there is a hot journal when
43173     ** in fact there is none.  This results in a false-positive which will
43174     ** be dealt with by the playback routine.  Ticket #3883.
43175     */
43176     rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
43177     if( rc==SQLITE_OK && !locked ){
43178       Pgno nPage;                 /* Number of pages in database file */
43179
43180       /* Check the size of the database file. If it consists of 0 pages,
43181       ** then delete the journal file. See the header comment above for 
43182       ** the reasoning here.  Delete the obsolete journal file under
43183       ** a RESERVED lock to avoid race conditions and to avoid violating
43184       ** [H33020].
43185       */
43186       rc = pagerPagecount(pPager, &nPage);
43187       if( rc==SQLITE_OK ){
43188         if( nPage==0 ){
43189           sqlite3BeginBenignMalloc();
43190           if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
43191             sqlite3OsDelete(pVfs, pPager->zJournal, 0);
43192             if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
43193           }
43194           sqlite3EndBenignMalloc();
43195         }else{
43196           /* The journal file exists and no other connection has a reserved
43197           ** or greater lock on the database file. Now check that there is
43198           ** at least one non-zero bytes at the start of the journal file.
43199           ** If there is, then we consider this journal to be hot. If not, 
43200           ** it can be ignored.
43201           */
43202           if( !jrnlOpen ){
43203             int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
43204             rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
43205           }
43206           if( rc==SQLITE_OK ){
43207             u8 first = 0;
43208             rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
43209             if( rc==SQLITE_IOERR_SHORT_READ ){
43210               rc = SQLITE_OK;
43211             }
43212             if( !jrnlOpen ){
43213               sqlite3OsClose(pPager->jfd);
43214             }
43215             *pExists = (first!=0);
43216           }else if( rc==SQLITE_CANTOPEN ){
43217             /* If we cannot open the rollback journal file in order to see if
43218             ** its has a zero header, that might be due to an I/O error, or
43219             ** it might be due to the race condition described above and in
43220             ** ticket #3883.  Either way, assume that the journal is hot.
43221             ** This might be a false positive.  But if it is, then the
43222             ** automatic journal playback and recovery mechanism will deal
43223             ** with it under an EXCLUSIVE lock where we do not need to
43224             ** worry so much with race conditions.
43225             */
43226             *pExists = 1;
43227             rc = SQLITE_OK;
43228           }
43229         }
43230       }
43231     }
43232   }
43233
43234   return rc;
43235 }
43236
43237 /*
43238 ** This function is called to obtain a shared lock on the database file.
43239 ** It is illegal to call sqlite3PagerAcquire() until after this function
43240 ** has been successfully called. If a shared-lock is already held when
43241 ** this function is called, it is a no-op.
43242 **
43243 ** The following operations are also performed by this function.
43244 **
43245 **   1) If the pager is currently in PAGER_OPEN state (no lock held
43246 **      on the database file), then an attempt is made to obtain a
43247 **      SHARED lock on the database file. Immediately after obtaining
43248 **      the SHARED lock, the file-system is checked for a hot-journal,
43249 **      which is played back if present. Following any hot-journal 
43250 **      rollback, the contents of the cache are validated by checking
43251 **      the 'change-counter' field of the database file header and
43252 **      discarded if they are found to be invalid.
43253 **
43254 **   2) If the pager is running in exclusive-mode, and there are currently
43255 **      no outstanding references to any pages, and is in the error state,
43256 **      then an attempt is made to clear the error state by discarding
43257 **      the contents of the page cache and rolling back any open journal
43258 **      file.
43259 **
43260 ** If everything is successful, SQLITE_OK is returned. If an IO error 
43261 ** occurs while locking the database, checking for a hot-journal file or 
43262 ** rolling back a journal file, the IO error code is returned.
43263 */
43264 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
43265   int rc = SQLITE_OK;                /* Return code */
43266
43267   /* This routine is only called from b-tree and only when there are no
43268   ** outstanding pages. This implies that the pager state should either
43269   ** be OPEN or READER. READER is only possible if the pager is or was in 
43270   ** exclusive access mode.
43271   */
43272   assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
43273   assert( assert_pager_state(pPager) );
43274   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
43275   if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
43276
43277   if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
43278     int bHotJournal = 1;          /* True if there exists a hot journal-file */
43279
43280     assert( !MEMDB );
43281
43282     rc = pager_wait_on_lock(pPager, SHARED_LOCK);
43283     if( rc!=SQLITE_OK ){
43284       assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
43285       goto failed;
43286     }
43287
43288     /* If a journal file exists, and there is no RESERVED lock on the
43289     ** database file, then it either needs to be played back or deleted.
43290     */
43291     if( pPager->eLock<=SHARED_LOCK ){
43292       rc = hasHotJournal(pPager, &bHotJournal);
43293     }
43294     if( rc!=SQLITE_OK ){
43295       goto failed;
43296     }
43297     if( bHotJournal ){
43298       if( pPager->readOnly ){
43299         rc = SQLITE_READONLY_ROLLBACK;
43300         goto failed;
43301       }
43302
43303       /* Get an EXCLUSIVE lock on the database file. At this point it is
43304       ** important that a RESERVED lock is not obtained on the way to the
43305       ** EXCLUSIVE lock. If it were, another process might open the
43306       ** database file, detect the RESERVED lock, and conclude that the
43307       ** database is safe to read while this process is still rolling the 
43308       ** hot-journal back.
43309       ** 
43310       ** Because the intermediate RESERVED lock is not requested, any
43311       ** other process attempting to access the database file will get to 
43312       ** this point in the code and fail to obtain its own EXCLUSIVE lock 
43313       ** on the database file.
43314       **
43315       ** Unless the pager is in locking_mode=exclusive mode, the lock is
43316       ** downgraded to SHARED_LOCK before this function returns.
43317       */
43318       rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
43319       if( rc!=SQLITE_OK ){
43320         goto failed;
43321       }
43322  
43323       /* If it is not already open and the file exists on disk, open the 
43324       ** journal for read/write access. Write access is required because 
43325       ** in exclusive-access mode the file descriptor will be kept open 
43326       ** and possibly used for a transaction later on. Also, write-access 
43327       ** is usually required to finalize the journal in journal_mode=persist 
43328       ** mode (and also for journal_mode=truncate on some systems).
43329       **
43330       ** If the journal does not exist, it usually means that some 
43331       ** other connection managed to get in and roll it back before 
43332       ** this connection obtained the exclusive lock above. Or, it 
43333       ** may mean that the pager was in the error-state when this
43334       ** function was called and the journal file does not exist.
43335       */
43336       if( !isOpen(pPager->jfd) ){
43337         sqlite3_vfs * const pVfs = pPager->pVfs;
43338         int bExists;              /* True if journal file exists */
43339         rc = sqlite3OsAccess(
43340             pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
43341         if( rc==SQLITE_OK && bExists ){
43342           int fout = 0;
43343           int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
43344           assert( !pPager->tempFile );
43345           rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
43346           assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
43347           if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
43348             rc = SQLITE_CANTOPEN_BKPT;
43349             sqlite3OsClose(pPager->jfd);
43350           }
43351         }
43352       }
43353  
43354       /* Playback and delete the journal.  Drop the database write
43355       ** lock and reacquire the read lock. Purge the cache before
43356       ** playing back the hot-journal so that we don't end up with
43357       ** an inconsistent cache.  Sync the hot journal before playing
43358       ** it back since the process that crashed and left the hot journal
43359       ** probably did not sync it and we are required to always sync
43360       ** the journal before playing it back.
43361       */
43362       if( isOpen(pPager->jfd) ){
43363         assert( rc==SQLITE_OK );
43364         rc = pagerSyncHotJournal(pPager);
43365         if( rc==SQLITE_OK ){
43366           rc = pager_playback(pPager, 1);
43367           pPager->eState = PAGER_OPEN;
43368         }
43369       }else if( !pPager->exclusiveMode ){
43370         pagerUnlockDb(pPager, SHARED_LOCK);
43371       }
43372
43373       if( rc!=SQLITE_OK ){
43374         /* This branch is taken if an error occurs while trying to open
43375         ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
43376         ** pager_unlock() routine will be called before returning to unlock
43377         ** the file. If the unlock attempt fails, then Pager.eLock must be
43378         ** set to UNKNOWN_LOCK (see the comment above the #define for 
43379         ** UNKNOWN_LOCK above for an explanation). 
43380         **
43381         ** In order to get pager_unlock() to do this, set Pager.eState to
43382         ** PAGER_ERROR now. This is not actually counted as a transition
43383         ** to ERROR state in the state diagram at the top of this file,
43384         ** since we know that the same call to pager_unlock() will very
43385         ** shortly transition the pager object to the OPEN state. Calling
43386         ** assert_pager_state() would fail now, as it should not be possible
43387         ** to be in ERROR state when there are zero outstanding page 
43388         ** references.
43389         */
43390         pager_error(pPager, rc);
43391         goto failed;
43392       }
43393
43394       assert( pPager->eState==PAGER_OPEN );
43395       assert( (pPager->eLock==SHARED_LOCK)
43396            || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
43397       );
43398     }
43399
43400     if( !pPager->tempFile && (
43401         pPager->pBackup 
43402      || sqlite3PcachePagecount(pPager->pPCache)>0 
43403      || USEFETCH(pPager)
43404     )){
43405       /* The shared-lock has just been acquired on the database file
43406       ** and there are already pages in the cache (from a previous
43407       ** read or write transaction).  Check to see if the database
43408       ** has been modified.  If the database has changed, flush the
43409       ** cache.
43410       **
43411       ** Database changes is detected by looking at 15 bytes beginning
43412       ** at offset 24 into the file.  The first 4 of these 16 bytes are
43413       ** a 32-bit counter that is incremented with each change.  The
43414       ** other bytes change randomly with each file change when
43415       ** a codec is in use.
43416       ** 
43417       ** There is a vanishingly small chance that a change will not be 
43418       ** detected.  The chance of an undetected change is so small that
43419       ** it can be neglected.
43420       */
43421       Pgno nPage = 0;
43422       char dbFileVers[sizeof(pPager->dbFileVers)];
43423
43424       rc = pagerPagecount(pPager, &nPage);
43425       if( rc ) goto failed;
43426
43427       if( nPage>0 ){
43428         IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
43429         rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
43430         if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
43431           goto failed;
43432         }
43433       }else{
43434         memset(dbFileVers, 0, sizeof(dbFileVers));
43435       }
43436
43437       if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
43438         pager_reset(pPager);
43439
43440         /* Unmap the database file. It is possible that external processes
43441         ** may have truncated the database file and then extended it back
43442         ** to its original size while this process was not holding a lock.
43443         ** In this case there may exist a Pager.pMap mapping that appears
43444         ** to be the right size but is not actually valid. Avoid this
43445         ** possibility by unmapping the db here. */
43446         if( USEFETCH(pPager) ){
43447           sqlite3OsUnfetch(pPager->fd, 0, 0);
43448         }
43449       }
43450     }
43451
43452     /* If there is a WAL file in the file-system, open this database in WAL
43453     ** mode. Otherwise, the following function call is a no-op.
43454     */
43455     rc = pagerOpenWalIfPresent(pPager);
43456 #ifndef SQLITE_OMIT_WAL
43457     assert( pPager->pWal==0 || rc==SQLITE_OK );
43458 #endif
43459   }
43460
43461   if( pagerUseWal(pPager) ){
43462     assert( rc==SQLITE_OK );
43463     rc = pagerBeginReadTransaction(pPager);
43464   }
43465
43466   if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
43467     rc = pagerPagecount(pPager, &pPager->dbSize);
43468   }
43469
43470  failed:
43471   if( rc!=SQLITE_OK ){
43472     assert( !MEMDB );
43473     pager_unlock(pPager);
43474     assert( pPager->eState==PAGER_OPEN );
43475   }else{
43476     pPager->eState = PAGER_READER;
43477   }
43478   return rc;
43479 }
43480
43481 /*
43482 ** If the reference count has reached zero, rollback any active
43483 ** transaction and unlock the pager.
43484 **
43485 ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
43486 ** the rollback journal, the unlock is not performed and there is
43487 ** nothing to rollback, so this routine is a no-op.
43488 */ 
43489 static void pagerUnlockIfUnused(Pager *pPager){
43490   if( pPager->nMmapOut==0 && (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
43491     pagerUnlockAndRollback(pPager);
43492   }
43493 }
43494
43495 /*
43496 ** Acquire a reference to page number pgno in pager pPager (a page
43497 ** reference has type DbPage*). If the requested reference is 
43498 ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
43499 **
43500 ** If the requested page is already in the cache, it is returned. 
43501 ** Otherwise, a new page object is allocated and populated with data
43502 ** read from the database file. In some cases, the pcache module may
43503 ** choose not to allocate a new page object and may reuse an existing
43504 ** object with no outstanding references.
43505 **
43506 ** The extra data appended to a page is always initialized to zeros the 
43507 ** first time a page is loaded into memory. If the page requested is 
43508 ** already in the cache when this function is called, then the extra
43509 ** data is left as it was when the page object was last used.
43510 **
43511 ** If the database image is smaller than the requested page or if a 
43512 ** non-zero value is passed as the noContent parameter and the 
43513 ** requested page is not already stored in the cache, then no 
43514 ** actual disk read occurs. In this case the memory image of the 
43515 ** page is initialized to all zeros. 
43516 **
43517 ** If noContent is true, it means that we do not care about the contents
43518 ** of the page. This occurs in two seperate scenarios:
43519 **
43520 **   a) When reading a free-list leaf page from the database, and
43521 **
43522 **   b) When a savepoint is being rolled back and we need to load
43523 **      a new page into the cache to be filled with the data read
43524 **      from the savepoint journal.
43525 **
43526 ** If noContent is true, then the data returned is zeroed instead of
43527 ** being read from the database. Additionally, the bits corresponding
43528 ** to pgno in Pager.pInJournal (bitvec of pages already written to the
43529 ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
43530 ** savepoints are set. This means if the page is made writable at any
43531 ** point in the future, using a call to sqlite3PagerWrite(), its contents
43532 ** will not be journaled. This saves IO.
43533 **
43534 ** The acquisition might fail for several reasons.  In all cases,
43535 ** an appropriate error code is returned and *ppPage is set to NULL.
43536 **
43537 ** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
43538 ** to find a page in the in-memory cache first.  If the page is not already
43539 ** in memory, this routine goes to disk to read it in whereas Lookup()
43540 ** just returns 0.  This routine acquires a read-lock the first time it
43541 ** has to go to disk, and could also playback an old journal if necessary.
43542 ** Since Lookup() never goes to disk, it never has to deal with locks
43543 ** or journal files.
43544 */
43545 SQLITE_PRIVATE int sqlite3PagerAcquire(
43546   Pager *pPager,      /* The pager open on the database file */
43547   Pgno pgno,          /* Page number to fetch */
43548   DbPage **ppPage,    /* Write a pointer to the page here */
43549   int flags           /* PAGER_ACQUIRE_XXX flags */
43550 ){
43551   int rc = SQLITE_OK;
43552   PgHdr *pPg = 0;
43553   u32 iFrame = 0;                 /* Frame to read from WAL file */
43554   const int noContent = (flags & PAGER_ACQUIRE_NOCONTENT);
43555
43556   /* It is acceptable to use a read-only (mmap) page for any page except
43557   ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
43558   ** flag was specified by the caller. And so long as the db is not a 
43559   ** temporary or in-memory database.  */
43560   const int bMmapOk = (pgno!=1 && USEFETCH(pPager)
43561    && (pPager->eState==PAGER_READER || (flags & PAGER_ACQUIRE_READONLY))
43562 #ifdef SQLITE_HAS_CODEC
43563    && pPager->xCodec==0
43564 #endif
43565   );
43566
43567   assert( pPager->eState>=PAGER_READER );
43568   assert( assert_pager_state(pPager) );
43569   assert( noContent==0 || bMmapOk==0 );
43570
43571   if( pgno==0 ){
43572     return SQLITE_CORRUPT_BKPT;
43573   }
43574
43575   /* If the pager is in the error state, return an error immediately. 
43576   ** Otherwise, request the page from the PCache layer. */
43577   if( pPager->errCode!=SQLITE_OK ){
43578     rc = pPager->errCode;
43579   }else{
43580
43581     if( bMmapOk && pagerUseWal(pPager) ){
43582       rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
43583       if( rc!=SQLITE_OK ) goto pager_acquire_err;
43584     }
43585
43586     if( iFrame==0 && bMmapOk ){
43587       void *pData = 0;
43588
43589       rc = sqlite3OsFetch(pPager->fd, 
43590           (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
43591       );
43592
43593       if( rc==SQLITE_OK && pData ){
43594         if( pPager->eState>PAGER_READER ){
43595           (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
43596         }
43597         if( pPg==0 ){
43598           rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
43599         }else{
43600           sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
43601         }
43602         if( pPg ){
43603           assert( rc==SQLITE_OK );
43604           *ppPage = pPg;
43605           return SQLITE_OK;
43606         }
43607       }
43608       if( rc!=SQLITE_OK ){
43609         goto pager_acquire_err;
43610       }
43611     }
43612
43613     rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
43614   }
43615
43616   if( rc!=SQLITE_OK ){
43617     /* Either the call to sqlite3PcacheFetch() returned an error or the
43618     ** pager was already in the error-state when this function was called.
43619     ** Set pPg to 0 and jump to the exception handler.  */
43620     pPg = 0;
43621     goto pager_acquire_err;
43622   }
43623   assert( (*ppPage)->pgno==pgno );
43624   assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
43625
43626   if( (*ppPage)->pPager && !noContent ){
43627     /* In this case the pcache already contains an initialized copy of
43628     ** the page. Return without further ado.  */
43629     assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
43630     pPager->aStat[PAGER_STAT_HIT]++;
43631     return SQLITE_OK;
43632
43633   }else{
43634     /* The pager cache has created a new page. Its content needs to 
43635     ** be initialized.  */
43636
43637     pPg = *ppPage;
43638     pPg->pPager = pPager;
43639
43640     /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
43641     ** number greater than this, or the unused locking-page, is requested. */
43642     if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
43643       rc = SQLITE_CORRUPT_BKPT;
43644       goto pager_acquire_err;
43645     }
43646
43647     if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
43648       if( pgno>pPager->mxPgno ){
43649         rc = SQLITE_FULL;
43650         goto pager_acquire_err;
43651       }
43652       if( noContent ){
43653         /* Failure to set the bits in the InJournal bit-vectors is benign.
43654         ** It merely means that we might do some extra work to journal a 
43655         ** page that does not need to be journaled.  Nevertheless, be sure 
43656         ** to test the case where a malloc error occurs while trying to set 
43657         ** a bit in a bit vector.
43658         */
43659         sqlite3BeginBenignMalloc();
43660         if( pgno<=pPager->dbOrigSize ){
43661           TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
43662           testcase( rc==SQLITE_NOMEM );
43663         }
43664         TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
43665         testcase( rc==SQLITE_NOMEM );
43666         sqlite3EndBenignMalloc();
43667       }
43668       memset(pPg->pData, 0, pPager->pageSize);
43669       IOTRACE(("ZERO %p %d\n", pPager, pgno));
43670     }else{
43671       if( pagerUseWal(pPager) && bMmapOk==0 ){
43672         rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
43673         if( rc!=SQLITE_OK ) goto pager_acquire_err;
43674       }
43675       assert( pPg->pPager==pPager );
43676       pPager->aStat[PAGER_STAT_MISS]++;
43677       rc = readDbPage(pPg, iFrame);
43678       if( rc!=SQLITE_OK ){
43679         goto pager_acquire_err;
43680       }
43681     }
43682     pager_set_pagehash(pPg);
43683   }
43684
43685   return SQLITE_OK;
43686
43687 pager_acquire_err:
43688   assert( rc!=SQLITE_OK );
43689   if( pPg ){
43690     sqlite3PcacheDrop(pPg);
43691   }
43692   pagerUnlockIfUnused(pPager);
43693
43694   *ppPage = 0;
43695   return rc;
43696 }
43697
43698 /*
43699 ** Acquire a page if it is already in the in-memory cache.  Do
43700 ** not read the page from disk.  Return a pointer to the page,
43701 ** or 0 if the page is not in cache. 
43702 **
43703 ** See also sqlite3PagerGet().  The difference between this routine
43704 ** and sqlite3PagerGet() is that _get() will go to the disk and read
43705 ** in the page if the page is not already in cache.  This routine
43706 ** returns NULL if the page is not in cache or if a disk I/O error 
43707 ** has ever happened.
43708 */
43709 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
43710   PgHdr *pPg = 0;
43711   assert( pPager!=0 );
43712   assert( pgno!=0 );
43713   assert( pPager->pPCache!=0 );
43714   assert( pPager->eState>=PAGER_READER && pPager->eState!=PAGER_ERROR );
43715   sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
43716   return pPg;
43717 }
43718
43719 /*
43720 ** Release a page reference.
43721 **
43722 ** If the number of references to the page drop to zero, then the
43723 ** page is added to the LRU list.  When all references to all pages
43724 ** are released, a rollback occurs and the lock on the database is
43725 ** removed.
43726 */
43727 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
43728   if( pPg ){
43729     Pager *pPager = pPg->pPager;
43730     if( pPg->flags & PGHDR_MMAP ){
43731       pagerReleaseMapPage(pPg);
43732     }else{
43733       sqlite3PcacheRelease(pPg);
43734     }
43735     pagerUnlockIfUnused(pPager);
43736   }
43737 }
43738
43739 /*
43740 ** This function is called at the start of every write transaction.
43741 ** There must already be a RESERVED or EXCLUSIVE lock on the database 
43742 ** file when this routine is called.
43743 **
43744 ** Open the journal file for pager pPager and write a journal header
43745 ** to the start of it. If there are active savepoints, open the sub-journal
43746 ** as well. This function is only used when the journal file is being 
43747 ** opened to write a rollback log for a transaction. It is not used 
43748 ** when opening a hot journal file to roll it back.
43749 **
43750 ** If the journal file is already open (as it may be in exclusive mode),
43751 ** then this function just writes a journal header to the start of the
43752 ** already open file. 
43753 **
43754 ** Whether or not the journal file is opened by this function, the
43755 ** Pager.pInJournal bitvec structure is allocated.
43756 **
43757 ** Return SQLITE_OK if everything is successful. Otherwise, return 
43758 ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or 
43759 ** an IO error code if opening or writing the journal file fails.
43760 */
43761 static int pager_open_journal(Pager *pPager){
43762   int rc = SQLITE_OK;                        /* Return code */
43763   sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
43764
43765   assert( pPager->eState==PAGER_WRITER_LOCKED );
43766   assert( assert_pager_state(pPager) );
43767   assert( pPager->pInJournal==0 );
43768   
43769   /* If already in the error state, this function is a no-op.  But on
43770   ** the other hand, this routine is never called if we are already in
43771   ** an error state. */
43772   if( NEVER(pPager->errCode) ) return pPager->errCode;
43773
43774   if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
43775     pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
43776     if( pPager->pInJournal==0 ){
43777       return SQLITE_NOMEM;
43778     }
43779   
43780     /* Open the journal file if it is not already open. */
43781     if( !isOpen(pPager->jfd) ){
43782       if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
43783         sqlite3MemJournalOpen(pPager->jfd);
43784       }else{
43785         const int flags =                   /* VFS flags to open journal file */
43786           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
43787           (pPager->tempFile ? 
43788             (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
43789             (SQLITE_OPEN_MAIN_JOURNAL)
43790           );
43791   #ifdef SQLITE_ENABLE_ATOMIC_WRITE
43792         rc = sqlite3JournalOpen(
43793             pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
43794         );
43795   #else
43796         rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
43797   #endif
43798       }
43799       assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
43800     }
43801   
43802   
43803     /* Write the first journal header to the journal file and open 
43804     ** the sub-journal if necessary.
43805     */
43806     if( rc==SQLITE_OK ){
43807       /* TODO: Check if all of these are really required. */
43808       pPager->nRec = 0;
43809       pPager->journalOff = 0;
43810       pPager->setMaster = 0;
43811       pPager->journalHdr = 0;
43812       rc = writeJournalHdr(pPager);
43813     }
43814   }
43815
43816   if( rc!=SQLITE_OK ){
43817     sqlite3BitvecDestroy(pPager->pInJournal);
43818     pPager->pInJournal = 0;
43819   }else{
43820     assert( pPager->eState==PAGER_WRITER_LOCKED );
43821     pPager->eState = PAGER_WRITER_CACHEMOD;
43822   }
43823
43824   return rc;
43825 }
43826
43827 /*
43828 ** Begin a write-transaction on the specified pager object. If a 
43829 ** write-transaction has already been opened, this function is a no-op.
43830 **
43831 ** If the exFlag argument is false, then acquire at least a RESERVED
43832 ** lock on the database file. If exFlag is true, then acquire at least
43833 ** an EXCLUSIVE lock. If such a lock is already held, no locking 
43834 ** functions need be called.
43835 **
43836 ** If the subjInMemory argument is non-zero, then any sub-journal opened
43837 ** within this transaction will be opened as an in-memory file. This
43838 ** has no effect if the sub-journal is already opened (as it may be when
43839 ** running in exclusive mode) or if the transaction does not require a
43840 ** sub-journal. If the subjInMemory argument is zero, then any required
43841 ** sub-journal is implemented in-memory if pPager is an in-memory database, 
43842 ** or using a temporary file otherwise.
43843 */
43844 SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
43845   int rc = SQLITE_OK;
43846
43847   if( pPager->errCode ) return pPager->errCode;
43848   assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
43849   pPager->subjInMemory = (u8)subjInMemory;
43850
43851   if( ALWAYS(pPager->eState==PAGER_READER) ){
43852     assert( pPager->pInJournal==0 );
43853
43854     if( pagerUseWal(pPager) ){
43855       /* If the pager is configured to use locking_mode=exclusive, and an
43856       ** exclusive lock on the database is not already held, obtain it now.
43857       */
43858       if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
43859         rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
43860         if( rc!=SQLITE_OK ){
43861           return rc;
43862         }
43863         sqlite3WalExclusiveMode(pPager->pWal, 1);
43864       }
43865
43866       /* Grab the write lock on the log file. If successful, upgrade to
43867       ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
43868       ** The busy-handler is not invoked if another connection already
43869       ** holds the write-lock. If possible, the upper layer will call it.
43870       */
43871       rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
43872     }else{
43873       /* Obtain a RESERVED lock on the database file. If the exFlag parameter
43874       ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
43875       ** busy-handler callback can be used when upgrading to the EXCLUSIVE
43876       ** lock, but not when obtaining the RESERVED lock.
43877       */
43878       rc = pagerLockDb(pPager, RESERVED_LOCK);
43879       if( rc==SQLITE_OK && exFlag ){
43880         rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
43881       }
43882     }
43883
43884     if( rc==SQLITE_OK ){
43885       /* Change to WRITER_LOCKED state.
43886       **
43887       ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
43888       ** when it has an open transaction, but never to DBMOD or FINISHED.
43889       ** This is because in those states the code to roll back savepoint 
43890       ** transactions may copy data from the sub-journal into the database 
43891       ** file as well as into the page cache. Which would be incorrect in 
43892       ** WAL mode.
43893       */
43894       pPager->eState = PAGER_WRITER_LOCKED;
43895       pPager->dbHintSize = pPager->dbSize;
43896       pPager->dbFileSize = pPager->dbSize;
43897       pPager->dbOrigSize = pPager->dbSize;
43898       pPager->journalOff = 0;
43899     }
43900
43901     assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
43902     assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
43903     assert( assert_pager_state(pPager) );
43904   }
43905
43906   PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
43907   return rc;
43908 }
43909
43910 /*
43911 ** Mark a single data page as writeable. The page is written into the 
43912 ** main journal or sub-journal as required. If the page is written into
43913 ** one of the journals, the corresponding bit is set in the 
43914 ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
43915 ** of any open savepoints as appropriate.
43916 */
43917 static int pager_write(PgHdr *pPg){
43918   void *pData = pPg->pData;
43919   Pager *pPager = pPg->pPager;
43920   int rc = SQLITE_OK;
43921
43922   /* This routine is not called unless a write-transaction has already 
43923   ** been started. The journal file may or may not be open at this point.
43924   ** It is never called in the ERROR state.
43925   */
43926   assert( pPager->eState==PAGER_WRITER_LOCKED
43927        || pPager->eState==PAGER_WRITER_CACHEMOD
43928        || pPager->eState==PAGER_WRITER_DBMOD
43929   );
43930   assert( assert_pager_state(pPager) );
43931
43932   /* If an error has been previously detected, report the same error
43933   ** again. This should not happen, but the check provides robustness. */
43934   if( NEVER(pPager->errCode) )  return pPager->errCode;
43935
43936   /* Higher-level routines never call this function if database is not
43937   ** writable.  But check anyway, just for robustness. */
43938   if( NEVER(pPager->readOnly) ) return SQLITE_PERM;
43939
43940   CHECK_PAGE(pPg);
43941
43942   /* The journal file needs to be opened. Higher level routines have already
43943   ** obtained the necessary locks to begin the write-transaction, but the
43944   ** rollback journal might not yet be open. Open it now if this is the case.
43945   **
43946   ** This is done before calling sqlite3PcacheMakeDirty() on the page. 
43947   ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
43948   ** an error might occur and the pager would end up in WRITER_LOCKED state
43949   ** with pages marked as dirty in the cache.
43950   */
43951   if( pPager->eState==PAGER_WRITER_LOCKED ){
43952     rc = pager_open_journal(pPager);
43953     if( rc!=SQLITE_OK ) return rc;
43954   }
43955   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
43956   assert( assert_pager_state(pPager) );
43957
43958   /* Mark the page as dirty.  If the page has already been written
43959   ** to the journal then we can return right away.
43960   */
43961   sqlite3PcacheMakeDirty(pPg);
43962   if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
43963     assert( !pagerUseWal(pPager) );
43964   }else{
43965   
43966     /* The transaction journal now exists and we have a RESERVED or an
43967     ** EXCLUSIVE lock on the main database file.  Write the current page to
43968     ** the transaction journal if it is not there already.
43969     */
43970     if( !pageInJournal(pPg) && !pagerUseWal(pPager) ){
43971       assert( pagerUseWal(pPager)==0 );
43972       if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){
43973         u32 cksum;
43974         char *pData2;
43975         i64 iOff = pPager->journalOff;
43976
43977         /* We should never write to the journal file the page that
43978         ** contains the database locks.  The following assert verifies
43979         ** that we do not. */
43980         assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
43981
43982         assert( pPager->journalHdr<=pPager->journalOff );
43983         CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
43984         cksum = pager_cksum(pPager, (u8*)pData2);
43985
43986         /* Even if an IO or diskfull error occurs while journalling the
43987         ** page in the block above, set the need-sync flag for the page.
43988         ** Otherwise, when the transaction is rolled back, the logic in
43989         ** playback_one_page() will think that the page needs to be restored
43990         ** in the database file. And if an IO error occurs while doing so,
43991         ** then corruption may follow.
43992         */
43993         pPg->flags |= PGHDR_NEED_SYNC;
43994
43995         rc = write32bits(pPager->jfd, iOff, pPg->pgno);
43996         if( rc!=SQLITE_OK ) return rc;
43997         rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
43998         if( rc!=SQLITE_OK ) return rc;
43999         rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
44000         if( rc!=SQLITE_OK ) return rc;
44001
44002         IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno, 
44003                  pPager->journalOff, pPager->pageSize));
44004         PAGER_INCR(sqlite3_pager_writej_count);
44005         PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
44006              PAGERID(pPager), pPg->pgno, 
44007              ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
44008
44009         pPager->journalOff += 8 + pPager->pageSize;
44010         pPager->nRec++;
44011         assert( pPager->pInJournal!=0 );
44012         rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
44013         testcase( rc==SQLITE_NOMEM );
44014         assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
44015         rc |= addToSavepointBitvecs(pPager, pPg->pgno);
44016         if( rc!=SQLITE_OK ){
44017           assert( rc==SQLITE_NOMEM );
44018           return rc;
44019         }
44020       }else{
44021         if( pPager->eState!=PAGER_WRITER_DBMOD ){
44022           pPg->flags |= PGHDR_NEED_SYNC;
44023         }
44024         PAGERTRACE(("APPEND %d page %d needSync=%d\n",
44025                 PAGERID(pPager), pPg->pgno,
44026                ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
44027       }
44028     }
44029   
44030     /* If the statement journal is open and the page is not in it,
44031     ** then write the current page to the statement journal.  Note that
44032     ** the statement journal format differs from the standard journal format
44033     ** in that it omits the checksums and the header.
44034     */
44035     if( subjRequiresPage(pPg) ){
44036       rc = subjournalPage(pPg);
44037     }
44038   }
44039
44040   /* Update the database size and return.
44041   */
44042   if( pPager->dbSize<pPg->pgno ){
44043     pPager->dbSize = pPg->pgno;
44044   }
44045   return rc;
44046 }
44047
44048 /*
44049 ** Mark a data page as writeable. This routine must be called before 
44050 ** making changes to a page. The caller must check the return value 
44051 ** of this function and be careful not to change any page data unless 
44052 ** this routine returns SQLITE_OK.
44053 **
44054 ** The difference between this function and pager_write() is that this
44055 ** function also deals with the special case where 2 or more pages
44056 ** fit on a single disk sector. In this case all co-resident pages
44057 ** must have been written to the journal file before returning.
44058 **
44059 ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
44060 ** as appropriate. Otherwise, SQLITE_OK.
44061 */
44062 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
44063   int rc = SQLITE_OK;
44064
44065   PgHdr *pPg = pDbPage;
44066   Pager *pPager = pPg->pPager;
44067   Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
44068
44069   assert( (pPg->flags & PGHDR_MMAP)==0 );
44070   assert( pPager->eState>=PAGER_WRITER_LOCKED );
44071   assert( pPager->eState!=PAGER_ERROR );
44072   assert( assert_pager_state(pPager) );
44073
44074   if( nPagePerSector>1 ){
44075     Pgno nPageCount;          /* Total number of pages in database file */
44076     Pgno pg1;                 /* First page of the sector pPg is located on. */
44077     int nPage = 0;            /* Number of pages starting at pg1 to journal */
44078     int ii;                   /* Loop counter */
44079     int needSync = 0;         /* True if any page has PGHDR_NEED_SYNC */
44080
44081     /* Set the doNotSyncSpill flag to 1. This is because we cannot allow
44082     ** a journal header to be written between the pages journaled by
44083     ** this function.
44084     */
44085     assert( !MEMDB );
44086     assert( pPager->doNotSyncSpill==0 );
44087     pPager->doNotSyncSpill++;
44088
44089     /* This trick assumes that both the page-size and sector-size are
44090     ** an integer power of 2. It sets variable pg1 to the identifier
44091     ** of the first page of the sector pPg is located on.
44092     */
44093     pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
44094
44095     nPageCount = pPager->dbSize;
44096     if( pPg->pgno>nPageCount ){
44097       nPage = (pPg->pgno - pg1)+1;
44098     }else if( (pg1+nPagePerSector-1)>nPageCount ){
44099       nPage = nPageCount+1-pg1;
44100     }else{
44101       nPage = nPagePerSector;
44102     }
44103     assert(nPage>0);
44104     assert(pg1<=pPg->pgno);
44105     assert((pg1+nPage)>pPg->pgno);
44106
44107     for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
44108       Pgno pg = pg1+ii;
44109       PgHdr *pPage;
44110       if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
44111         if( pg!=PAGER_MJ_PGNO(pPager) ){
44112           rc = sqlite3PagerGet(pPager, pg, &pPage);
44113           if( rc==SQLITE_OK ){
44114             rc = pager_write(pPage);
44115             if( pPage->flags&PGHDR_NEED_SYNC ){
44116               needSync = 1;
44117             }
44118             sqlite3PagerUnref(pPage);
44119           }
44120         }
44121       }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
44122         if( pPage->flags&PGHDR_NEED_SYNC ){
44123           needSync = 1;
44124         }
44125         sqlite3PagerUnref(pPage);
44126       }
44127     }
44128
44129     /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages 
44130     ** starting at pg1, then it needs to be set for all of them. Because
44131     ** writing to any of these nPage pages may damage the others, the
44132     ** journal file must contain sync()ed copies of all of them
44133     ** before any of them can be written out to the database file.
44134     */
44135     if( rc==SQLITE_OK && needSync ){
44136       assert( !MEMDB );
44137       for(ii=0; ii<nPage; ii++){
44138         PgHdr *pPage = pager_lookup(pPager, pg1+ii);
44139         if( pPage ){
44140           pPage->flags |= PGHDR_NEED_SYNC;
44141           sqlite3PagerUnref(pPage);
44142         }
44143       }
44144     }
44145
44146     assert( pPager->doNotSyncSpill==1 );
44147     pPager->doNotSyncSpill--;
44148   }else{
44149     rc = pager_write(pDbPage);
44150   }
44151   return rc;
44152 }
44153
44154 /*
44155 ** Return TRUE if the page given in the argument was previously passed
44156 ** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
44157 ** to change the content of the page.
44158 */
44159 #ifndef NDEBUG
44160 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
44161   return pPg->flags&PGHDR_DIRTY;
44162 }
44163 #endif
44164
44165 /*
44166 ** A call to this routine tells the pager that it is not necessary to
44167 ** write the information on page pPg back to the disk, even though
44168 ** that page might be marked as dirty.  This happens, for example, when
44169 ** the page has been added as a leaf of the freelist and so its
44170 ** content no longer matters.
44171 **
44172 ** The overlying software layer calls this routine when all of the data
44173 ** on the given page is unused. The pager marks the page as clean so
44174 ** that it does not get written to disk.
44175 **
44176 ** Tests show that this optimization can quadruple the speed of large 
44177 ** DELETE operations.
44178 */
44179 SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
44180   Pager *pPager = pPg->pPager;
44181   if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
44182     PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
44183     IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
44184     pPg->flags |= PGHDR_DONT_WRITE;
44185     pager_set_pagehash(pPg);
44186   }
44187 }
44188
44189 /*
44190 ** This routine is called to increment the value of the database file 
44191 ** change-counter, stored as a 4-byte big-endian integer starting at 
44192 ** byte offset 24 of the pager file.  The secondary change counter at
44193 ** 92 is also updated, as is the SQLite version number at offset 96.
44194 **
44195 ** But this only happens if the pPager->changeCountDone flag is false.
44196 ** To avoid excess churning of page 1, the update only happens once.
44197 ** See also the pager_write_changecounter() routine that does an 
44198 ** unconditional update of the change counters.
44199 **
44200 ** If the isDirectMode flag is zero, then this is done by calling 
44201 ** sqlite3PagerWrite() on page 1, then modifying the contents of the
44202 ** page data. In this case the file will be updated when the current
44203 ** transaction is committed.
44204 **
44205 ** The isDirectMode flag may only be non-zero if the library was compiled
44206 ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
44207 ** if isDirect is non-zero, then the database file is updated directly
44208 ** by writing an updated version of page 1 using a call to the 
44209 ** sqlite3OsWrite() function.
44210 */
44211 static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
44212   int rc = SQLITE_OK;
44213
44214   assert( pPager->eState==PAGER_WRITER_CACHEMOD
44215        || pPager->eState==PAGER_WRITER_DBMOD
44216   );
44217   assert( assert_pager_state(pPager) );
44218
44219   /* Declare and initialize constant integer 'isDirect'. If the
44220   ** atomic-write optimization is enabled in this build, then isDirect
44221   ** is initialized to the value passed as the isDirectMode parameter
44222   ** to this function. Otherwise, it is always set to zero.
44223   **
44224   ** The idea is that if the atomic-write optimization is not
44225   ** enabled at compile time, the compiler can omit the tests of
44226   ** 'isDirect' below, as well as the block enclosed in the
44227   ** "if( isDirect )" condition.
44228   */
44229 #ifndef SQLITE_ENABLE_ATOMIC_WRITE
44230 # define DIRECT_MODE 0
44231   assert( isDirectMode==0 );
44232   UNUSED_PARAMETER(isDirectMode);
44233 #else
44234 # define DIRECT_MODE isDirectMode
44235 #endif
44236
44237   if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
44238     PgHdr *pPgHdr;                /* Reference to page 1 */
44239
44240     assert( !pPager->tempFile && isOpen(pPager->fd) );
44241
44242     /* Open page 1 of the file for writing. */
44243     rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
44244     assert( pPgHdr==0 || rc==SQLITE_OK );
44245
44246     /* If page one was fetched successfully, and this function is not
44247     ** operating in direct-mode, make page 1 writable.  When not in 
44248     ** direct mode, page 1 is always held in cache and hence the PagerGet()
44249     ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
44250     */
44251     if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
44252       rc = sqlite3PagerWrite(pPgHdr);
44253     }
44254
44255     if( rc==SQLITE_OK ){
44256       /* Actually do the update of the change counter */
44257       pager_write_changecounter(pPgHdr);
44258
44259       /* If running in direct mode, write the contents of page 1 to the file. */
44260       if( DIRECT_MODE ){
44261         const void *zBuf;
44262         assert( pPager->dbFileSize>0 );
44263         CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
44264         if( rc==SQLITE_OK ){
44265           rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
44266           pPager->aStat[PAGER_STAT_WRITE]++;
44267         }
44268         if( rc==SQLITE_OK ){
44269           /* Update the pager's copy of the change-counter. Otherwise, the
44270           ** next time a read transaction is opened the cache will be
44271           ** flushed (as the change-counter values will not match).  */
44272           const void *pCopy = (const void *)&((const char *)zBuf)[24];
44273           memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
44274           pPager->changeCountDone = 1;
44275         }
44276       }else{
44277         pPager->changeCountDone = 1;
44278       }
44279     }
44280
44281     /* Release the page reference. */
44282     sqlite3PagerUnref(pPgHdr);
44283   }
44284   return rc;
44285 }
44286
44287 /*
44288 ** Sync the database file to disk. This is a no-op for in-memory databases
44289 ** or pages with the Pager.noSync flag set.
44290 **
44291 ** If successful, or if called on a pager for which it is a no-op, this
44292 ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
44293 */
44294 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
44295   int rc = SQLITE_OK;
44296   if( !pPager->noSync ){
44297     assert( !MEMDB );
44298     rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
44299   }else if( isOpen(pPager->fd) ){
44300     assert( !MEMDB );
44301     rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC_OMITTED, 0);
44302     if( rc==SQLITE_NOTFOUND ){
44303       rc = SQLITE_OK;
44304     }
44305   }
44306   return rc;
44307 }
44308
44309 /*
44310 ** This function may only be called while a write-transaction is active in
44311 ** rollback. If the connection is in WAL mode, this call is a no-op. 
44312 ** Otherwise, if the connection does not already have an EXCLUSIVE lock on 
44313 ** the database file, an attempt is made to obtain one.
44314 **
44315 ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
44316 ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
44317 ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is 
44318 ** returned.
44319 */
44320 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
44321   int rc = SQLITE_OK;
44322   assert( pPager->eState==PAGER_WRITER_CACHEMOD 
44323        || pPager->eState==PAGER_WRITER_DBMOD 
44324        || pPager->eState==PAGER_WRITER_LOCKED 
44325   );
44326   assert( assert_pager_state(pPager) );
44327   if( 0==pagerUseWal(pPager) ){
44328     rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
44329   }
44330   return rc;
44331 }
44332
44333 /*
44334 ** Sync the database file for the pager pPager. zMaster points to the name
44335 ** of a master journal file that should be written into the individual
44336 ** journal file. zMaster may be NULL, which is interpreted as no master
44337 ** journal (a single database transaction).
44338 **
44339 ** This routine ensures that:
44340 **
44341 **   * The database file change-counter is updated,
44342 **   * the journal is synced (unless the atomic-write optimization is used),
44343 **   * all dirty pages are written to the database file, 
44344 **   * the database file is truncated (if required), and
44345 **   * the database file synced. 
44346 **
44347 ** The only thing that remains to commit the transaction is to finalize 
44348 ** (delete, truncate or zero the first part of) the journal file (or 
44349 ** delete the master journal file if specified).
44350 **
44351 ** Note that if zMaster==NULL, this does not overwrite a previous value
44352 ** passed to an sqlite3PagerCommitPhaseOne() call.
44353 **
44354 ** If the final parameter - noSync - is true, then the database file itself
44355 ** is not synced. The caller must call sqlite3PagerSync() directly to
44356 ** sync the database file before calling CommitPhaseTwo() to delete the
44357 ** journal file in this case.
44358 */
44359 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
44360   Pager *pPager,                  /* Pager object */
44361   const char *zMaster,            /* If not NULL, the master journal name */
44362   int noSync                      /* True to omit the xSync on the db file */
44363 ){
44364   int rc = SQLITE_OK;             /* Return code */
44365
44366   assert( pPager->eState==PAGER_WRITER_LOCKED
44367        || pPager->eState==PAGER_WRITER_CACHEMOD
44368        || pPager->eState==PAGER_WRITER_DBMOD
44369        || pPager->eState==PAGER_ERROR
44370   );
44371   assert( assert_pager_state(pPager) );
44372
44373   /* If a prior error occurred, report that error again. */
44374   if( NEVER(pPager->errCode) ) return pPager->errCode;
44375
44376   PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n", 
44377       pPager->zFilename, zMaster, pPager->dbSize));
44378
44379   /* If no database changes have been made, return early. */
44380   if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
44381
44382   if( MEMDB ){
44383     /* If this is an in-memory db, or no pages have been written to, or this
44384     ** function has already been called, it is mostly a no-op.  However, any
44385     ** backup in progress needs to be restarted.
44386     */
44387     sqlite3BackupRestart(pPager->pBackup);
44388   }else{
44389     if( pagerUseWal(pPager) ){
44390       PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
44391       PgHdr *pPageOne = 0;
44392       if( pList==0 ){
44393         /* Must have at least one page for the WAL commit flag.
44394         ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
44395         rc = sqlite3PagerGet(pPager, 1, &pPageOne);
44396         pList = pPageOne;
44397         pList->pDirty = 0;
44398       }
44399       assert( rc==SQLITE_OK );
44400       if( ALWAYS(pList) ){
44401         rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
44402       }
44403       sqlite3PagerUnref(pPageOne);
44404       if( rc==SQLITE_OK ){
44405         sqlite3PcacheCleanAll(pPager->pPCache);
44406       }
44407     }else{
44408       /* The following block updates the change-counter. Exactly how it
44409       ** does this depends on whether or not the atomic-update optimization
44410       ** was enabled at compile time, and if this transaction meets the 
44411       ** runtime criteria to use the operation: 
44412       **
44413       **    * The file-system supports the atomic-write property for
44414       **      blocks of size page-size, and 
44415       **    * This commit is not part of a multi-file transaction, and
44416       **    * Exactly one page has been modified and store in the journal file.
44417       **
44418       ** If the optimization was not enabled at compile time, then the
44419       ** pager_incr_changecounter() function is called to update the change
44420       ** counter in 'indirect-mode'. If the optimization is compiled in but
44421       ** is not applicable to this transaction, call sqlite3JournalCreate()
44422       ** to make sure the journal file has actually been created, then call
44423       ** pager_incr_changecounter() to update the change-counter in indirect
44424       ** mode. 
44425       **
44426       ** Otherwise, if the optimization is both enabled and applicable,
44427       ** then call pager_incr_changecounter() to update the change-counter
44428       ** in 'direct' mode. In this case the journal file will never be
44429       ** created for this transaction.
44430       */
44431   #ifdef SQLITE_ENABLE_ATOMIC_WRITE
44432       PgHdr *pPg;
44433       assert( isOpen(pPager->jfd) 
44434            || pPager->journalMode==PAGER_JOURNALMODE_OFF 
44435            || pPager->journalMode==PAGER_JOURNALMODE_WAL 
44436       );
44437       if( !zMaster && isOpen(pPager->jfd) 
44438        && pPager->journalOff==jrnlBufferSize(pPager) 
44439        && pPager->dbSize>=pPager->dbOrigSize
44440        && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
44441       ){
44442         /* Update the db file change counter via the direct-write method. The 
44443         ** following call will modify the in-memory representation of page 1 
44444         ** to include the updated change counter and then write page 1 
44445         ** directly to the database file. Because of the atomic-write 
44446         ** property of the host file-system, this is safe.
44447         */
44448         rc = pager_incr_changecounter(pPager, 1);
44449       }else{
44450         rc = sqlite3JournalCreate(pPager->jfd);
44451         if( rc==SQLITE_OK ){
44452           rc = pager_incr_changecounter(pPager, 0);
44453         }
44454       }
44455   #else
44456       rc = pager_incr_changecounter(pPager, 0);
44457   #endif
44458       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
44459   
44460       /* Write the master journal name into the journal file. If a master 
44461       ** journal file name has already been written to the journal file, 
44462       ** or if zMaster is NULL (no master journal), then this call is a no-op.
44463       */
44464       rc = writeMasterJournal(pPager, zMaster);
44465       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
44466   
44467       /* Sync the journal file and write all dirty pages to the database.
44468       ** If the atomic-update optimization is being used, this sync will not 
44469       ** create the journal file or perform any real IO.
44470       **
44471       ** Because the change-counter page was just modified, unless the
44472       ** atomic-update optimization is used it is almost certain that the
44473       ** journal requires a sync here. However, in locking_mode=exclusive
44474       ** on a system under memory pressure it is just possible that this is 
44475       ** not the case. In this case it is likely enough that the redundant
44476       ** xSync() call will be changed to a no-op by the OS anyhow. 
44477       */
44478       rc = syncJournal(pPager, 0);
44479       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
44480   
44481       rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
44482       if( rc!=SQLITE_OK ){
44483         assert( rc!=SQLITE_IOERR_BLOCKED );
44484         goto commit_phase_one_exit;
44485       }
44486       sqlite3PcacheCleanAll(pPager->pPCache);
44487
44488       /* If the file on disk is smaller than the database image, use 
44489       ** pager_truncate to grow the file here. This can happen if the database
44490       ** image was extended as part of the current transaction and then the
44491       ** last page in the db image moved to the free-list. In this case the
44492       ** last page is never written out to disk, leaving the database file
44493       ** undersized. Fix this now if it is the case.  */
44494       if( pPager->dbSize>pPager->dbFileSize ){
44495         Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
44496         assert( pPager->eState==PAGER_WRITER_DBMOD );
44497         rc = pager_truncate(pPager, nNew);
44498         if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
44499       }
44500   
44501       /* Finally, sync the database file. */
44502       if( !noSync ){
44503         rc = sqlite3PagerSync(pPager);
44504       }
44505       IOTRACE(("DBSYNC %p\n", pPager))
44506     }
44507   }
44508
44509 commit_phase_one_exit:
44510   if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
44511     pPager->eState = PAGER_WRITER_FINISHED;
44512   }
44513   return rc;
44514 }
44515
44516
44517 /*
44518 ** When this function is called, the database file has been completely
44519 ** updated to reflect the changes made by the current transaction and
44520 ** synced to disk. The journal file still exists in the file-system 
44521 ** though, and if a failure occurs at this point it will eventually
44522 ** be used as a hot-journal and the current transaction rolled back.
44523 **
44524 ** This function finalizes the journal file, either by deleting, 
44525 ** truncating or partially zeroing it, so that it cannot be used 
44526 ** for hot-journal rollback. Once this is done the transaction is
44527 ** irrevocably committed.
44528 **
44529 ** If an error occurs, an IO error code is returned and the pager
44530 ** moves into the error state. Otherwise, SQLITE_OK is returned.
44531 */
44532 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
44533   int rc = SQLITE_OK;                  /* Return code */
44534
44535   /* This routine should not be called if a prior error has occurred.
44536   ** But if (due to a coding error elsewhere in the system) it does get
44537   ** called, just return the same error code without doing anything. */
44538   if( NEVER(pPager->errCode) ) return pPager->errCode;
44539
44540   assert( pPager->eState==PAGER_WRITER_LOCKED
44541        || pPager->eState==PAGER_WRITER_FINISHED
44542        || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
44543   );
44544   assert( assert_pager_state(pPager) );
44545
44546   /* An optimization. If the database was not actually modified during
44547   ** this transaction, the pager is running in exclusive-mode and is
44548   ** using persistent journals, then this function is a no-op.
44549   **
44550   ** The start of the journal file currently contains a single journal 
44551   ** header with the nRec field set to 0. If such a journal is used as
44552   ** a hot-journal during hot-journal rollback, 0 changes will be made
44553   ** to the database file. So there is no need to zero the journal 
44554   ** header. Since the pager is in exclusive mode, there is no need
44555   ** to drop any locks either.
44556   */
44557   if( pPager->eState==PAGER_WRITER_LOCKED 
44558    && pPager->exclusiveMode 
44559    && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
44560   ){
44561     assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
44562     pPager->eState = PAGER_READER;
44563     return SQLITE_OK;
44564   }
44565
44566   PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
44567   rc = pager_end_transaction(pPager, pPager->setMaster, 1);
44568   return pager_error(pPager, rc);
44569 }
44570
44571 /*
44572 ** If a write transaction is open, then all changes made within the 
44573 ** transaction are reverted and the current write-transaction is closed.
44574 ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
44575 ** state if an error occurs.
44576 **
44577 ** If the pager is already in PAGER_ERROR state when this function is called,
44578 ** it returns Pager.errCode immediately. No work is performed in this case.
44579 **
44580 ** Otherwise, in rollback mode, this function performs two functions:
44581 **
44582 **   1) It rolls back the journal file, restoring all database file and 
44583 **      in-memory cache pages to the state they were in when the transaction
44584 **      was opened, and
44585 **
44586 **   2) It finalizes the journal file, so that it is not used for hot
44587 **      rollback at any point in the future.
44588 **
44589 ** Finalization of the journal file (task 2) is only performed if the 
44590 ** rollback is successful.
44591 **
44592 ** In WAL mode, all cache-entries containing data modified within the
44593 ** current transaction are either expelled from the cache or reverted to
44594 ** their pre-transaction state by re-reading data from the database or
44595 ** WAL files. The WAL transaction is then closed.
44596 */
44597 SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
44598   int rc = SQLITE_OK;                  /* Return code */
44599   PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
44600
44601   /* PagerRollback() is a no-op if called in READER or OPEN state. If
44602   ** the pager is already in the ERROR state, the rollback is not 
44603   ** attempted here. Instead, the error code is returned to the caller.
44604   */
44605   assert( assert_pager_state(pPager) );
44606   if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
44607   if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
44608
44609   if( pagerUseWal(pPager) ){
44610     int rc2;
44611     rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
44612     rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);
44613     if( rc==SQLITE_OK ) rc = rc2;
44614   }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
44615     int eState = pPager->eState;
44616     rc = pager_end_transaction(pPager, 0, 0);
44617     if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
44618       /* This can happen using journal_mode=off. Move the pager to the error 
44619       ** state to indicate that the contents of the cache may not be trusted.
44620       ** Any active readers will get SQLITE_ABORT.
44621       */
44622       pPager->errCode = SQLITE_ABORT;
44623       pPager->eState = PAGER_ERROR;
44624       return rc;
44625     }
44626   }else{
44627     rc = pager_playback(pPager, 0);
44628   }
44629
44630   assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
44631   assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
44632           || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR );
44633
44634   /* If an error occurs during a ROLLBACK, we can no longer trust the pager
44635   ** cache. So call pager_error() on the way out to make any error persistent.
44636   */
44637   return pager_error(pPager, rc);
44638 }
44639
44640 /*
44641 ** Return TRUE if the database file is opened read-only.  Return FALSE
44642 ** if the database is (in theory) writable.
44643 */
44644 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
44645   return pPager->readOnly;
44646 }
44647
44648 /*
44649 ** Return the number of references to the pager.
44650 */
44651 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
44652   return sqlite3PcacheRefCount(pPager->pPCache);
44653 }
44654
44655 /*
44656 ** Return the approximate number of bytes of memory currently
44657 ** used by the pager and its associated cache.
44658 */
44659 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
44660   int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
44661                                      + 5*sizeof(void*);
44662   return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
44663            + sqlite3MallocSize(pPager)
44664            + pPager->pageSize;
44665 }
44666
44667 /*
44668 ** Return the number of references to the specified page.
44669 */
44670 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
44671   return sqlite3PcachePageRefcount(pPage);
44672 }
44673
44674 #ifdef SQLITE_TEST
44675 /*
44676 ** This routine is used for testing and analysis only.
44677 */
44678 SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
44679   static int a[11];
44680   a[0] = sqlite3PcacheRefCount(pPager->pPCache);
44681   a[1] = sqlite3PcachePagecount(pPager->pPCache);
44682   a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
44683   a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
44684   a[4] = pPager->eState;
44685   a[5] = pPager->errCode;
44686   a[6] = pPager->aStat[PAGER_STAT_HIT];
44687   a[7] = pPager->aStat[PAGER_STAT_MISS];
44688   a[8] = 0;  /* Used to be pPager->nOvfl */
44689   a[9] = pPager->nRead;
44690   a[10] = pPager->aStat[PAGER_STAT_WRITE];
44691   return a;
44692 }
44693 #endif
44694
44695 /*
44696 ** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
44697 ** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
44698 ** current cache hit or miss count, according to the value of eStat. If the 
44699 ** reset parameter is non-zero, the cache hit or miss count is zeroed before 
44700 ** returning.
44701 */
44702 SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
44703
44704   assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
44705        || eStat==SQLITE_DBSTATUS_CACHE_MISS
44706        || eStat==SQLITE_DBSTATUS_CACHE_WRITE
44707   );
44708
44709   assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
44710   assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
44711   assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 );
44712
44713   *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT];
44714   if( reset ){
44715     pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;
44716   }
44717 }
44718
44719 /*
44720 ** Return true if this is an in-memory pager.
44721 */
44722 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
44723   return MEMDB;
44724 }
44725
44726 /*
44727 ** Check that there are at least nSavepoint savepoints open. If there are
44728 ** currently less than nSavepoints open, then open one or more savepoints
44729 ** to make up the difference. If the number of savepoints is already
44730 ** equal to nSavepoint, then this function is a no-op.
44731 **
44732 ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error 
44733 ** occurs while opening the sub-journal file, then an IO error code is
44734 ** returned. Otherwise, SQLITE_OK.
44735 */
44736 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
44737   int rc = SQLITE_OK;                       /* Return code */
44738   int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
44739
44740   assert( pPager->eState>=PAGER_WRITER_LOCKED );
44741   assert( assert_pager_state(pPager) );
44742
44743   if( nSavepoint>nCurrent && pPager->useJournal ){
44744     int ii;                                 /* Iterator variable */
44745     PagerSavepoint *aNew;                   /* New Pager.aSavepoint array */
44746
44747     /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
44748     ** if the allocation fails. Otherwise, zero the new portion in case a 
44749     ** malloc failure occurs while populating it in the for(...) loop below.
44750     */
44751     aNew = (PagerSavepoint *)sqlite3Realloc(
44752         pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
44753     );
44754     if( !aNew ){
44755       return SQLITE_NOMEM;
44756     }
44757     memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
44758     pPager->aSavepoint = aNew;
44759
44760     /* Populate the PagerSavepoint structures just allocated. */
44761     for(ii=nCurrent; ii<nSavepoint; ii++){
44762       aNew[ii].nOrig = pPager->dbSize;
44763       if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
44764         aNew[ii].iOffset = pPager->journalOff;
44765       }else{
44766         aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
44767       }
44768       aNew[ii].iSubRec = pPager->nSubRec;
44769       aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
44770       if( !aNew[ii].pInSavepoint ){
44771         return SQLITE_NOMEM;
44772       }
44773       if( pagerUseWal(pPager) ){
44774         sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
44775       }
44776       pPager->nSavepoint = ii+1;
44777     }
44778     assert( pPager->nSavepoint==nSavepoint );
44779     assertTruncateConstraint(pPager);
44780   }
44781
44782   return rc;
44783 }
44784
44785 /*
44786 ** This function is called to rollback or release (commit) a savepoint.
44787 ** The savepoint to release or rollback need not be the most recently 
44788 ** created savepoint.
44789 **
44790 ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
44791 ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
44792 ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
44793 ** that have occurred since the specified savepoint was created.
44794 **
44795 ** The savepoint to rollback or release is identified by parameter 
44796 ** iSavepoint. A value of 0 means to operate on the outermost savepoint
44797 ** (the first created). A value of (Pager.nSavepoint-1) means operate
44798 ** on the most recently created savepoint. If iSavepoint is greater than
44799 ** (Pager.nSavepoint-1), then this function is a no-op.
44800 **
44801 ** If a negative value is passed to this function, then the current
44802 ** transaction is rolled back. This is different to calling 
44803 ** sqlite3PagerRollback() because this function does not terminate
44804 ** the transaction or unlock the database, it just restores the 
44805 ** contents of the database to its original state. 
44806 **
44807 ** In any case, all savepoints with an index greater than iSavepoint 
44808 ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
44809 ** then savepoint iSavepoint is also destroyed.
44810 **
44811 ** This function may return SQLITE_NOMEM if a memory allocation fails,
44812 ** or an IO error code if an IO error occurs while rolling back a 
44813 ** savepoint. If no errors occur, SQLITE_OK is returned.
44814 */ 
44815 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
44816   int rc = pPager->errCode;       /* Return code */
44817
44818   assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
44819   assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
44820
44821   if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
44822     int ii;            /* Iterator variable */
44823     int nNew;          /* Number of remaining savepoints after this op. */
44824
44825     /* Figure out how many savepoints will still be active after this
44826     ** operation. Store this value in nNew. Then free resources associated 
44827     ** with any savepoints that are destroyed by this operation.
44828     */
44829     nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
44830     for(ii=nNew; ii<pPager->nSavepoint; ii++){
44831       sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
44832     }
44833     pPager->nSavepoint = nNew;
44834
44835     /* If this is a release of the outermost savepoint, truncate 
44836     ** the sub-journal to zero bytes in size. */
44837     if( op==SAVEPOINT_RELEASE ){
44838       if( nNew==0 && isOpen(pPager->sjfd) ){
44839         /* Only truncate if it is an in-memory sub-journal. */
44840         if( sqlite3IsMemJournal(pPager->sjfd) ){
44841           rc = sqlite3OsTruncate(pPager->sjfd, 0);
44842           assert( rc==SQLITE_OK );
44843         }
44844         pPager->nSubRec = 0;
44845       }
44846     }
44847     /* Else this is a rollback operation, playback the specified savepoint.
44848     ** If this is a temp-file, it is possible that the journal file has
44849     ** not yet been opened. In this case there have been no changes to
44850     ** the database file, so the playback operation can be skipped.
44851     */
44852     else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
44853       PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
44854       rc = pagerPlaybackSavepoint(pPager, pSavepoint);
44855       assert(rc!=SQLITE_DONE);
44856     }
44857   }
44858
44859   return rc;
44860 }
44861
44862 /*
44863 ** Return the full pathname of the database file.
44864 **
44865 ** Except, if the pager is in-memory only, then return an empty string if
44866 ** nullIfMemDb is true.  This routine is called with nullIfMemDb==1 when
44867 ** used to report the filename to the user, for compatibility with legacy
44868 ** behavior.  But when the Btree needs to know the filename for matching to
44869 ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
44870 ** participate in shared-cache.
44871 */
44872 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
44873   return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
44874 }
44875
44876 /*
44877 ** Return the VFS structure for the pager.
44878 */
44879 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
44880   return pPager->pVfs;
44881 }
44882
44883 /*
44884 ** Return the file handle for the database file associated
44885 ** with the pager.  This might return NULL if the file has
44886 ** not yet been opened.
44887 */
44888 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
44889   return pPager->fd;
44890 }
44891
44892 /*
44893 ** Return the full pathname of the journal file.
44894 */
44895 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
44896   return pPager->zJournal;
44897 }
44898
44899 /*
44900 ** Return true if fsync() calls are disabled for this pager.  Return FALSE
44901 ** if fsync()s are executed normally.
44902 */
44903 SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
44904   return pPager->noSync;
44905 }
44906
44907 #ifdef SQLITE_HAS_CODEC
44908 /*
44909 ** Set or retrieve the codec for this pager
44910 */
44911 SQLITE_PRIVATE void sqlite3PagerSetCodec(
44912   Pager *pPager,
44913   void *(*xCodec)(void*,void*,Pgno,int),
44914   void (*xCodecSizeChng)(void*,int,int),
44915   void (*xCodecFree)(void*),
44916   void *pCodec
44917 ){
44918   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
44919   pPager->xCodec = pPager->memDb ? 0 : xCodec;
44920   pPager->xCodecSizeChng = xCodecSizeChng;
44921   pPager->xCodecFree = xCodecFree;
44922   pPager->pCodec = pCodec;
44923   pagerReportSize(pPager);
44924 }
44925 SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
44926   return pPager->pCodec;
44927 }
44928 #endif
44929
44930 #ifndef SQLITE_OMIT_AUTOVACUUM
44931 /*
44932 ** Move the page pPg to location pgno in the file.
44933 **
44934 ** There must be no references to the page previously located at
44935 ** pgno (which we call pPgOld) though that page is allowed to be
44936 ** in cache.  If the page previously located at pgno is not already
44937 ** in the rollback journal, it is not put there by by this routine.
44938 **
44939 ** References to the page pPg remain valid. Updating any
44940 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
44941 ** allocated along with the page) is the responsibility of the caller.
44942 **
44943 ** A transaction must be active when this routine is called. It used to be
44944 ** required that a statement transaction was not active, but this restriction
44945 ** has been removed (CREATE INDEX needs to move a page when a statement
44946 ** transaction is active).
44947 **
44948 ** If the fourth argument, isCommit, is non-zero, then this page is being
44949 ** moved as part of a database reorganization just before the transaction 
44950 ** is being committed. In this case, it is guaranteed that the database page 
44951 ** pPg refers to will not be written to again within this transaction.
44952 **
44953 ** This function may return SQLITE_NOMEM or an IO error code if an error
44954 ** occurs. Otherwise, it returns SQLITE_OK.
44955 */
44956 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
44957   PgHdr *pPgOld;               /* The page being overwritten. */
44958   Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
44959   int rc;                      /* Return code */
44960   Pgno origPgno;               /* The original page number */
44961
44962   assert( pPg->nRef>0 );
44963   assert( pPager->eState==PAGER_WRITER_CACHEMOD
44964        || pPager->eState==PAGER_WRITER_DBMOD
44965   );
44966   assert( assert_pager_state(pPager) );
44967
44968   /* In order to be able to rollback, an in-memory database must journal
44969   ** the page we are moving from.
44970   */
44971   if( MEMDB ){
44972     rc = sqlite3PagerWrite(pPg);
44973     if( rc ) return rc;
44974   }
44975
44976   /* If the page being moved is dirty and has not been saved by the latest
44977   ** savepoint, then save the current contents of the page into the 
44978   ** sub-journal now. This is required to handle the following scenario:
44979   **
44980   **   BEGIN;
44981   **     <journal page X, then modify it in memory>
44982   **     SAVEPOINT one;
44983   **       <Move page X to location Y>
44984   **     ROLLBACK TO one;
44985   **
44986   ** If page X were not written to the sub-journal here, it would not
44987   ** be possible to restore its contents when the "ROLLBACK TO one"
44988   ** statement were is processed.
44989   **
44990   ** subjournalPage() may need to allocate space to store pPg->pgno into
44991   ** one or more savepoint bitvecs. This is the reason this function
44992   ** may return SQLITE_NOMEM.
44993   */
44994   if( pPg->flags&PGHDR_DIRTY
44995    && subjRequiresPage(pPg)
44996    && SQLITE_OK!=(rc = subjournalPage(pPg))
44997   ){
44998     return rc;
44999   }
45000
45001   PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n", 
45002       PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
45003   IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
45004
45005   /* If the journal needs to be sync()ed before page pPg->pgno can
45006   ** be written to, store pPg->pgno in local variable needSyncPgno.
45007   **
45008   ** If the isCommit flag is set, there is no need to remember that
45009   ** the journal needs to be sync()ed before database page pPg->pgno 
45010   ** can be written to. The caller has already promised not to write to it.
45011   */
45012   if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
45013     needSyncPgno = pPg->pgno;
45014     assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
45015             pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
45016     assert( pPg->flags&PGHDR_DIRTY );
45017   }
45018
45019   /* If the cache contains a page with page-number pgno, remove it
45020   ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for 
45021   ** page pgno before the 'move' operation, it needs to be retained 
45022   ** for the page moved there.
45023   */
45024   pPg->flags &= ~PGHDR_NEED_SYNC;
45025   pPgOld = pager_lookup(pPager, pgno);
45026   assert( !pPgOld || pPgOld->nRef==1 );
45027   if( pPgOld ){
45028     pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
45029     if( MEMDB ){
45030       /* Do not discard pages from an in-memory database since we might
45031       ** need to rollback later.  Just move the page out of the way. */
45032       sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
45033     }else{
45034       sqlite3PcacheDrop(pPgOld);
45035     }
45036   }
45037
45038   origPgno = pPg->pgno;
45039   sqlite3PcacheMove(pPg, pgno);
45040   sqlite3PcacheMakeDirty(pPg);
45041
45042   /* For an in-memory database, make sure the original page continues
45043   ** to exist, in case the transaction needs to roll back.  Use pPgOld
45044   ** as the original page since it has already been allocated.
45045   */
45046   if( MEMDB ){
45047     assert( pPgOld );
45048     sqlite3PcacheMove(pPgOld, origPgno);
45049     sqlite3PagerUnref(pPgOld);
45050   }
45051
45052   if( needSyncPgno ){
45053     /* If needSyncPgno is non-zero, then the journal file needs to be 
45054     ** sync()ed before any data is written to database file page needSyncPgno.
45055     ** Currently, no such page exists in the page-cache and the 
45056     ** "is journaled" bitvec flag has been set. This needs to be remedied by
45057     ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
45058     ** flag.
45059     **
45060     ** If the attempt to load the page into the page-cache fails, (due
45061     ** to a malloc() or IO failure), clear the bit in the pInJournal[]
45062     ** array. Otherwise, if the page is loaded and written again in
45063     ** this transaction, it may be written to the database file before
45064     ** it is synced into the journal file. This way, it may end up in
45065     ** the journal file twice, but that is not a problem.
45066     */
45067     PgHdr *pPgHdr;
45068     rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
45069     if( rc!=SQLITE_OK ){
45070       if( needSyncPgno<=pPager->dbOrigSize ){
45071         assert( pPager->pTmpSpace!=0 );
45072         sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
45073       }
45074       return rc;
45075     }
45076     pPgHdr->flags |= PGHDR_NEED_SYNC;
45077     sqlite3PcacheMakeDirty(pPgHdr);
45078     sqlite3PagerUnref(pPgHdr);
45079   }
45080
45081   return SQLITE_OK;
45082 }
45083 #endif
45084
45085 /*
45086 ** Return a pointer to the data for the specified page.
45087 */
45088 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
45089   assert( pPg->nRef>0 || pPg->pPager->memDb );
45090   return pPg->pData;
45091 }
45092
45093 /*
45094 ** Return a pointer to the Pager.nExtra bytes of "extra" space 
45095 ** allocated along with the specified page.
45096 */
45097 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
45098   return pPg->pExtra;
45099 }
45100
45101 /*
45102 ** Get/set the locking-mode for this pager. Parameter eMode must be one
45103 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or 
45104 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
45105 ** the locking-mode is set to the value specified.
45106 **
45107 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
45108 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
45109 ** locking-mode.
45110 */
45111 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
45112   assert( eMode==PAGER_LOCKINGMODE_QUERY
45113             || eMode==PAGER_LOCKINGMODE_NORMAL
45114             || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
45115   assert( PAGER_LOCKINGMODE_QUERY<0 );
45116   assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
45117   assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
45118   if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
45119     pPager->exclusiveMode = (u8)eMode;
45120   }
45121   return (int)pPager->exclusiveMode;
45122 }
45123
45124 /*
45125 ** Set the journal-mode for this pager. Parameter eMode must be one of:
45126 **
45127 **    PAGER_JOURNALMODE_DELETE
45128 **    PAGER_JOURNALMODE_TRUNCATE
45129 **    PAGER_JOURNALMODE_PERSIST
45130 **    PAGER_JOURNALMODE_OFF
45131 **    PAGER_JOURNALMODE_MEMORY
45132 **    PAGER_JOURNALMODE_WAL
45133 **
45134 ** The journalmode is set to the value specified if the change is allowed.
45135 ** The change may be disallowed for the following reasons:
45136 **
45137 **   *  An in-memory database can only have its journal_mode set to _OFF
45138 **      or _MEMORY.
45139 **
45140 **   *  Temporary databases cannot have _WAL journalmode.
45141 **
45142 ** The returned indicate the current (possibly updated) journal-mode.
45143 */
45144 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
45145   u8 eOld = pPager->journalMode;    /* Prior journalmode */
45146
45147 #ifdef SQLITE_DEBUG
45148   /* The print_pager_state() routine is intended to be used by the debugger
45149   ** only.  We invoke it once here to suppress a compiler warning. */
45150   print_pager_state(pPager);
45151 #endif
45152
45153
45154   /* The eMode parameter is always valid */
45155   assert(      eMode==PAGER_JOURNALMODE_DELETE
45156             || eMode==PAGER_JOURNALMODE_TRUNCATE
45157             || eMode==PAGER_JOURNALMODE_PERSIST
45158             || eMode==PAGER_JOURNALMODE_OFF 
45159             || eMode==PAGER_JOURNALMODE_WAL 
45160             || eMode==PAGER_JOURNALMODE_MEMORY );
45161
45162   /* This routine is only called from the OP_JournalMode opcode, and
45163   ** the logic there will never allow a temporary file to be changed
45164   ** to WAL mode.
45165   */
45166   assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
45167
45168   /* Do allow the journalmode of an in-memory database to be set to
45169   ** anything other than MEMORY or OFF
45170   */
45171   if( MEMDB ){
45172     assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
45173     if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
45174       eMode = eOld;
45175     }
45176   }
45177
45178   if( eMode!=eOld ){
45179
45180     /* Change the journal mode. */
45181     assert( pPager->eState!=PAGER_ERROR );
45182     pPager->journalMode = (u8)eMode;
45183
45184     /* When transistioning from TRUNCATE or PERSIST to any other journal
45185     ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
45186     ** delete the journal file.
45187     */
45188     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
45189     assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
45190     assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
45191     assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
45192     assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
45193     assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
45194
45195     assert( isOpen(pPager->fd) || pPager->exclusiveMode );
45196     if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
45197
45198       /* In this case we would like to delete the journal file. If it is
45199       ** not possible, then that is not a problem. Deleting the journal file
45200       ** here is an optimization only.
45201       **
45202       ** Before deleting the journal file, obtain a RESERVED lock on the
45203       ** database file. This ensures that the journal file is not deleted
45204       ** while it is in use by some other client.
45205       */
45206       sqlite3OsClose(pPager->jfd);
45207       if( pPager->eLock>=RESERVED_LOCK ){
45208         sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
45209       }else{
45210         int rc = SQLITE_OK;
45211         int state = pPager->eState;
45212         assert( state==PAGER_OPEN || state==PAGER_READER );
45213         if( state==PAGER_OPEN ){
45214           rc = sqlite3PagerSharedLock(pPager);
45215         }
45216         if( pPager->eState==PAGER_READER ){
45217           assert( rc==SQLITE_OK );
45218           rc = pagerLockDb(pPager, RESERVED_LOCK);
45219         }
45220         if( rc==SQLITE_OK ){
45221           sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
45222         }
45223         if( rc==SQLITE_OK && state==PAGER_READER ){
45224           pagerUnlockDb(pPager, SHARED_LOCK);
45225         }else if( state==PAGER_OPEN ){
45226           pager_unlock(pPager);
45227         }
45228         assert( state==pPager->eState );
45229       }
45230     }
45231   }
45232
45233   /* Return the new journal mode */
45234   return (int)pPager->journalMode;
45235 }
45236
45237 /*
45238 ** Return the current journal mode.
45239 */
45240 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
45241   return (int)pPager->journalMode;
45242 }
45243
45244 /*
45245 ** Return TRUE if the pager is in a state where it is OK to change the
45246 ** journalmode.  Journalmode changes can only happen when the database
45247 ** is unmodified.
45248 */
45249 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
45250   assert( assert_pager_state(pPager) );
45251   if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
45252   if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
45253   return 1;
45254 }
45255
45256 /*
45257 ** Get/set the size-limit used for persistent journal files.
45258 **
45259 ** Setting the size limit to -1 means no limit is enforced.
45260 ** An attempt to set a limit smaller than -1 is a no-op.
45261 */
45262 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
45263   if( iLimit>=-1 ){
45264     pPager->journalSizeLimit = iLimit;
45265     sqlite3WalLimit(pPager->pWal, iLimit);
45266   }
45267   return pPager->journalSizeLimit;
45268 }
45269
45270 /*
45271 ** Return a pointer to the pPager->pBackup variable. The backup module
45272 ** in backup.c maintains the content of this variable. This module
45273 ** uses it opaquely as an argument to sqlite3BackupRestart() and
45274 ** sqlite3BackupUpdate() only.
45275 */
45276 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
45277   return &pPager->pBackup;
45278 }
45279
45280 #ifndef SQLITE_OMIT_VACUUM
45281 /*
45282 ** Unless this is an in-memory or temporary database, clear the pager cache.
45283 */
45284 SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
45285   if( !MEMDB && pPager->tempFile==0 ) pager_reset(pPager);
45286 }
45287 #endif
45288
45289 #ifndef SQLITE_OMIT_WAL
45290 /*
45291 ** This function is called when the user invokes "PRAGMA wal_checkpoint",
45292 ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
45293 ** or wal_blocking_checkpoint() API functions.
45294 **
45295 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
45296 */
45297 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
45298   int rc = SQLITE_OK;
45299   if( pPager->pWal ){
45300     rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
45301         pPager->xBusyHandler, pPager->pBusyHandlerArg,
45302         pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
45303         pnLog, pnCkpt
45304     );
45305   }
45306   return rc;
45307 }
45308
45309 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
45310   return sqlite3WalCallback(pPager->pWal);
45311 }
45312
45313 /*
45314 ** Return true if the underlying VFS for the given pager supports the
45315 ** primitives necessary for write-ahead logging.
45316 */
45317 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
45318   const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
45319   return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
45320 }
45321
45322 /*
45323 ** Attempt to take an exclusive lock on the database file. If a PENDING lock
45324 ** is obtained instead, immediately release it.
45325 */
45326 static int pagerExclusiveLock(Pager *pPager){
45327   int rc;                         /* Return code */
45328
45329   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
45330   rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
45331   if( rc!=SQLITE_OK ){
45332     /* If the attempt to grab the exclusive lock failed, release the 
45333     ** pending lock that may have been obtained instead.  */
45334     pagerUnlockDb(pPager, SHARED_LOCK);
45335   }
45336
45337   return rc;
45338 }
45339
45340 /*
45341 ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in 
45342 ** exclusive-locking mode when this function is called, take an EXCLUSIVE
45343 ** lock on the database file and use heap-memory to store the wal-index
45344 ** in. Otherwise, use the normal shared-memory.
45345 */
45346 static int pagerOpenWal(Pager *pPager){
45347   int rc = SQLITE_OK;
45348
45349   assert( pPager->pWal==0 && pPager->tempFile==0 );
45350   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
45351
45352   /* If the pager is already in exclusive-mode, the WAL module will use 
45353   ** heap-memory for the wal-index instead of the VFS shared-memory 
45354   ** implementation. Take the exclusive lock now, before opening the WAL
45355   ** file, to make sure this is safe.
45356   */
45357   if( pPager->exclusiveMode ){
45358     rc = pagerExclusiveLock(pPager);
45359   }
45360
45361   /* Open the connection to the log file. If this operation fails, 
45362   ** (e.g. due to malloc() failure), return an error code.
45363   */
45364   if( rc==SQLITE_OK ){
45365     rc = sqlite3WalOpen(pPager->pVfs,
45366         pPager->fd, pPager->zWal, pPager->exclusiveMode,
45367         pPager->journalSizeLimit, &pPager->pWal
45368     );
45369   }
45370   pagerFixMaplimit(pPager);
45371
45372   return rc;
45373 }
45374
45375
45376 /*
45377 ** The caller must be holding a SHARED lock on the database file to call
45378 ** this function.
45379 **
45380 ** If the pager passed as the first argument is open on a real database
45381 ** file (not a temp file or an in-memory database), and the WAL file
45382 ** is not already open, make an attempt to open it now. If successful,
45383 ** return SQLITE_OK. If an error occurs or the VFS used by the pager does 
45384 ** not support the xShmXXX() methods, return an error code. *pbOpen is
45385 ** not modified in either case.
45386 **
45387 ** If the pager is open on a temp-file (or in-memory database), or if
45388 ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
45389 ** without doing anything.
45390 */
45391 SQLITE_PRIVATE int sqlite3PagerOpenWal(
45392   Pager *pPager,                  /* Pager object */
45393   int *pbOpen                     /* OUT: Set to true if call is a no-op */
45394 ){
45395   int rc = SQLITE_OK;             /* Return code */
45396
45397   assert( assert_pager_state(pPager) );
45398   assert( pPager->eState==PAGER_OPEN   || pbOpen );
45399   assert( pPager->eState==PAGER_READER || !pbOpen );
45400   assert( pbOpen==0 || *pbOpen==0 );
45401   assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
45402
45403   if( !pPager->tempFile && !pPager->pWal ){
45404     if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
45405
45406     /* Close any rollback journal previously open */
45407     sqlite3OsClose(pPager->jfd);
45408
45409     rc = pagerOpenWal(pPager);
45410     if( rc==SQLITE_OK ){
45411       pPager->journalMode = PAGER_JOURNALMODE_WAL;
45412       pPager->eState = PAGER_OPEN;
45413     }
45414   }else{
45415     *pbOpen = 1;
45416   }
45417
45418   return rc;
45419 }
45420
45421 /*
45422 ** This function is called to close the connection to the log file prior
45423 ** to switching from WAL to rollback mode.
45424 **
45425 ** Before closing the log file, this function attempts to take an 
45426 ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
45427 ** error (SQLITE_BUSY) is returned and the log connection is not closed.
45428 ** If successful, the EXCLUSIVE lock is not released before returning.
45429 */
45430 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
45431   int rc = SQLITE_OK;
45432
45433   assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
45434
45435   /* If the log file is not already open, but does exist in the file-system,
45436   ** it may need to be checkpointed before the connection can switch to
45437   ** rollback mode. Open it now so this can happen.
45438   */
45439   if( !pPager->pWal ){
45440     int logexists = 0;
45441     rc = pagerLockDb(pPager, SHARED_LOCK);
45442     if( rc==SQLITE_OK ){
45443       rc = sqlite3OsAccess(
45444           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
45445       );
45446     }
45447     if( rc==SQLITE_OK && logexists ){
45448       rc = pagerOpenWal(pPager);
45449     }
45450   }
45451     
45452   /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
45453   ** the database file, the log and log-summary files will be deleted.
45454   */
45455   if( rc==SQLITE_OK && pPager->pWal ){
45456     rc = pagerExclusiveLock(pPager);
45457     if( rc==SQLITE_OK ){
45458       rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
45459                            pPager->pageSize, (u8*)pPager->pTmpSpace);
45460       pPager->pWal = 0;
45461       pagerFixMaplimit(pPager);
45462     }
45463   }
45464   return rc;
45465 }
45466
45467 #endif /* !SQLITE_OMIT_WAL */
45468
45469 #ifdef SQLITE_ENABLE_ZIPVFS
45470 /*
45471 ** A read-lock must be held on the pager when this function is called. If
45472 ** the pager is in WAL mode and the WAL file currently contains one or more
45473 ** frames, return the size in bytes of the page images stored within the
45474 ** WAL frames. Otherwise, if this is not a WAL database or the WAL file
45475 ** is empty, return 0.
45476 */
45477 SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
45478   assert( pPager->eState==PAGER_READER );
45479   return sqlite3WalFramesize(pPager->pWal);
45480 }
45481 #endif
45482
45483 #ifdef SQLITE_HAS_CODEC
45484 /*
45485 ** This function is called by the wal module when writing page content
45486 ** into the log file.
45487 **
45488 ** This function returns a pointer to a buffer containing the encrypted
45489 ** page content. If a malloc fails, this function may return NULL.
45490 */
45491 SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
45492   void *aData = 0;
45493   CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
45494   return aData;
45495 }
45496 #endif /* SQLITE_HAS_CODEC */
45497
45498 #endif /* SQLITE_OMIT_DISKIO */
45499
45500 /************** End of pager.c ***********************************************/
45501 /************** Begin file wal.c *********************************************/
45502 /*
45503 ** 2010 February 1
45504 **
45505 ** The author disclaims copyright to this source code.  In place of
45506 ** a legal notice, here is a blessing:
45507 **
45508 **    May you do good and not evil.
45509 **    May you find forgiveness for yourself and forgive others.
45510 **    May you share freely, never taking more than you give.
45511 **
45512 *************************************************************************
45513 **
45514 ** This file contains the implementation of a write-ahead log (WAL) used in 
45515 ** "journal_mode=WAL" mode.
45516 **
45517 ** WRITE-AHEAD LOG (WAL) FILE FORMAT
45518 **
45519 ** A WAL file consists of a header followed by zero or more "frames".
45520 ** Each frame records the revised content of a single page from the
45521 ** database file.  All changes to the database are recorded by writing
45522 ** frames into the WAL.  Transactions commit when a frame is written that
45523 ** contains a commit marker.  A single WAL can and usually does record 
45524 ** multiple transactions.  Periodically, the content of the WAL is
45525 ** transferred back into the database file in an operation called a
45526 ** "checkpoint".
45527 **
45528 ** A single WAL file can be used multiple times.  In other words, the
45529 ** WAL can fill up with frames and then be checkpointed and then new
45530 ** frames can overwrite the old ones.  A WAL always grows from beginning
45531 ** toward the end.  Checksums and counters attached to each frame are
45532 ** used to determine which frames within the WAL are valid and which
45533 ** are leftovers from prior checkpoints.
45534 **
45535 ** The WAL header is 32 bytes in size and consists of the following eight
45536 ** big-endian 32-bit unsigned integer values:
45537 **
45538 **     0: Magic number.  0x377f0682 or 0x377f0683
45539 **     4: File format version.  Currently 3007000
45540 **     8: Database page size.  Example: 1024
45541 **    12: Checkpoint sequence number
45542 **    16: Salt-1, random integer incremented with each checkpoint
45543 **    20: Salt-2, a different random integer changing with each ckpt
45544 **    24: Checksum-1 (first part of checksum for first 24 bytes of header).
45545 **    28: Checksum-2 (second part of checksum for first 24 bytes of header).
45546 **
45547 ** Immediately following the wal-header are zero or more frames. Each
45548 ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
45549 ** of page data. The frame-header is six big-endian 32-bit unsigned 
45550 ** integer values, as follows:
45551 **
45552 **     0: Page number.
45553 **     4: For commit records, the size of the database image in pages 
45554 **        after the commit. For all other records, zero.
45555 **     8: Salt-1 (copied from the header)
45556 **    12: Salt-2 (copied from the header)
45557 **    16: Checksum-1.
45558 **    20: Checksum-2.
45559 **
45560 ** A frame is considered valid if and only if the following conditions are
45561 ** true:
45562 **
45563 **    (1) The salt-1 and salt-2 values in the frame-header match
45564 **        salt values in the wal-header
45565 **
45566 **    (2) The checksum values in the final 8 bytes of the frame-header
45567 **        exactly match the checksum computed consecutively on the
45568 **        WAL header and the first 8 bytes and the content of all frames
45569 **        up to and including the current frame.
45570 **
45571 ** The checksum is computed using 32-bit big-endian integers if the
45572 ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
45573 ** is computed using little-endian if the magic number is 0x377f0682.
45574 ** The checksum values are always stored in the frame header in a
45575 ** big-endian format regardless of which byte order is used to compute
45576 ** the checksum.  The checksum is computed by interpreting the input as
45577 ** an even number of unsigned 32-bit integers: x[0] through x[N].  The
45578 ** algorithm used for the checksum is as follows:
45579 ** 
45580 **   for i from 0 to n-1 step 2:
45581 **     s0 += x[i] + s1;
45582 **     s1 += x[i+1] + s0;
45583 **   endfor
45584 **
45585 ** Note that s0 and s1 are both weighted checksums using fibonacci weights
45586 ** in reverse order (the largest fibonacci weight occurs on the first element
45587 ** of the sequence being summed.)  The s1 value spans all 32-bit 
45588 ** terms of the sequence whereas s0 omits the final term.
45589 **
45590 ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
45591 ** WAL is transferred into the database, then the database is VFS.xSync-ed.
45592 ** The VFS.xSync operations serve as write barriers - all writes launched
45593 ** before the xSync must complete before any write that launches after the
45594 ** xSync begins.
45595 **
45596 ** After each checkpoint, the salt-1 value is incremented and the salt-2
45597 ** value is randomized.  This prevents old and new frames in the WAL from
45598 ** being considered valid at the same time and being checkpointing together
45599 ** following a crash.
45600 **
45601 ** READER ALGORITHM
45602 **
45603 ** To read a page from the database (call it page number P), a reader
45604 ** first checks the WAL to see if it contains page P.  If so, then the
45605 ** last valid instance of page P that is a followed by a commit frame
45606 ** or is a commit frame itself becomes the value read.  If the WAL
45607 ** contains no copies of page P that are valid and which are a commit
45608 ** frame or are followed by a commit frame, then page P is read from
45609 ** the database file.
45610 **
45611 ** To start a read transaction, the reader records the index of the last
45612 ** valid frame in the WAL.  The reader uses this recorded "mxFrame" value
45613 ** for all subsequent read operations.  New transactions can be appended
45614 ** to the WAL, but as long as the reader uses its original mxFrame value
45615 ** and ignores the newly appended content, it will see a consistent snapshot
45616 ** of the database from a single point in time.  This technique allows
45617 ** multiple concurrent readers to view different versions of the database
45618 ** content simultaneously.
45619 **
45620 ** The reader algorithm in the previous paragraphs works correctly, but 
45621 ** because frames for page P can appear anywhere within the WAL, the
45622 ** reader has to scan the entire WAL looking for page P frames.  If the
45623 ** WAL is large (multiple megabytes is typical) that scan can be slow,
45624 ** and read performance suffers.  To overcome this problem, a separate
45625 ** data structure called the wal-index is maintained to expedite the
45626 ** search for frames of a particular page.
45627 ** 
45628 ** WAL-INDEX FORMAT
45629 **
45630 ** Conceptually, the wal-index is shared memory, though VFS implementations
45631 ** might choose to implement the wal-index using a mmapped file.  Because
45632 ** the wal-index is shared memory, SQLite does not support journal_mode=WAL 
45633 ** on a network filesystem.  All users of the database must be able to
45634 ** share memory.
45635 **
45636 ** The wal-index is transient.  After a crash, the wal-index can (and should
45637 ** be) reconstructed from the original WAL file.  In fact, the VFS is required
45638 ** to either truncate or zero the header of the wal-index when the last
45639 ** connection to it closes.  Because the wal-index is transient, it can
45640 ** use an architecture-specific format; it does not have to be cross-platform.
45641 ** Hence, unlike the database and WAL file formats which store all values
45642 ** as big endian, the wal-index can store multi-byte values in the native
45643 ** byte order of the host computer.
45644 **
45645 ** The purpose of the wal-index is to answer this question quickly:  Given
45646 ** a page number P and a maximum frame index M, return the index of the 
45647 ** last frame in the wal before frame M for page P in the WAL, or return
45648 ** NULL if there are no frames for page P in the WAL prior to M.
45649 **
45650 ** The wal-index consists of a header region, followed by an one or
45651 ** more index blocks.  
45652 **
45653 ** The wal-index header contains the total number of frames within the WAL
45654 ** in the mxFrame field.
45655 **
45656 ** Each index block except for the first contains information on 
45657 ** HASHTABLE_NPAGE frames. The first index block contains information on
45658 ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and 
45659 ** HASHTABLE_NPAGE are selected so that together the wal-index header and
45660 ** first index block are the same size as all other index blocks in the
45661 ** wal-index.
45662 **
45663 ** Each index block contains two sections, a page-mapping that contains the
45664 ** database page number associated with each wal frame, and a hash-table 
45665 ** that allows readers to query an index block for a specific page number.
45666 ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
45667 ** for the first index block) 32-bit page numbers. The first entry in the 
45668 ** first index-block contains the database page number corresponding to the
45669 ** first frame in the WAL file. The first entry in the second index block
45670 ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
45671 ** the log, and so on.
45672 **
45673 ** The last index block in a wal-index usually contains less than the full
45674 ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
45675 ** depending on the contents of the WAL file. This does not change the
45676 ** allocated size of the page-mapping array - the page-mapping array merely
45677 ** contains unused entries.
45678 **
45679 ** Even without using the hash table, the last frame for page P
45680 ** can be found by scanning the page-mapping sections of each index block
45681 ** starting with the last index block and moving toward the first, and
45682 ** within each index block, starting at the end and moving toward the
45683 ** beginning.  The first entry that equals P corresponds to the frame
45684 ** holding the content for that page.
45685 **
45686 ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
45687 ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
45688 ** hash table for each page number in the mapping section, so the hash 
45689 ** table is never more than half full.  The expected number of collisions 
45690 ** prior to finding a match is 1.  Each entry of the hash table is an
45691 ** 1-based index of an entry in the mapping section of the same
45692 ** index block.   Let K be the 1-based index of the largest entry in
45693 ** the mapping section.  (For index blocks other than the last, K will
45694 ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
45695 ** K will be (mxFrame%HASHTABLE_NPAGE).)  Unused slots of the hash table
45696 ** contain a value of 0.
45697 **
45698 ** To look for page P in the hash table, first compute a hash iKey on
45699 ** P as follows:
45700 **
45701 **      iKey = (P * 383) % HASHTABLE_NSLOT
45702 **
45703 ** Then start scanning entries of the hash table, starting with iKey
45704 ** (wrapping around to the beginning when the end of the hash table is
45705 ** reached) until an unused hash slot is found. Let the first unused slot
45706 ** be at index iUnused.  (iUnused might be less than iKey if there was
45707 ** wrap-around.) Because the hash table is never more than half full,
45708 ** the search is guaranteed to eventually hit an unused entry.  Let 
45709 ** iMax be the value between iKey and iUnused, closest to iUnused,
45710 ** where aHash[iMax]==P.  If there is no iMax entry (if there exists
45711 ** no hash slot such that aHash[i]==p) then page P is not in the
45712 ** current index block.  Otherwise the iMax-th mapping entry of the
45713 ** current index block corresponds to the last entry that references 
45714 ** page P.
45715 **
45716 ** A hash search begins with the last index block and moves toward the
45717 ** first index block, looking for entries corresponding to page P.  On
45718 ** average, only two or three slots in each index block need to be
45719 ** examined in order to either find the last entry for page P, or to
45720 ** establish that no such entry exists in the block.  Each index block
45721 ** holds over 4000 entries.  So two or three index blocks are sufficient
45722 ** to cover a typical 10 megabyte WAL file, assuming 1K pages.  8 or 10
45723 ** comparisons (on average) suffice to either locate a frame in the
45724 ** WAL or to establish that the frame does not exist in the WAL.  This
45725 ** is much faster than scanning the entire 10MB WAL.
45726 **
45727 ** Note that entries are added in order of increasing K.  Hence, one
45728 ** reader might be using some value K0 and a second reader that started
45729 ** at a later time (after additional transactions were added to the WAL
45730 ** and to the wal-index) might be using a different value K1, where K1>K0.
45731 ** Both readers can use the same hash table and mapping section to get
45732 ** the correct result.  There may be entries in the hash table with
45733 ** K>K0 but to the first reader, those entries will appear to be unused
45734 ** slots in the hash table and so the first reader will get an answer as
45735 ** if no values greater than K0 had ever been inserted into the hash table
45736 ** in the first place - which is what reader one wants.  Meanwhile, the
45737 ** second reader using K1 will see additional values that were inserted
45738 ** later, which is exactly what reader two wants.  
45739 **
45740 ** When a rollback occurs, the value of K is decreased. Hash table entries
45741 ** that correspond to frames greater than the new K value are removed
45742 ** from the hash table at this point.
45743 */
45744 #ifndef SQLITE_OMIT_WAL
45745
45746
45747 /*
45748 ** Trace output macros
45749 */
45750 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
45751 SQLITE_PRIVATE int sqlite3WalTrace = 0;
45752 # define WALTRACE(X)  if(sqlite3WalTrace) sqlite3DebugPrintf X
45753 #else
45754 # define WALTRACE(X)
45755 #endif
45756
45757 /*
45758 ** The maximum (and only) versions of the wal and wal-index formats
45759 ** that may be interpreted by this version of SQLite.
45760 **
45761 ** If a client begins recovering a WAL file and finds that (a) the checksum
45762 ** values in the wal-header are correct and (b) the version field is not
45763 ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
45764 **
45765 ** Similarly, if a client successfully reads a wal-index header (i.e. the 
45766 ** checksum test is successful) and finds that the version field is not
45767 ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
45768 ** returns SQLITE_CANTOPEN.
45769 */
45770 #define WAL_MAX_VERSION      3007000
45771 #define WALINDEX_MAX_VERSION 3007000
45772
45773 /*
45774 ** Indices of various locking bytes.   WAL_NREADER is the number
45775 ** of available reader locks and should be at least 3.
45776 */
45777 #define WAL_WRITE_LOCK         0
45778 #define WAL_ALL_BUT_WRITE      1
45779 #define WAL_CKPT_LOCK          1
45780 #define WAL_RECOVER_LOCK       2
45781 #define WAL_READ_LOCK(I)       (3+(I))
45782 #define WAL_NREADER            (SQLITE_SHM_NLOCK-3)
45783
45784
45785 /* Object declarations */
45786 typedef struct WalIndexHdr WalIndexHdr;
45787 typedef struct WalIterator WalIterator;
45788 typedef struct WalCkptInfo WalCkptInfo;
45789
45790
45791 /*
45792 ** The following object holds a copy of the wal-index header content.
45793 **
45794 ** The actual header in the wal-index consists of two copies of this
45795 ** object.
45796 **
45797 ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
45798 ** Or it can be 1 to represent a 65536-byte page.  The latter case was
45799 ** added in 3.7.1 when support for 64K pages was added.  
45800 */
45801 struct WalIndexHdr {
45802   u32 iVersion;                   /* Wal-index version */
45803   u32 unused;                     /* Unused (padding) field */
45804   u32 iChange;                    /* Counter incremented each transaction */
45805   u8 isInit;                      /* 1 when initialized */
45806   u8 bigEndCksum;                 /* True if checksums in WAL are big-endian */
45807   u16 szPage;                     /* Database page size in bytes. 1==64K */
45808   u32 mxFrame;                    /* Index of last valid frame in the WAL */
45809   u32 nPage;                      /* Size of database in pages */
45810   u32 aFrameCksum[2];             /* Checksum of last frame in log */
45811   u32 aSalt[2];                   /* Two salt values copied from WAL header */
45812   u32 aCksum[2];                  /* Checksum over all prior fields */
45813 };
45814
45815 /*
45816 ** A copy of the following object occurs in the wal-index immediately
45817 ** following the second copy of the WalIndexHdr.  This object stores
45818 ** information used by checkpoint.
45819 **
45820 ** nBackfill is the number of frames in the WAL that have been written
45821 ** back into the database. (We call the act of moving content from WAL to
45822 ** database "backfilling".)  The nBackfill number is never greater than
45823 ** WalIndexHdr.mxFrame.  nBackfill can only be increased by threads
45824 ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
45825 ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
45826 ** mxFrame back to zero when the WAL is reset.
45827 **
45828 ** There is one entry in aReadMark[] for each reader lock.  If a reader
45829 ** holds read-lock K, then the value in aReadMark[K] is no greater than
45830 ** the mxFrame for that reader.  The value READMARK_NOT_USED (0xffffffff)
45831 ** for any aReadMark[] means that entry is unused.  aReadMark[0] is 
45832 ** a special case; its value is never used and it exists as a place-holder
45833 ** to avoid having to offset aReadMark[] indexs by one.  Readers holding
45834 ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
45835 ** directly from the database.
45836 **
45837 ** The value of aReadMark[K] may only be changed by a thread that
45838 ** is holding an exclusive lock on WAL_READ_LOCK(K).  Thus, the value of
45839 ** aReadMark[K] cannot changed while there is a reader is using that mark
45840 ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
45841 **
45842 ** The checkpointer may only transfer frames from WAL to database where
45843 ** the frame numbers are less than or equal to every aReadMark[] that is
45844 ** in use (that is, every aReadMark[j] for which there is a corresponding
45845 ** WAL_READ_LOCK(j)).  New readers (usually) pick the aReadMark[] with the
45846 ** largest value and will increase an unused aReadMark[] to mxFrame if there
45847 ** is not already an aReadMark[] equal to mxFrame.  The exception to the
45848 ** previous sentence is when nBackfill equals mxFrame (meaning that everything
45849 ** in the WAL has been backfilled into the database) then new readers
45850 ** will choose aReadMark[0] which has value 0 and hence such reader will
45851 ** get all their all content directly from the database file and ignore 
45852 ** the WAL.
45853 **
45854 ** Writers normally append new frames to the end of the WAL.  However,
45855 ** if nBackfill equals mxFrame (meaning that all WAL content has been
45856 ** written back into the database) and if no readers are using the WAL
45857 ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
45858 ** the writer will first "reset" the WAL back to the beginning and start
45859 ** writing new content beginning at frame 1.
45860 **
45861 ** We assume that 32-bit loads are atomic and so no locks are needed in
45862 ** order to read from any aReadMark[] entries.
45863 */
45864 struct WalCkptInfo {
45865   u32 nBackfill;                  /* Number of WAL frames backfilled into DB */
45866   u32 aReadMark[WAL_NREADER];     /* Reader marks */
45867 };
45868 #define READMARK_NOT_USED  0xffffffff
45869
45870
45871 /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
45872 ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
45873 ** only support mandatory file-locks, we do not read or write data
45874 ** from the region of the file on which locks are applied.
45875 */
45876 #define WALINDEX_LOCK_OFFSET   (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
45877 #define WALINDEX_LOCK_RESERVED 16
45878 #define WALINDEX_HDR_SIZE      (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
45879
45880 /* Size of header before each frame in wal */
45881 #define WAL_FRAME_HDRSIZE 24
45882
45883 /* Size of write ahead log header, including checksum. */
45884 /* #define WAL_HDRSIZE 24 */
45885 #define WAL_HDRSIZE 32
45886
45887 /* WAL magic value. Either this value, or the same value with the least
45888 ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
45889 ** big-endian format in the first 4 bytes of a WAL file.
45890 **
45891 ** If the LSB is set, then the checksums for each frame within the WAL
45892 ** file are calculated by treating all data as an array of 32-bit 
45893 ** big-endian words. Otherwise, they are calculated by interpreting 
45894 ** all data as 32-bit little-endian words.
45895 */
45896 #define WAL_MAGIC 0x377f0682
45897
45898 /*
45899 ** Return the offset of frame iFrame in the write-ahead log file, 
45900 ** assuming a database page size of szPage bytes. The offset returned
45901 ** is to the start of the write-ahead log frame-header.
45902 */
45903 #define walFrameOffset(iFrame, szPage) (                               \
45904   WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE)         \
45905 )
45906
45907 /*
45908 ** An open write-ahead log file is represented by an instance of the
45909 ** following object.
45910 */
45911 struct Wal {
45912   sqlite3_vfs *pVfs;         /* The VFS used to create pDbFd */
45913   sqlite3_file *pDbFd;       /* File handle for the database file */
45914   sqlite3_file *pWalFd;      /* File handle for WAL file */
45915   u32 iCallback;             /* Value to pass to log callback (or 0) */
45916   i64 mxWalSize;             /* Truncate WAL to this size upon reset */
45917   int nWiData;               /* Size of array apWiData */
45918   int szFirstBlock;          /* Size of first block written to WAL file */
45919   volatile u32 **apWiData;   /* Pointer to wal-index content in memory */
45920   u32 szPage;                /* Database page size */
45921   i16 readLock;              /* Which read lock is being held.  -1 for none */
45922   u8 syncFlags;              /* Flags to use to sync header writes */
45923   u8 exclusiveMode;          /* Non-zero if connection is in exclusive mode */
45924   u8 writeLock;              /* True if in a write transaction */
45925   u8 ckptLock;               /* True if holding a checkpoint lock */
45926   u8 readOnly;               /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
45927   u8 truncateOnCommit;       /* True to truncate WAL file on commit */
45928   u8 syncHeader;             /* Fsync the WAL header if true */
45929   u8 padToSectorBoundary;    /* Pad transactions out to the next sector */
45930   WalIndexHdr hdr;           /* Wal-index header for current transaction */
45931   const char *zWalName;      /* Name of WAL file */
45932   u32 nCkpt;                 /* Checkpoint sequence counter in the wal-header */
45933 #ifdef SQLITE_DEBUG
45934   u8 lockError;              /* True if a locking error has occurred */
45935 #endif
45936 };
45937
45938 /*
45939 ** Candidate values for Wal.exclusiveMode.
45940 */
45941 #define WAL_NORMAL_MODE     0
45942 #define WAL_EXCLUSIVE_MODE  1     
45943 #define WAL_HEAPMEMORY_MODE 2
45944
45945 /*
45946 ** Possible values for WAL.readOnly
45947 */
45948 #define WAL_RDWR        0    /* Normal read/write connection */
45949 #define WAL_RDONLY      1    /* The WAL file is readonly */
45950 #define WAL_SHM_RDONLY  2    /* The SHM file is readonly */
45951
45952 /*
45953 ** Each page of the wal-index mapping contains a hash-table made up of
45954 ** an array of HASHTABLE_NSLOT elements of the following type.
45955 */
45956 typedef u16 ht_slot;
45957
45958 /*
45959 ** This structure is used to implement an iterator that loops through
45960 ** all frames in the WAL in database page order. Where two or more frames
45961 ** correspond to the same database page, the iterator visits only the 
45962 ** frame most recently written to the WAL (in other words, the frame with
45963 ** the largest index).
45964 **
45965 ** The internals of this structure are only accessed by:
45966 **
45967 **   walIteratorInit() - Create a new iterator,
45968 **   walIteratorNext() - Step an iterator,
45969 **   walIteratorFree() - Free an iterator.
45970 **
45971 ** This functionality is used by the checkpoint code (see walCheckpoint()).
45972 */
45973 struct WalIterator {
45974   int iPrior;                     /* Last result returned from the iterator */
45975   int nSegment;                   /* Number of entries in aSegment[] */
45976   struct WalSegment {
45977     int iNext;                    /* Next slot in aIndex[] not yet returned */
45978     ht_slot *aIndex;              /* i0, i1, i2... such that aPgno[iN] ascend */
45979     u32 *aPgno;                   /* Array of page numbers. */
45980     int nEntry;                   /* Nr. of entries in aPgno[] and aIndex[] */
45981     int iZero;                    /* Frame number associated with aPgno[0] */
45982   } aSegment[1];                  /* One for every 32KB page in the wal-index */
45983 };
45984
45985 /*
45986 ** Define the parameters of the hash tables in the wal-index file. There
45987 ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
45988 ** wal-index.
45989 **
45990 ** Changing any of these constants will alter the wal-index format and
45991 ** create incompatibilities.
45992 */
45993 #define HASHTABLE_NPAGE      4096                 /* Must be power of 2 */
45994 #define HASHTABLE_HASH_1     383                  /* Should be prime */
45995 #define HASHTABLE_NSLOT      (HASHTABLE_NPAGE*2)  /* Must be a power of 2 */
45996
45997 /* 
45998 ** The block of page numbers associated with the first hash-table in a
45999 ** wal-index is smaller than usual. This is so that there is a complete
46000 ** hash-table on each aligned 32KB page of the wal-index.
46001 */
46002 #define HASHTABLE_NPAGE_ONE  (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
46003
46004 /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
46005 #define WALINDEX_PGSZ   (                                         \
46006     sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
46007 )
46008
46009 /*
46010 ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
46011 ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
46012 ** numbered from zero.
46013 **
46014 ** If this call is successful, *ppPage is set to point to the wal-index
46015 ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
46016 ** then an SQLite error code is returned and *ppPage is set to 0.
46017 */
46018 static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
46019   int rc = SQLITE_OK;
46020
46021   /* Enlarge the pWal->apWiData[] array if required */
46022   if( pWal->nWiData<=iPage ){
46023     int nByte = sizeof(u32*)*(iPage+1);
46024     volatile u32 **apNew;
46025     apNew = (volatile u32 **)sqlite3_realloc((void *)pWal->apWiData, nByte);
46026     if( !apNew ){
46027       *ppPage = 0;
46028       return SQLITE_NOMEM;
46029     }
46030     memset((void*)&apNew[pWal->nWiData], 0,
46031            sizeof(u32*)*(iPage+1-pWal->nWiData));
46032     pWal->apWiData = apNew;
46033     pWal->nWiData = iPage+1;
46034   }
46035
46036   /* Request a pointer to the required page from the VFS */
46037   if( pWal->apWiData[iPage]==0 ){
46038     if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
46039       pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
46040       if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;
46041     }else{
46042       rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ, 
46043           pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
46044       );
46045       if( rc==SQLITE_READONLY ){
46046         pWal->readOnly |= WAL_SHM_RDONLY;
46047         rc = SQLITE_OK;
46048       }
46049     }
46050   }
46051
46052   *ppPage = pWal->apWiData[iPage];
46053   assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
46054   return rc;
46055 }
46056
46057 /*
46058 ** Return a pointer to the WalCkptInfo structure in the wal-index.
46059 */
46060 static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
46061   assert( pWal->nWiData>0 && pWal->apWiData[0] );
46062   return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
46063 }
46064
46065 /*
46066 ** Return a pointer to the WalIndexHdr structure in the wal-index.
46067 */
46068 static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
46069   assert( pWal->nWiData>0 && pWal->apWiData[0] );
46070   return (volatile WalIndexHdr*)pWal->apWiData[0];
46071 }
46072
46073 /*
46074 ** The argument to this macro must be of type u32. On a little-endian
46075 ** architecture, it returns the u32 value that results from interpreting
46076 ** the 4 bytes as a big-endian value. On a big-endian architecture, it
46077 ** returns the value that would be produced by intepreting the 4 bytes
46078 ** of the input value as a little-endian integer.
46079 */
46080 #define BYTESWAP32(x) ( \
46081     (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8)  \
46082   + (((x)&0x00FF0000)>>8)  + (((x)&0xFF000000)>>24) \
46083 )
46084
46085 /*
46086 ** Generate or extend an 8 byte checksum based on the data in 
46087 ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
46088 ** initial values of 0 and 0 if aIn==NULL).
46089 **
46090 ** The checksum is written back into aOut[] before returning.
46091 **
46092 ** nByte must be a positive multiple of 8.
46093 */
46094 static void walChecksumBytes(
46095   int nativeCksum, /* True for native byte-order, false for non-native */
46096   u8 *a,           /* Content to be checksummed */
46097   int nByte,       /* Bytes of content in a[].  Must be a multiple of 8. */
46098   const u32 *aIn,  /* Initial checksum value input */
46099   u32 *aOut        /* OUT: Final checksum value output */
46100 ){
46101   u32 s1, s2;
46102   u32 *aData = (u32 *)a;
46103   u32 *aEnd = (u32 *)&a[nByte];
46104
46105   if( aIn ){
46106     s1 = aIn[0];
46107     s2 = aIn[1];
46108   }else{
46109     s1 = s2 = 0;
46110   }
46111
46112   assert( nByte>=8 );
46113   assert( (nByte&0x00000007)==0 );
46114
46115   if( nativeCksum ){
46116     do {
46117       s1 += *aData++ + s2;
46118       s2 += *aData++ + s1;
46119     }while( aData<aEnd );
46120   }else{
46121     do {
46122       s1 += BYTESWAP32(aData[0]) + s2;
46123       s2 += BYTESWAP32(aData[1]) + s1;
46124       aData += 2;
46125     }while( aData<aEnd );
46126   }
46127
46128   aOut[0] = s1;
46129   aOut[1] = s2;
46130 }
46131
46132 static void walShmBarrier(Wal *pWal){
46133   if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
46134     sqlite3OsShmBarrier(pWal->pDbFd);
46135   }
46136 }
46137
46138 /*
46139 ** Write the header information in pWal->hdr into the wal-index.
46140 **
46141 ** The checksum on pWal->hdr is updated before it is written.
46142 */
46143 static void walIndexWriteHdr(Wal *pWal){
46144   volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
46145   const int nCksum = offsetof(WalIndexHdr, aCksum);
46146
46147   assert( pWal->writeLock );
46148   pWal->hdr.isInit = 1;
46149   pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
46150   walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
46151   memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
46152   walShmBarrier(pWal);
46153   memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
46154 }
46155
46156 /*
46157 ** This function encodes a single frame header and writes it to a buffer
46158 ** supplied by the caller. A frame-header is made up of a series of 
46159 ** 4-byte big-endian integers, as follows:
46160 **
46161 **     0: Page number.
46162 **     4: For commit records, the size of the database image in pages 
46163 **        after the commit. For all other records, zero.
46164 **     8: Salt-1 (copied from the wal-header)
46165 **    12: Salt-2 (copied from the wal-header)
46166 **    16: Checksum-1.
46167 **    20: Checksum-2.
46168 */
46169 static void walEncodeFrame(
46170   Wal *pWal,                      /* The write-ahead log */
46171   u32 iPage,                      /* Database page number for frame */
46172   u32 nTruncate,                  /* New db size (or 0 for non-commit frames) */
46173   u8 *aData,                      /* Pointer to page data */
46174   u8 *aFrame                      /* OUT: Write encoded frame here */
46175 ){
46176   int nativeCksum;                /* True for native byte-order checksums */
46177   u32 *aCksum = pWal->hdr.aFrameCksum;
46178   assert( WAL_FRAME_HDRSIZE==24 );
46179   sqlite3Put4byte(&aFrame[0], iPage);
46180   sqlite3Put4byte(&aFrame[4], nTruncate);
46181   memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
46182
46183   nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
46184   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
46185   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
46186
46187   sqlite3Put4byte(&aFrame[16], aCksum[0]);
46188   sqlite3Put4byte(&aFrame[20], aCksum[1]);
46189 }
46190
46191 /*
46192 ** Check to see if the frame with header in aFrame[] and content
46193 ** in aData[] is valid.  If it is a valid frame, fill *piPage and
46194 ** *pnTruncate and return true.  Return if the frame is not valid.
46195 */
46196 static int walDecodeFrame(
46197   Wal *pWal,                      /* The write-ahead log */
46198   u32 *piPage,                    /* OUT: Database page number for frame */
46199   u32 *pnTruncate,                /* OUT: New db size (or 0 if not commit) */
46200   u8 *aData,                      /* Pointer to page data (for checksum) */
46201   u8 *aFrame                      /* Frame data */
46202 ){
46203   int nativeCksum;                /* True for native byte-order checksums */
46204   u32 *aCksum = pWal->hdr.aFrameCksum;
46205   u32 pgno;                       /* Page number of the frame */
46206   assert( WAL_FRAME_HDRSIZE==24 );
46207
46208   /* A frame is only valid if the salt values in the frame-header
46209   ** match the salt values in the wal-header. 
46210   */
46211   if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
46212     return 0;
46213   }
46214
46215   /* A frame is only valid if the page number is creater than zero.
46216   */
46217   pgno = sqlite3Get4byte(&aFrame[0]);
46218   if( pgno==0 ){
46219     return 0;
46220   }
46221
46222   /* A frame is only valid if a checksum of the WAL header,
46223   ** all prior frams, the first 16 bytes of this frame-header, 
46224   ** and the frame-data matches the checksum in the last 8 
46225   ** bytes of this frame-header.
46226   */
46227   nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
46228   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
46229   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
46230   if( aCksum[0]!=sqlite3Get4byte(&aFrame[16]) 
46231    || aCksum[1]!=sqlite3Get4byte(&aFrame[20]) 
46232   ){
46233     /* Checksum failed. */
46234     return 0;
46235   }
46236
46237   /* If we reach this point, the frame is valid.  Return the page number
46238   ** and the new database size.
46239   */
46240   *piPage = pgno;
46241   *pnTruncate = sqlite3Get4byte(&aFrame[4]);
46242   return 1;
46243 }
46244
46245
46246 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
46247 /*
46248 ** Names of locks.  This routine is used to provide debugging output and is not
46249 ** a part of an ordinary build.
46250 */
46251 static const char *walLockName(int lockIdx){
46252   if( lockIdx==WAL_WRITE_LOCK ){
46253     return "WRITE-LOCK";
46254   }else if( lockIdx==WAL_CKPT_LOCK ){
46255     return "CKPT-LOCK";
46256   }else if( lockIdx==WAL_RECOVER_LOCK ){
46257     return "RECOVER-LOCK";
46258   }else{
46259     static char zName[15];
46260     sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
46261                      lockIdx-WAL_READ_LOCK(0));
46262     return zName;
46263   }
46264 }
46265 #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
46266     
46267
46268 /*
46269 ** Set or release locks on the WAL.  Locks are either shared or exclusive.
46270 ** A lock cannot be moved directly between shared and exclusive - it must go
46271 ** through the unlocked state first.
46272 **
46273 ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
46274 */
46275 static int walLockShared(Wal *pWal, int lockIdx){
46276   int rc;
46277   if( pWal->exclusiveMode ) return SQLITE_OK;
46278   rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
46279                         SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
46280   WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
46281             walLockName(lockIdx), rc ? "failed" : "ok"));
46282   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
46283   return rc;
46284 }
46285 static void walUnlockShared(Wal *pWal, int lockIdx){
46286   if( pWal->exclusiveMode ) return;
46287   (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
46288                          SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
46289   WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
46290 }
46291 static int walLockExclusive(Wal *pWal, int lockIdx, int n){
46292   int rc;
46293   if( pWal->exclusiveMode ) return SQLITE_OK;
46294   rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
46295                         SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
46296   WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
46297             walLockName(lockIdx), n, rc ? "failed" : "ok"));
46298   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
46299   return rc;
46300 }
46301 static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
46302   if( pWal->exclusiveMode ) return;
46303   (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
46304                          SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
46305   WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
46306              walLockName(lockIdx), n));
46307 }
46308
46309 /*
46310 ** Compute a hash on a page number.  The resulting hash value must land
46311 ** between 0 and (HASHTABLE_NSLOT-1).  The walHashNext() function advances
46312 ** the hash to the next value in the event of a collision.
46313 */
46314 static int walHash(u32 iPage){
46315   assert( iPage>0 );
46316   assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
46317   return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
46318 }
46319 static int walNextHash(int iPriorHash){
46320   return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
46321 }
46322
46323 /* 
46324 ** Return pointers to the hash table and page number array stored on
46325 ** page iHash of the wal-index. The wal-index is broken into 32KB pages
46326 ** numbered starting from 0.
46327 **
46328 ** Set output variable *paHash to point to the start of the hash table
46329 ** in the wal-index file. Set *piZero to one less than the frame 
46330 ** number of the first frame indexed by this hash table. If a
46331 ** slot in the hash table is set to N, it refers to frame number 
46332 ** (*piZero+N) in the log.
46333 **
46334 ** Finally, set *paPgno so that *paPgno[1] is the page number of the
46335 ** first frame indexed by the hash table, frame (*piZero+1).
46336 */
46337 static int walHashGet(
46338   Wal *pWal,                      /* WAL handle */
46339   int iHash,                      /* Find the iHash'th table */
46340   volatile ht_slot **paHash,      /* OUT: Pointer to hash index */
46341   volatile u32 **paPgno,          /* OUT: Pointer to page number array */
46342   u32 *piZero                     /* OUT: Frame associated with *paPgno[0] */
46343 ){
46344   int rc;                         /* Return code */
46345   volatile u32 *aPgno;
46346
46347   rc = walIndexPage(pWal, iHash, &aPgno);
46348   assert( rc==SQLITE_OK || iHash>0 );
46349
46350   if( rc==SQLITE_OK ){
46351     u32 iZero;
46352     volatile ht_slot *aHash;
46353
46354     aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
46355     if( iHash==0 ){
46356       aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
46357       iZero = 0;
46358     }else{
46359       iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
46360     }
46361   
46362     *paPgno = &aPgno[-1];
46363     *paHash = aHash;
46364     *piZero = iZero;
46365   }
46366   return rc;
46367 }
46368
46369 /*
46370 ** Return the number of the wal-index page that contains the hash-table
46371 ** and page-number array that contain entries corresponding to WAL frame
46372 ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages 
46373 ** are numbered starting from 0.
46374 */
46375 static int walFramePage(u32 iFrame){
46376   int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
46377   assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
46378        && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
46379        && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
46380        && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
46381        && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
46382   );
46383   return iHash;
46384 }
46385
46386 /*
46387 ** Return the page number associated with frame iFrame in this WAL.
46388 */
46389 static u32 walFramePgno(Wal *pWal, u32 iFrame){
46390   int iHash = walFramePage(iFrame);
46391   if( iHash==0 ){
46392     return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
46393   }
46394   return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
46395 }
46396
46397 /*
46398 ** Remove entries from the hash table that point to WAL slots greater
46399 ** than pWal->hdr.mxFrame.
46400 **
46401 ** This function is called whenever pWal->hdr.mxFrame is decreased due
46402 ** to a rollback or savepoint.
46403 **
46404 ** At most only the hash table containing pWal->hdr.mxFrame needs to be
46405 ** updated.  Any later hash tables will be automatically cleared when
46406 ** pWal->hdr.mxFrame advances to the point where those hash tables are
46407 ** actually needed.
46408 */
46409 static void walCleanupHash(Wal *pWal){
46410   volatile ht_slot *aHash = 0;    /* Pointer to hash table to clear */
46411   volatile u32 *aPgno = 0;        /* Page number array for hash table */
46412   u32 iZero = 0;                  /* frame == (aHash[x]+iZero) */
46413   int iLimit = 0;                 /* Zero values greater than this */
46414   int nByte;                      /* Number of bytes to zero in aPgno[] */
46415   int i;                          /* Used to iterate through aHash[] */
46416
46417   assert( pWal->writeLock );
46418   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
46419   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
46420   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
46421
46422   if( pWal->hdr.mxFrame==0 ) return;
46423
46424   /* Obtain pointers to the hash-table and page-number array containing 
46425   ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
46426   ** that the page said hash-table and array reside on is already mapped.
46427   */
46428   assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
46429   assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
46430   walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
46431
46432   /* Zero all hash-table entries that correspond to frame numbers greater
46433   ** than pWal->hdr.mxFrame.
46434   */
46435   iLimit = pWal->hdr.mxFrame - iZero;
46436   assert( iLimit>0 );
46437   for(i=0; i<HASHTABLE_NSLOT; i++){
46438     if( aHash[i]>iLimit ){
46439       aHash[i] = 0;
46440     }
46441   }
46442   
46443   /* Zero the entries in the aPgno array that correspond to frames with
46444   ** frame numbers greater than pWal->hdr.mxFrame. 
46445   */
46446   nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
46447   memset((void *)&aPgno[iLimit+1], 0, nByte);
46448
46449 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
46450   /* Verify that the every entry in the mapping region is still reachable
46451   ** via the hash table even after the cleanup.
46452   */
46453   if( iLimit ){
46454     int i;           /* Loop counter */
46455     int iKey;        /* Hash key */
46456     for(i=1; i<=iLimit; i++){
46457       for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
46458         if( aHash[iKey]==i ) break;
46459       }
46460       assert( aHash[iKey]==i );
46461     }
46462   }
46463 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
46464 }
46465
46466
46467 /*
46468 ** Set an entry in the wal-index that will map database page number
46469 ** pPage into WAL frame iFrame.
46470 */
46471 static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
46472   int rc;                         /* Return code */
46473   u32 iZero = 0;                  /* One less than frame number of aPgno[1] */
46474   volatile u32 *aPgno = 0;        /* Page number array */
46475   volatile ht_slot *aHash = 0;    /* Hash table */
46476
46477   rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
46478
46479   /* Assuming the wal-index file was successfully mapped, populate the
46480   ** page number array and hash table entry.
46481   */
46482   if( rc==SQLITE_OK ){
46483     int iKey;                     /* Hash table key */
46484     int idx;                      /* Value to write to hash-table slot */
46485     int nCollide;                 /* Number of hash collisions */
46486
46487     idx = iFrame - iZero;
46488     assert( idx <= HASHTABLE_NSLOT/2 + 1 );
46489     
46490     /* If this is the first entry to be added to this hash-table, zero the
46491     ** entire hash table and aPgno[] array before proceding. 
46492     */
46493     if( idx==1 ){
46494       int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
46495       memset((void*)&aPgno[1], 0, nByte);
46496     }
46497
46498     /* If the entry in aPgno[] is already set, then the previous writer
46499     ** must have exited unexpectedly in the middle of a transaction (after
46500     ** writing one or more dirty pages to the WAL to free up memory). 
46501     ** Remove the remnants of that writers uncommitted transaction from 
46502     ** the hash-table before writing any new entries.
46503     */
46504     if( aPgno[idx] ){
46505       walCleanupHash(pWal);
46506       assert( !aPgno[idx] );
46507     }
46508
46509     /* Write the aPgno[] array entry and the hash-table slot. */
46510     nCollide = idx;
46511     for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
46512       if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
46513     }
46514     aPgno[idx] = iPage;
46515     aHash[iKey] = (ht_slot)idx;
46516
46517 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
46518     /* Verify that the number of entries in the hash table exactly equals
46519     ** the number of entries in the mapping region.
46520     */
46521     {
46522       int i;           /* Loop counter */
46523       int nEntry = 0;  /* Number of entries in the hash table */
46524       for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
46525       assert( nEntry==idx );
46526     }
46527
46528     /* Verify that the every entry in the mapping region is reachable
46529     ** via the hash table.  This turns out to be a really, really expensive
46530     ** thing to check, so only do this occasionally - not on every
46531     ** iteration.
46532     */
46533     if( (idx&0x3ff)==0 ){
46534       int i;           /* Loop counter */
46535       for(i=1; i<=idx; i++){
46536         for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
46537           if( aHash[iKey]==i ) break;
46538         }
46539         assert( aHash[iKey]==i );
46540       }
46541     }
46542 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
46543   }
46544
46545
46546   return rc;
46547 }
46548
46549
46550 /*
46551 ** Recover the wal-index by reading the write-ahead log file. 
46552 **
46553 ** This routine first tries to establish an exclusive lock on the
46554 ** wal-index to prevent other threads/processes from doing anything
46555 ** with the WAL or wal-index while recovery is running.  The
46556 ** WAL_RECOVER_LOCK is also held so that other threads will know
46557 ** that this thread is running recovery.  If unable to establish
46558 ** the necessary locks, this routine returns SQLITE_BUSY.
46559 */
46560 static int walIndexRecover(Wal *pWal){
46561   int rc;                         /* Return Code */
46562   i64 nSize;                      /* Size of log file */
46563   u32 aFrameCksum[2] = {0, 0};
46564   int iLock;                      /* Lock offset to lock for checkpoint */
46565   int nLock;                      /* Number of locks to hold */
46566
46567   /* Obtain an exclusive lock on all byte in the locking range not already
46568   ** locked by the caller. The caller is guaranteed to have locked the
46569   ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
46570   ** If successful, the same bytes that are locked here are unlocked before
46571   ** this function returns.
46572   */
46573   assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
46574   assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
46575   assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
46576   assert( pWal->writeLock );
46577   iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
46578   nLock = SQLITE_SHM_NLOCK - iLock;
46579   rc = walLockExclusive(pWal, iLock, nLock);
46580   if( rc ){
46581     return rc;
46582   }
46583   WALTRACE(("WAL%p: recovery begin...\n", pWal));
46584
46585   memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
46586
46587   rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
46588   if( rc!=SQLITE_OK ){
46589     goto recovery_error;
46590   }
46591
46592   if( nSize>WAL_HDRSIZE ){
46593     u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */
46594     u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */
46595     int szFrame;                  /* Number of bytes in buffer aFrame[] */
46596     u8 *aData;                    /* Pointer to data part of aFrame buffer */
46597     int iFrame;                   /* Index of last frame read */
46598     i64 iOffset;                  /* Next offset to read from log file */
46599     int szPage;                   /* Page size according to the log */
46600     u32 magic;                    /* Magic value read from WAL header */
46601     u32 version;                  /* Magic value read from WAL header */
46602     int isValid;                  /* True if this frame is valid */
46603
46604     /* Read in the WAL header. */
46605     rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
46606     if( rc!=SQLITE_OK ){
46607       goto recovery_error;
46608     }
46609
46610     /* If the database page size is not a power of two, or is greater than
46611     ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid 
46612     ** data. Similarly, if the 'magic' value is invalid, ignore the whole
46613     ** WAL file.
46614     */
46615     magic = sqlite3Get4byte(&aBuf[0]);
46616     szPage = sqlite3Get4byte(&aBuf[8]);
46617     if( (magic&0xFFFFFFFE)!=WAL_MAGIC 
46618      || szPage&(szPage-1) 
46619      || szPage>SQLITE_MAX_PAGE_SIZE 
46620      || szPage<512 
46621     ){
46622       goto finished;
46623     }
46624     pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
46625     pWal->szPage = szPage;
46626     pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
46627     memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
46628
46629     /* Verify that the WAL header checksum is correct */
46630     walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN, 
46631         aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
46632     );
46633     if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
46634      || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
46635     ){
46636       goto finished;
46637     }
46638
46639     /* Verify that the version number on the WAL format is one that
46640     ** are able to understand */
46641     version = sqlite3Get4byte(&aBuf[4]);
46642     if( version!=WAL_MAX_VERSION ){
46643       rc = SQLITE_CANTOPEN_BKPT;
46644       goto finished;
46645     }
46646
46647     /* Malloc a buffer to read frames into. */
46648     szFrame = szPage + WAL_FRAME_HDRSIZE;
46649     aFrame = (u8 *)sqlite3_malloc(szFrame);
46650     if( !aFrame ){
46651       rc = SQLITE_NOMEM;
46652       goto recovery_error;
46653     }
46654     aData = &aFrame[WAL_FRAME_HDRSIZE];
46655
46656     /* Read all frames from the log file. */
46657     iFrame = 0;
46658     for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
46659       u32 pgno;                   /* Database page number for frame */
46660       u32 nTruncate;              /* dbsize field from frame header */
46661
46662       /* Read and decode the next log frame. */
46663       iFrame++;
46664       rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
46665       if( rc!=SQLITE_OK ) break;
46666       isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
46667       if( !isValid ) break;
46668       rc = walIndexAppend(pWal, iFrame, pgno);
46669       if( rc!=SQLITE_OK ) break;
46670
46671       /* If nTruncate is non-zero, this is a commit record. */
46672       if( nTruncate ){
46673         pWal->hdr.mxFrame = iFrame;
46674         pWal->hdr.nPage = nTruncate;
46675         pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
46676         testcase( szPage<=32768 );
46677         testcase( szPage>=65536 );
46678         aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
46679         aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
46680       }
46681     }
46682
46683     sqlite3_free(aFrame);
46684   }
46685
46686 finished:
46687   if( rc==SQLITE_OK ){
46688     volatile WalCkptInfo *pInfo;
46689     int i;
46690     pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
46691     pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
46692     walIndexWriteHdr(pWal);
46693
46694     /* Reset the checkpoint-header. This is safe because this thread is 
46695     ** currently holding locks that exclude all other readers, writers and
46696     ** checkpointers.
46697     */
46698     pInfo = walCkptInfo(pWal);
46699     pInfo->nBackfill = 0;
46700     pInfo->aReadMark[0] = 0;
46701     for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
46702     if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
46703
46704     /* If more than one frame was recovered from the log file, report an
46705     ** event via sqlite3_log(). This is to help with identifying performance
46706     ** problems caused by applications routinely shutting down without
46707     ** checkpointing the log file.
46708     */
46709     if( pWal->hdr.nPage ){
46710       sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
46711           "recovered %d frames from WAL file %s",
46712           pWal->hdr.mxFrame, pWal->zWalName
46713       );
46714     }
46715   }
46716
46717 recovery_error:
46718   WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
46719   walUnlockExclusive(pWal, iLock, nLock);
46720   return rc;
46721 }
46722
46723 /*
46724 ** Close an open wal-index.
46725 */
46726 static void walIndexClose(Wal *pWal, int isDelete){
46727   if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
46728     int i;
46729     for(i=0; i<pWal->nWiData; i++){
46730       sqlite3_free((void *)pWal->apWiData[i]);
46731       pWal->apWiData[i] = 0;
46732     }
46733   }else{
46734     sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
46735   }
46736 }
46737
46738 /* 
46739 ** Open a connection to the WAL file zWalName. The database file must 
46740 ** already be opened on connection pDbFd. The buffer that zWalName points
46741 ** to must remain valid for the lifetime of the returned Wal* handle.
46742 **
46743 ** A SHARED lock should be held on the database file when this function
46744 ** is called. The purpose of this SHARED lock is to prevent any other
46745 ** client from unlinking the WAL or wal-index file. If another process
46746 ** were to do this just after this client opened one of these files, the
46747 ** system would be badly broken.
46748 **
46749 ** If the log file is successfully opened, SQLITE_OK is returned and 
46750 ** *ppWal is set to point to a new WAL handle. If an error occurs,
46751 ** an SQLite error code is returned and *ppWal is left unmodified.
46752 */
46753 SQLITE_PRIVATE int sqlite3WalOpen(
46754   sqlite3_vfs *pVfs,              /* vfs module to open wal and wal-index */
46755   sqlite3_file *pDbFd,            /* The open database file */
46756   const char *zWalName,           /* Name of the WAL file */
46757   int bNoShm,                     /* True to run in heap-memory mode */
46758   i64 mxWalSize,                  /* Truncate WAL to this size on reset */
46759   Wal **ppWal                     /* OUT: Allocated Wal handle */
46760 ){
46761   int rc;                         /* Return Code */
46762   Wal *pRet;                      /* Object to allocate and return */
46763   int flags;                      /* Flags passed to OsOpen() */
46764
46765   assert( zWalName && zWalName[0] );
46766   assert( pDbFd );
46767
46768   /* In the amalgamation, the os_unix.c and os_win.c source files come before
46769   ** this source file.  Verify that the #defines of the locking byte offsets
46770   ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
46771   */
46772 #ifdef WIN_SHM_BASE
46773   assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
46774 #endif
46775 #ifdef UNIX_SHM_BASE
46776   assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
46777 #endif
46778
46779
46780   /* Allocate an instance of struct Wal to return. */
46781   *ppWal = 0;
46782   pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
46783   if( !pRet ){
46784     return SQLITE_NOMEM;
46785   }
46786
46787   pRet->pVfs = pVfs;
46788   pRet->pWalFd = (sqlite3_file *)&pRet[1];
46789   pRet->pDbFd = pDbFd;
46790   pRet->readLock = -1;
46791   pRet->mxWalSize = mxWalSize;
46792   pRet->zWalName = zWalName;
46793   pRet->syncHeader = 1;
46794   pRet->padToSectorBoundary = 1;
46795   pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
46796
46797   /* Open file handle on the write-ahead log file. */
46798   flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
46799   rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
46800   if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
46801     pRet->readOnly = WAL_RDONLY;
46802   }
46803
46804   if( rc!=SQLITE_OK ){
46805     walIndexClose(pRet, 0);
46806     sqlite3OsClose(pRet->pWalFd);
46807     sqlite3_free(pRet);
46808   }else{
46809     int iDC = sqlite3OsDeviceCharacteristics(pRet->pWalFd);
46810     if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
46811     if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
46812       pRet->padToSectorBoundary = 0;
46813     }
46814     *ppWal = pRet;
46815     WALTRACE(("WAL%d: opened\n", pRet));
46816   }
46817   return rc;
46818 }
46819
46820 /*
46821 ** Change the size to which the WAL file is trucated on each reset.
46822 */
46823 SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
46824   if( pWal ) pWal->mxWalSize = iLimit;
46825 }
46826
46827 /*
46828 ** Find the smallest page number out of all pages held in the WAL that
46829 ** has not been returned by any prior invocation of this method on the
46830 ** same WalIterator object.   Write into *piFrame the frame index where
46831 ** that page was last written into the WAL.  Write into *piPage the page
46832 ** number.
46833 **
46834 ** Return 0 on success.  If there are no pages in the WAL with a page
46835 ** number larger than *piPage, then return 1.
46836 */
46837 static int walIteratorNext(
46838   WalIterator *p,               /* Iterator */
46839   u32 *piPage,                  /* OUT: The page number of the next page */
46840   u32 *piFrame                  /* OUT: Wal frame index of next page */
46841 ){
46842   u32 iMin;                     /* Result pgno must be greater than iMin */
46843   u32 iRet = 0xFFFFFFFF;        /* 0xffffffff is never a valid page number */
46844   int i;                        /* For looping through segments */
46845
46846   iMin = p->iPrior;
46847   assert( iMin<0xffffffff );
46848   for(i=p->nSegment-1; i>=0; i--){
46849     struct WalSegment *pSegment = &p->aSegment[i];
46850     while( pSegment->iNext<pSegment->nEntry ){
46851       u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
46852       if( iPg>iMin ){
46853         if( iPg<iRet ){
46854           iRet = iPg;
46855           *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
46856         }
46857         break;
46858       }
46859       pSegment->iNext++;
46860     }
46861   }
46862
46863   *piPage = p->iPrior = iRet;
46864   return (iRet==0xFFFFFFFF);
46865 }
46866
46867 /*
46868 ** This function merges two sorted lists into a single sorted list.
46869 **
46870 ** aLeft[] and aRight[] are arrays of indices.  The sort key is
46871 ** aContent[aLeft[]] and aContent[aRight[]].  Upon entry, the following
46872 ** is guaranteed for all J<K:
46873 **
46874 **        aContent[aLeft[J]] < aContent[aLeft[K]]
46875 **        aContent[aRight[J]] < aContent[aRight[K]]
46876 **
46877 ** This routine overwrites aRight[] with a new (probably longer) sequence
46878 ** of indices such that the aRight[] contains every index that appears in
46879 ** either aLeft[] or the old aRight[] and such that the second condition
46880 ** above is still met.
46881 **
46882 ** The aContent[aLeft[X]] values will be unique for all X.  And the
46883 ** aContent[aRight[X]] values will be unique too.  But there might be
46884 ** one or more combinations of X and Y such that
46885 **
46886 **      aLeft[X]!=aRight[Y]  &&  aContent[aLeft[X]] == aContent[aRight[Y]]
46887 **
46888 ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
46889 */
46890 static void walMerge(
46891   const u32 *aContent,            /* Pages in wal - keys for the sort */
46892   ht_slot *aLeft,                 /* IN: Left hand input list */
46893   int nLeft,                      /* IN: Elements in array *paLeft */
46894   ht_slot **paRight,              /* IN/OUT: Right hand input list */
46895   int *pnRight,                   /* IN/OUT: Elements in *paRight */
46896   ht_slot *aTmp                   /* Temporary buffer */
46897 ){
46898   int iLeft = 0;                  /* Current index in aLeft */
46899   int iRight = 0;                 /* Current index in aRight */
46900   int iOut = 0;                   /* Current index in output buffer */
46901   int nRight = *pnRight;
46902   ht_slot *aRight = *paRight;
46903
46904   assert( nLeft>0 && nRight>0 );
46905   while( iRight<nRight || iLeft<nLeft ){
46906     ht_slot logpage;
46907     Pgno dbpage;
46908
46909     if( (iLeft<nLeft) 
46910      && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
46911     ){
46912       logpage = aLeft[iLeft++];
46913     }else{
46914       logpage = aRight[iRight++];
46915     }
46916     dbpage = aContent[logpage];
46917
46918     aTmp[iOut++] = logpage;
46919     if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
46920
46921     assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
46922     assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
46923   }
46924
46925   *paRight = aLeft;
46926   *pnRight = iOut;
46927   memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
46928 }
46929
46930 /*
46931 ** Sort the elements in list aList using aContent[] as the sort key.
46932 ** Remove elements with duplicate keys, preferring to keep the
46933 ** larger aList[] values.
46934 **
46935 ** The aList[] entries are indices into aContent[].  The values in
46936 ** aList[] are to be sorted so that for all J<K:
46937 **
46938 **      aContent[aList[J]] < aContent[aList[K]]
46939 **
46940 ** For any X and Y such that
46941 **
46942 **      aContent[aList[X]] == aContent[aList[Y]]
46943 **
46944 ** Keep the larger of the two values aList[X] and aList[Y] and discard
46945 ** the smaller.
46946 */
46947 static void walMergesort(
46948   const u32 *aContent,            /* Pages in wal */
46949   ht_slot *aBuffer,               /* Buffer of at least *pnList items to use */
46950   ht_slot *aList,                 /* IN/OUT: List to sort */
46951   int *pnList                     /* IN/OUT: Number of elements in aList[] */
46952 ){
46953   struct Sublist {
46954     int nList;                    /* Number of elements in aList */
46955     ht_slot *aList;               /* Pointer to sub-list content */
46956   };
46957
46958   const int nList = *pnList;      /* Size of input list */
46959   int nMerge = 0;                 /* Number of elements in list aMerge */
46960   ht_slot *aMerge = 0;            /* List to be merged */
46961   int iList;                      /* Index into input list */
46962   int iSub = 0;                   /* Index into aSub array */
46963   struct Sublist aSub[13];        /* Array of sub-lists */
46964
46965   memset(aSub, 0, sizeof(aSub));
46966   assert( nList<=HASHTABLE_NPAGE && nList>0 );
46967   assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
46968
46969   for(iList=0; iList<nList; iList++){
46970     nMerge = 1;
46971     aMerge = &aList[iList];
46972     for(iSub=0; iList & (1<<iSub); iSub++){
46973       struct Sublist *p = &aSub[iSub];
46974       assert( p->aList && p->nList<=(1<<iSub) );
46975       assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
46976       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
46977     }
46978     aSub[iSub].aList = aMerge;
46979     aSub[iSub].nList = nMerge;
46980   }
46981
46982   for(iSub++; iSub<ArraySize(aSub); iSub++){
46983     if( nList & (1<<iSub) ){
46984       struct Sublist *p = &aSub[iSub];
46985       assert( p->nList<=(1<<iSub) );
46986       assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
46987       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
46988     }
46989   }
46990   assert( aMerge==aList );
46991   *pnList = nMerge;
46992
46993 #ifdef SQLITE_DEBUG
46994   {
46995     int i;
46996     for(i=1; i<*pnList; i++){
46997       assert( aContent[aList[i]] > aContent[aList[i-1]] );
46998     }
46999   }
47000 #endif
47001 }
47002
47003 /* 
47004 ** Free an iterator allocated by walIteratorInit().
47005 */
47006 static void walIteratorFree(WalIterator *p){
47007   sqlite3ScratchFree(p);
47008 }
47009
47010 /*
47011 ** Construct a WalInterator object that can be used to loop over all 
47012 ** pages in the WAL in ascending order. The caller must hold the checkpoint
47013 ** lock.
47014 **
47015 ** On success, make *pp point to the newly allocated WalInterator object
47016 ** return SQLITE_OK. Otherwise, return an error code. If this routine
47017 ** returns an error, the value of *pp is undefined.
47018 **
47019 ** The calling routine should invoke walIteratorFree() to destroy the
47020 ** WalIterator object when it has finished with it.
47021 */
47022 static int walIteratorInit(Wal *pWal, WalIterator **pp){
47023   WalIterator *p;                 /* Return value */
47024   int nSegment;                   /* Number of segments to merge */
47025   u32 iLast;                      /* Last frame in log */
47026   int nByte;                      /* Number of bytes to allocate */
47027   int i;                          /* Iterator variable */
47028   ht_slot *aTmp;                  /* Temp space used by merge-sort */
47029   int rc = SQLITE_OK;             /* Return Code */
47030
47031   /* This routine only runs while holding the checkpoint lock. And
47032   ** it only runs if there is actually content in the log (mxFrame>0).
47033   */
47034   assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
47035   iLast = pWal->hdr.mxFrame;
47036
47037   /* Allocate space for the WalIterator object. */
47038   nSegment = walFramePage(iLast) + 1;
47039   nByte = sizeof(WalIterator) 
47040         + (nSegment-1)*sizeof(struct WalSegment)
47041         + iLast*sizeof(ht_slot);
47042   p = (WalIterator *)sqlite3ScratchMalloc(nByte);
47043   if( !p ){
47044     return SQLITE_NOMEM;
47045   }
47046   memset(p, 0, nByte);
47047   p->nSegment = nSegment;
47048
47049   /* Allocate temporary space used by the merge-sort routine. This block
47050   ** of memory will be freed before this function returns.
47051   */
47052   aTmp = (ht_slot *)sqlite3ScratchMalloc(
47053       sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
47054   );
47055   if( !aTmp ){
47056     rc = SQLITE_NOMEM;
47057   }
47058
47059   for(i=0; rc==SQLITE_OK && i<nSegment; i++){
47060     volatile ht_slot *aHash;
47061     u32 iZero;
47062     volatile u32 *aPgno;
47063
47064     rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
47065     if( rc==SQLITE_OK ){
47066       int j;                      /* Counter variable */
47067       int nEntry;                 /* Number of entries in this segment */
47068       ht_slot *aIndex;            /* Sorted index for this segment */
47069
47070       aPgno++;
47071       if( (i+1)==nSegment ){
47072         nEntry = (int)(iLast - iZero);
47073       }else{
47074         nEntry = (int)((u32*)aHash - (u32*)aPgno);
47075       }
47076       aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
47077       iZero++;
47078   
47079       for(j=0; j<nEntry; j++){
47080         aIndex[j] = (ht_slot)j;
47081       }
47082       walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
47083       p->aSegment[i].iZero = iZero;
47084       p->aSegment[i].nEntry = nEntry;
47085       p->aSegment[i].aIndex = aIndex;
47086       p->aSegment[i].aPgno = (u32 *)aPgno;
47087     }
47088   }
47089   sqlite3ScratchFree(aTmp);
47090
47091   if( rc!=SQLITE_OK ){
47092     walIteratorFree(p);
47093   }
47094   *pp = p;
47095   return rc;
47096 }
47097
47098 /*
47099 ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
47100 ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
47101 ** busy-handler function. Invoke it and retry the lock until either the
47102 ** lock is successfully obtained or the busy-handler returns 0.
47103 */
47104 static int walBusyLock(
47105   Wal *pWal,                      /* WAL connection */
47106   int (*xBusy)(void*),            /* Function to call when busy */
47107   void *pBusyArg,                 /* Context argument for xBusyHandler */
47108   int lockIdx,                    /* Offset of first byte to lock */
47109   int n                           /* Number of bytes to lock */
47110 ){
47111   int rc;
47112   do {
47113     rc = walLockExclusive(pWal, lockIdx, n);
47114   }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
47115   return rc;
47116 }
47117
47118 /*
47119 ** The cache of the wal-index header must be valid to call this function.
47120 ** Return the page-size in bytes used by the database.
47121 */
47122 static int walPagesize(Wal *pWal){
47123   return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
47124 }
47125
47126 /*
47127 ** Copy as much content as we can from the WAL back into the database file
47128 ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
47129 **
47130 ** The amount of information copies from WAL to database might be limited
47131 ** by active readers.  This routine will never overwrite a database page
47132 ** that a concurrent reader might be using.
47133 **
47134 ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
47135 ** SQLite is in WAL-mode in synchronous=NORMAL.  That means that if 
47136 ** checkpoints are always run by a background thread or background 
47137 ** process, foreground threads will never block on a lengthy fsync call.
47138 **
47139 ** Fsync is called on the WAL before writing content out of the WAL and
47140 ** into the database.  This ensures that if the new content is persistent
47141 ** in the WAL and can be recovered following a power-loss or hard reset.
47142 **
47143 ** Fsync is also called on the database file if (and only if) the entire
47144 ** WAL content is copied into the database file.  This second fsync makes
47145 ** it safe to delete the WAL since the new content will persist in the
47146 ** database file.
47147 **
47148 ** This routine uses and updates the nBackfill field of the wal-index header.
47149 ** This is the only routine tha will increase the value of nBackfill.  
47150 ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
47151 ** its value.)
47152 **
47153 ** The caller must be holding sufficient locks to ensure that no other
47154 ** checkpoint is running (in any other thread or process) at the same
47155 ** time.
47156 */
47157 static int walCheckpoint(
47158   Wal *pWal,                      /* Wal connection */
47159   int eMode,                      /* One of PASSIVE, FULL or RESTART */
47160   int (*xBusyCall)(void*),        /* Function to call when busy */
47161   void *pBusyArg,                 /* Context argument for xBusyHandler */
47162   int sync_flags,                 /* Flags for OsSync() (or 0) */
47163   u8 *zBuf                        /* Temporary buffer to use */
47164 ){
47165   int rc;                         /* Return code */
47166   int szPage;                     /* Database page-size */
47167   WalIterator *pIter = 0;         /* Wal iterator context */
47168   u32 iDbpage = 0;                /* Next database page to write */
47169   u32 iFrame = 0;                 /* Wal frame containing data for iDbpage */
47170   u32 mxSafeFrame;                /* Max frame that can be backfilled */
47171   u32 mxPage;                     /* Max database page to write */
47172   int i;                          /* Loop counter */
47173   volatile WalCkptInfo *pInfo;    /* The checkpoint status information */
47174   int (*xBusy)(void*) = 0;        /* Function to call when waiting for locks */
47175
47176   szPage = walPagesize(pWal);
47177   testcase( szPage<=32768 );
47178   testcase( szPage>=65536 );
47179   pInfo = walCkptInfo(pWal);
47180   if( pInfo->nBackfill>=pWal->hdr.mxFrame ) return SQLITE_OK;
47181
47182   /* Allocate the iterator */
47183   rc = walIteratorInit(pWal, &pIter);
47184   if( rc!=SQLITE_OK ){
47185     return rc;
47186   }
47187   assert( pIter );
47188
47189   if( eMode!=SQLITE_CHECKPOINT_PASSIVE ) xBusy = xBusyCall;
47190
47191   /* Compute in mxSafeFrame the index of the last frame of the WAL that is
47192   ** safe to write into the database.  Frames beyond mxSafeFrame might
47193   ** overwrite database pages that are in use by active readers and thus
47194   ** cannot be backfilled from the WAL.
47195   */
47196   mxSafeFrame = pWal->hdr.mxFrame;
47197   mxPage = pWal->hdr.nPage;
47198   for(i=1; i<WAL_NREADER; i++){
47199     u32 y = pInfo->aReadMark[i];
47200     if( mxSafeFrame>y ){
47201       assert( y<=pWal->hdr.mxFrame );
47202       rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
47203       if( rc==SQLITE_OK ){
47204         pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
47205         walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
47206       }else if( rc==SQLITE_BUSY ){
47207         mxSafeFrame = y;
47208         xBusy = 0;
47209       }else{
47210         goto walcheckpoint_out;
47211       }
47212     }
47213   }
47214
47215   if( pInfo->nBackfill<mxSafeFrame
47216    && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0), 1))==SQLITE_OK
47217   ){
47218     i64 nSize;                    /* Current size of database file */
47219     u32 nBackfill = pInfo->nBackfill;
47220
47221     /* Sync the WAL to disk */
47222     if( sync_flags ){
47223       rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
47224     }
47225
47226     /* If the database may grow as a result of this checkpoint, hint
47227     ** about the eventual size of the db file to the VFS layer.
47228     */
47229     if( rc==SQLITE_OK ){
47230       i64 nReq = ((i64)mxPage * szPage);
47231       rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
47232       if( rc==SQLITE_OK && nSize<nReq ){
47233         sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
47234       }
47235     }
47236
47237
47238     /* Iterate through the contents of the WAL, copying data to the db file. */
47239     while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
47240       i64 iOffset;
47241       assert( walFramePgno(pWal, iFrame)==iDbpage );
47242       if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ) continue;
47243       iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
47244       /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
47245       rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
47246       if( rc!=SQLITE_OK ) break;
47247       iOffset = (iDbpage-1)*(i64)szPage;
47248       testcase( IS_BIG_INT(iOffset) );
47249       rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
47250       if( rc!=SQLITE_OK ) break;
47251     }
47252
47253     /* If work was actually accomplished... */
47254     if( rc==SQLITE_OK ){
47255       if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
47256         i64 szDb = pWal->hdr.nPage*(i64)szPage;
47257         testcase( IS_BIG_INT(szDb) );
47258         rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
47259         if( rc==SQLITE_OK && sync_flags ){
47260           rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
47261         }
47262       }
47263       if( rc==SQLITE_OK ){
47264         pInfo->nBackfill = mxSafeFrame;
47265       }
47266     }
47267
47268     /* Release the reader lock held while backfilling */
47269     walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
47270   }
47271
47272   if( rc==SQLITE_BUSY ){
47273     /* Reset the return code so as not to report a checkpoint failure
47274     ** just because there are active readers.  */
47275     rc = SQLITE_OK;
47276   }
47277
47278   /* If this is an SQLITE_CHECKPOINT_RESTART operation, and the entire wal
47279   ** file has been copied into the database file, then block until all
47280   ** readers have finished using the wal file. This ensures that the next
47281   ** process to write to the database restarts the wal file.
47282   */
47283   if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
47284     assert( pWal->writeLock );
47285     if( pInfo->nBackfill<pWal->hdr.mxFrame ){
47286       rc = SQLITE_BUSY;
47287     }else if( eMode==SQLITE_CHECKPOINT_RESTART ){
47288       assert( mxSafeFrame==pWal->hdr.mxFrame );
47289       rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
47290       if( rc==SQLITE_OK ){
47291         walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
47292       }
47293     }
47294   }
47295
47296  walcheckpoint_out:
47297   walIteratorFree(pIter);
47298   return rc;
47299 }
47300
47301 /*
47302 ** If the WAL file is currently larger than nMax bytes in size, truncate
47303 ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
47304 */
47305 static void walLimitSize(Wal *pWal, i64 nMax){
47306   i64 sz;
47307   int rx;
47308   sqlite3BeginBenignMalloc();
47309   rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
47310   if( rx==SQLITE_OK && (sz > nMax ) ){
47311     rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
47312   }
47313   sqlite3EndBenignMalloc();
47314   if( rx ){
47315     sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
47316   }
47317 }
47318
47319 /*
47320 ** Close a connection to a log file.
47321 */
47322 SQLITE_PRIVATE int sqlite3WalClose(
47323   Wal *pWal,                      /* Wal to close */
47324   int sync_flags,                 /* Flags to pass to OsSync() (or 0) */
47325   int nBuf,
47326   u8 *zBuf                        /* Buffer of at least nBuf bytes */
47327 ){
47328   int rc = SQLITE_OK;
47329   if( pWal ){
47330     int isDelete = 0;             /* True to unlink wal and wal-index files */
47331
47332     /* If an EXCLUSIVE lock can be obtained on the database file (using the
47333     ** ordinary, rollback-mode locking methods, this guarantees that the
47334     ** connection associated with this log file is the only connection to
47335     ** the database. In this case checkpoint the database and unlink both
47336     ** the wal and wal-index files.
47337     **
47338     ** The EXCLUSIVE lock is not released before returning.
47339     */
47340     rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
47341     if( rc==SQLITE_OK ){
47342       if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
47343         pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
47344       }
47345       rc = sqlite3WalCheckpoint(
47346           pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
47347       );
47348       if( rc==SQLITE_OK ){
47349         int bPersist = -1;
47350         sqlite3OsFileControlHint(
47351             pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
47352         );
47353         if( bPersist!=1 ){
47354           /* Try to delete the WAL file if the checkpoint completed and
47355           ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
47356           ** mode (!bPersist) */
47357           isDelete = 1;
47358         }else if( pWal->mxWalSize>=0 ){
47359           /* Try to truncate the WAL file to zero bytes if the checkpoint
47360           ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
47361           ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
47362           ** non-negative value (pWal->mxWalSize>=0).  Note that we truncate
47363           ** to zero bytes as truncating to the journal_size_limit might
47364           ** leave a corrupt WAL file on disk. */
47365           walLimitSize(pWal, 0);
47366         }
47367       }
47368     }
47369
47370     walIndexClose(pWal, isDelete);
47371     sqlite3OsClose(pWal->pWalFd);
47372     if( isDelete ){
47373       sqlite3BeginBenignMalloc();
47374       sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
47375       sqlite3EndBenignMalloc();
47376     }
47377     WALTRACE(("WAL%p: closed\n", pWal));
47378     sqlite3_free((void *)pWal->apWiData);
47379     sqlite3_free(pWal);
47380   }
47381   return rc;
47382 }
47383
47384 /*
47385 ** Try to read the wal-index header.  Return 0 on success and 1 if
47386 ** there is a problem.
47387 **
47388 ** The wal-index is in shared memory.  Another thread or process might
47389 ** be writing the header at the same time this procedure is trying to
47390 ** read it, which might result in inconsistency.  A dirty read is detected
47391 ** by verifying that both copies of the header are the same and also by
47392 ** a checksum on the header.
47393 **
47394 ** If and only if the read is consistent and the header is different from
47395 ** pWal->hdr, then pWal->hdr is updated to the content of the new header
47396 ** and *pChanged is set to 1.
47397 **
47398 ** If the checksum cannot be verified return non-zero. If the header
47399 ** is read successfully and the checksum verified, return zero.
47400 */
47401 static int walIndexTryHdr(Wal *pWal, int *pChanged){
47402   u32 aCksum[2];                  /* Checksum on the header content */
47403   WalIndexHdr h1, h2;             /* Two copies of the header content */
47404   WalIndexHdr volatile *aHdr;     /* Header in shared memory */
47405
47406   /* The first page of the wal-index must be mapped at this point. */
47407   assert( pWal->nWiData>0 && pWal->apWiData[0] );
47408
47409   /* Read the header. This might happen concurrently with a write to the
47410   ** same area of shared memory on a different CPU in a SMP,
47411   ** meaning it is possible that an inconsistent snapshot is read
47412   ** from the file. If this happens, return non-zero.
47413   **
47414   ** There are two copies of the header at the beginning of the wal-index.
47415   ** When reading, read [0] first then [1].  Writes are in the reverse order.
47416   ** Memory barriers are used to prevent the compiler or the hardware from
47417   ** reordering the reads and writes.
47418   */
47419   aHdr = walIndexHdr(pWal);
47420   memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
47421   walShmBarrier(pWal);
47422   memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
47423
47424   if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
47425     return 1;   /* Dirty read */
47426   }  
47427   if( h1.isInit==0 ){
47428     return 1;   /* Malformed header - probably all zeros */
47429   }
47430   walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
47431   if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
47432     return 1;   /* Checksum does not match */
47433   }
47434
47435   if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
47436     *pChanged = 1;
47437     memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
47438     pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
47439     testcase( pWal->szPage<=32768 );
47440     testcase( pWal->szPage>=65536 );
47441   }
47442
47443   /* The header was successfully read. Return zero. */
47444   return 0;
47445 }
47446
47447 /*
47448 ** Read the wal-index header from the wal-index and into pWal->hdr.
47449 ** If the wal-header appears to be corrupt, try to reconstruct the
47450 ** wal-index from the WAL before returning.
47451 **
47452 ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
47453 ** changed by this opertion.  If pWal->hdr is unchanged, set *pChanged
47454 ** to 0.
47455 **
47456 ** If the wal-index header is successfully read, return SQLITE_OK. 
47457 ** Otherwise an SQLite error code.
47458 */
47459 static int walIndexReadHdr(Wal *pWal, int *pChanged){
47460   int rc;                         /* Return code */
47461   int badHdr;                     /* True if a header read failed */
47462   volatile u32 *page0;            /* Chunk of wal-index containing header */
47463
47464   /* Ensure that page 0 of the wal-index (the page that contains the 
47465   ** wal-index header) is mapped. Return early if an error occurs here.
47466   */
47467   assert( pChanged );
47468   rc = walIndexPage(pWal, 0, &page0);
47469   if( rc!=SQLITE_OK ){
47470     return rc;
47471   };
47472   assert( page0 || pWal->writeLock==0 );
47473
47474   /* If the first page of the wal-index has been mapped, try to read the
47475   ** wal-index header immediately, without holding any lock. This usually
47476   ** works, but may fail if the wal-index header is corrupt or currently 
47477   ** being modified by another thread or process.
47478   */
47479   badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
47480
47481   /* If the first attempt failed, it might have been due to a race
47482   ** with a writer.  So get a WRITE lock and try again.
47483   */
47484   assert( badHdr==0 || pWal->writeLock==0 );
47485   if( badHdr ){
47486     if( pWal->readOnly & WAL_SHM_RDONLY ){
47487       if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
47488         walUnlockShared(pWal, WAL_WRITE_LOCK);
47489         rc = SQLITE_READONLY_RECOVERY;
47490       }
47491     }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
47492       pWal->writeLock = 1;
47493       if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
47494         badHdr = walIndexTryHdr(pWal, pChanged);
47495         if( badHdr ){
47496           /* If the wal-index header is still malformed even while holding
47497           ** a WRITE lock, it can only mean that the header is corrupted and
47498           ** needs to be reconstructed.  So run recovery to do exactly that.
47499           */
47500           rc = walIndexRecover(pWal);
47501           *pChanged = 1;
47502         }
47503       }
47504       pWal->writeLock = 0;
47505       walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
47506     }
47507   }
47508
47509   /* If the header is read successfully, check the version number to make
47510   ** sure the wal-index was not constructed with some future format that
47511   ** this version of SQLite cannot understand.
47512   */
47513   if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
47514     rc = SQLITE_CANTOPEN_BKPT;
47515   }
47516
47517   return rc;
47518 }
47519
47520 /*
47521 ** This is the value that walTryBeginRead returns when it needs to
47522 ** be retried.
47523 */
47524 #define WAL_RETRY  (-1)
47525
47526 /*
47527 ** Attempt to start a read transaction.  This might fail due to a race or
47528 ** other transient condition.  When that happens, it returns WAL_RETRY to
47529 ** indicate to the caller that it is safe to retry immediately.
47530 **
47531 ** On success return SQLITE_OK.  On a permanent failure (such an
47532 ** I/O error or an SQLITE_BUSY because another process is running
47533 ** recovery) return a positive error code.
47534 **
47535 ** The useWal parameter is true to force the use of the WAL and disable
47536 ** the case where the WAL is bypassed because it has been completely
47537 ** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr() 
47538 ** to make a copy of the wal-index header into pWal->hdr.  If the 
47539 ** wal-index header has changed, *pChanged is set to 1 (as an indication 
47540 ** to the caller that the local paget cache is obsolete and needs to be 
47541 ** flushed.)  When useWal==1, the wal-index header is assumed to already
47542 ** be loaded and the pChanged parameter is unused.
47543 **
47544 ** The caller must set the cnt parameter to the number of prior calls to
47545 ** this routine during the current read attempt that returned WAL_RETRY.
47546 ** This routine will start taking more aggressive measures to clear the
47547 ** race conditions after multiple WAL_RETRY returns, and after an excessive
47548 ** number of errors will ultimately return SQLITE_PROTOCOL.  The
47549 ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
47550 ** and is not honoring the locking protocol.  There is a vanishingly small
47551 ** chance that SQLITE_PROTOCOL could be returned because of a run of really
47552 ** bad luck when there is lots of contention for the wal-index, but that
47553 ** possibility is so small that it can be safely neglected, we believe.
47554 **
47555 ** On success, this routine obtains a read lock on 
47556 ** WAL_READ_LOCK(pWal->readLock).  The pWal->readLock integer is
47557 ** in the range 0 <= pWal->readLock < WAL_NREADER.  If pWal->readLock==(-1)
47558 ** that means the Wal does not hold any read lock.  The reader must not
47559 ** access any database page that is modified by a WAL frame up to and
47560 ** including frame number aReadMark[pWal->readLock].  The reader will
47561 ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
47562 ** Or if pWal->readLock==0, then the reader will ignore the WAL
47563 ** completely and get all content directly from the database file.
47564 ** If the useWal parameter is 1 then the WAL will never be ignored and
47565 ** this routine will always set pWal->readLock>0 on success.
47566 ** When the read transaction is completed, the caller must release the
47567 ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
47568 **
47569 ** This routine uses the nBackfill and aReadMark[] fields of the header
47570 ** to select a particular WAL_READ_LOCK() that strives to let the
47571 ** checkpoint process do as much work as possible.  This routine might
47572 ** update values of the aReadMark[] array in the header, but if it does
47573 ** so it takes care to hold an exclusive lock on the corresponding
47574 ** WAL_READ_LOCK() while changing values.
47575 */
47576 static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
47577   volatile WalCkptInfo *pInfo;    /* Checkpoint information in wal-index */
47578   u32 mxReadMark;                 /* Largest aReadMark[] value */
47579   int mxI;                        /* Index of largest aReadMark[] value */
47580   int i;                          /* Loop counter */
47581   int rc = SQLITE_OK;             /* Return code  */
47582
47583   assert( pWal->readLock<0 );     /* Not currently locked */
47584
47585   /* Take steps to avoid spinning forever if there is a protocol error.
47586   **
47587   ** Circumstances that cause a RETRY should only last for the briefest
47588   ** instances of time.  No I/O or other system calls are done while the
47589   ** locks are held, so the locks should not be held for very long. But 
47590   ** if we are unlucky, another process that is holding a lock might get
47591   ** paged out or take a page-fault that is time-consuming to resolve, 
47592   ** during the few nanoseconds that it is holding the lock.  In that case,
47593   ** it might take longer than normal for the lock to free.
47594   **
47595   ** After 5 RETRYs, we begin calling sqlite3OsSleep().  The first few
47596   ** calls to sqlite3OsSleep() have a delay of 1 microsecond.  Really this
47597   ** is more of a scheduler yield than an actual delay.  But on the 10th
47598   ** an subsequent retries, the delays start becoming longer and longer, 
47599   ** so that on the 100th (and last) RETRY we delay for 21 milliseconds.
47600   ** The total delay time before giving up is less than 1 second.
47601   */
47602   if( cnt>5 ){
47603     int nDelay = 1;                      /* Pause time in microseconds */
47604     if( cnt>100 ){
47605       VVA_ONLY( pWal->lockError = 1; )
47606       return SQLITE_PROTOCOL;
47607     }
47608     if( cnt>=10 ) nDelay = (cnt-9)*238;  /* Max delay 21ms. Total delay 996ms */
47609     sqlite3OsSleep(pWal->pVfs, nDelay);
47610   }
47611
47612   if( !useWal ){
47613     rc = walIndexReadHdr(pWal, pChanged);
47614     if( rc==SQLITE_BUSY ){
47615       /* If there is not a recovery running in another thread or process
47616       ** then convert BUSY errors to WAL_RETRY.  If recovery is known to
47617       ** be running, convert BUSY to BUSY_RECOVERY.  There is a race here
47618       ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
47619       ** would be technically correct.  But the race is benign since with
47620       ** WAL_RETRY this routine will be called again and will probably be
47621       ** right on the second iteration.
47622       */
47623       if( pWal->apWiData[0]==0 ){
47624         /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
47625         ** We assume this is a transient condition, so return WAL_RETRY. The
47626         ** xShmMap() implementation used by the default unix and win32 VFS 
47627         ** modules may return SQLITE_BUSY due to a race condition in the 
47628         ** code that determines whether or not the shared-memory region 
47629         ** must be zeroed before the requested page is returned.
47630         */
47631         rc = WAL_RETRY;
47632       }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
47633         walUnlockShared(pWal, WAL_RECOVER_LOCK);
47634         rc = WAL_RETRY;
47635       }else if( rc==SQLITE_BUSY ){
47636         rc = SQLITE_BUSY_RECOVERY;
47637       }
47638     }
47639     if( rc!=SQLITE_OK ){
47640       return rc;
47641     }
47642   }
47643
47644   pInfo = walCkptInfo(pWal);
47645   if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
47646     /* The WAL has been completely backfilled (or it is empty).
47647     ** and can be safely ignored.
47648     */
47649     rc = walLockShared(pWal, WAL_READ_LOCK(0));
47650     walShmBarrier(pWal);
47651     if( rc==SQLITE_OK ){
47652       if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
47653         /* It is not safe to allow the reader to continue here if frames
47654         ** may have been appended to the log before READ_LOCK(0) was obtained.
47655         ** When holding READ_LOCK(0), the reader ignores the entire log file,
47656         ** which implies that the database file contains a trustworthy
47657         ** snapshoT. Since holding READ_LOCK(0) prevents a checkpoint from
47658         ** happening, this is usually correct.
47659         **
47660         ** However, if frames have been appended to the log (or if the log 
47661         ** is wrapped and written for that matter) before the READ_LOCK(0)
47662         ** is obtained, that is not necessarily true. A checkpointer may
47663         ** have started to backfill the appended frames but crashed before
47664         ** it finished. Leaving a corrupt image in the database file.
47665         */
47666         walUnlockShared(pWal, WAL_READ_LOCK(0));
47667         return WAL_RETRY;
47668       }
47669       pWal->readLock = 0;
47670       return SQLITE_OK;
47671     }else if( rc!=SQLITE_BUSY ){
47672       return rc;
47673     }
47674   }
47675
47676   /* If we get this far, it means that the reader will want to use
47677   ** the WAL to get at content from recent commits.  The job now is
47678   ** to select one of the aReadMark[] entries that is closest to
47679   ** but not exceeding pWal->hdr.mxFrame and lock that entry.
47680   */
47681   mxReadMark = 0;
47682   mxI = 0;
47683   for(i=1; i<WAL_NREADER; i++){
47684     u32 thisMark = pInfo->aReadMark[i];
47685     if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
47686       assert( thisMark!=READMARK_NOT_USED );
47687       mxReadMark = thisMark;
47688       mxI = i;
47689     }
47690   }
47691   /* There was once an "if" here. The extra "{" is to preserve indentation. */
47692   {
47693     if( (pWal->readOnly & WAL_SHM_RDONLY)==0
47694      && (mxReadMark<pWal->hdr.mxFrame || mxI==0)
47695     ){
47696       for(i=1; i<WAL_NREADER; i++){
47697         rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
47698         if( rc==SQLITE_OK ){
47699           mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
47700           mxI = i;
47701           walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
47702           break;
47703         }else if( rc!=SQLITE_BUSY ){
47704           return rc;
47705         }
47706       }
47707     }
47708     if( mxI==0 ){
47709       assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
47710       return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
47711     }
47712
47713     rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
47714     if( rc ){
47715       return rc==SQLITE_BUSY ? WAL_RETRY : rc;
47716     }
47717     /* Now that the read-lock has been obtained, check that neither the
47718     ** value in the aReadMark[] array or the contents of the wal-index
47719     ** header have changed.
47720     **
47721     ** It is necessary to check that the wal-index header did not change
47722     ** between the time it was read and when the shared-lock was obtained
47723     ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
47724     ** that the log file may have been wrapped by a writer, or that frames
47725     ** that occur later in the log than pWal->hdr.mxFrame may have been
47726     ** copied into the database by a checkpointer. If either of these things
47727     ** happened, then reading the database with the current value of
47728     ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
47729     ** instead.
47730     **
47731     ** This does not guarantee that the copy of the wal-index header is up to
47732     ** date before proceeding. That would not be possible without somehow
47733     ** blocking writers. It only guarantees that a dangerous checkpoint or 
47734     ** log-wrap (either of which would require an exclusive lock on
47735     ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
47736     */
47737     walShmBarrier(pWal);
47738     if( pInfo->aReadMark[mxI]!=mxReadMark
47739      || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
47740     ){
47741       walUnlockShared(pWal, WAL_READ_LOCK(mxI));
47742       return WAL_RETRY;
47743     }else{
47744       assert( mxReadMark<=pWal->hdr.mxFrame );
47745       pWal->readLock = (i16)mxI;
47746     }
47747   }
47748   return rc;
47749 }
47750
47751 /*
47752 ** Begin a read transaction on the database.
47753 **
47754 ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
47755 ** it takes a snapshot of the state of the WAL and wal-index for the current
47756 ** instant in time.  The current thread will continue to use this snapshot.
47757 ** Other threads might append new content to the WAL and wal-index but
47758 ** that extra content is ignored by the current thread.
47759 **
47760 ** If the database contents have changes since the previous read
47761 ** transaction, then *pChanged is set to 1 before returning.  The
47762 ** Pager layer will use this to know that is cache is stale and
47763 ** needs to be flushed.
47764 */
47765 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
47766   int rc;                         /* Return code */
47767   int cnt = 0;                    /* Number of TryBeginRead attempts */
47768
47769   do{
47770     rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
47771   }while( rc==WAL_RETRY );
47772   testcase( (rc&0xff)==SQLITE_BUSY );
47773   testcase( (rc&0xff)==SQLITE_IOERR );
47774   testcase( rc==SQLITE_PROTOCOL );
47775   testcase( rc==SQLITE_OK );
47776   return rc;
47777 }
47778
47779 /*
47780 ** Finish with a read transaction.  All this does is release the
47781 ** read-lock.
47782 */
47783 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
47784   sqlite3WalEndWriteTransaction(pWal);
47785   if( pWal->readLock>=0 ){
47786     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
47787     pWal->readLock = -1;
47788   }
47789 }
47790
47791 /*
47792 ** Search the wal file for page pgno. If found, set *piRead to the frame that
47793 ** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
47794 ** to zero.
47795 **
47796 ** Return SQLITE_OK if successful, or an error code if an error occurs. If an
47797 ** error does occur, the final value of *piRead is undefined.
47798 */
47799 SQLITE_PRIVATE int sqlite3WalFindFrame(
47800   Wal *pWal,                      /* WAL handle */
47801   Pgno pgno,                      /* Database page number to read data for */
47802   u32 *piRead                     /* OUT: Frame number (or zero) */
47803 ){
47804   u32 iRead = 0;                  /* If !=0, WAL frame to return data from */
47805   u32 iLast = pWal->hdr.mxFrame;  /* Last page in WAL for this reader */
47806   int iHash;                      /* Used to loop through N hash tables */
47807
47808   /* This routine is only be called from within a read transaction. */
47809   assert( pWal->readLock>=0 || pWal->lockError );
47810
47811   /* If the "last page" field of the wal-index header snapshot is 0, then
47812   ** no data will be read from the wal under any circumstances. Return early
47813   ** in this case as an optimization.  Likewise, if pWal->readLock==0, 
47814   ** then the WAL is ignored by the reader so return early, as if the 
47815   ** WAL were empty.
47816   */
47817   if( iLast==0 || pWal->readLock==0 ){
47818     *piRead = 0;
47819     return SQLITE_OK;
47820   }
47821
47822   /* Search the hash table or tables for an entry matching page number
47823   ** pgno. Each iteration of the following for() loop searches one
47824   ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
47825   **
47826   ** This code might run concurrently to the code in walIndexAppend()
47827   ** that adds entries to the wal-index (and possibly to this hash 
47828   ** table). This means the value just read from the hash 
47829   ** slot (aHash[iKey]) may have been added before or after the 
47830   ** current read transaction was opened. Values added after the
47831   ** read transaction was opened may have been written incorrectly -
47832   ** i.e. these slots may contain garbage data. However, we assume
47833   ** that any slots written before the current read transaction was
47834   ** opened remain unmodified.
47835   **
47836   ** For the reasons above, the if(...) condition featured in the inner
47837   ** loop of the following block is more stringent that would be required 
47838   ** if we had exclusive access to the hash-table:
47839   **
47840   **   (aPgno[iFrame]==pgno): 
47841   **     This condition filters out normal hash-table collisions.
47842   **
47843   **   (iFrame<=iLast): 
47844   **     This condition filters out entries that were added to the hash
47845   **     table after the current read-transaction had started.
47846   */
47847   for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
47848     volatile ht_slot *aHash;      /* Pointer to hash table */
47849     volatile u32 *aPgno;          /* Pointer to array of page numbers */
47850     u32 iZero;                    /* Frame number corresponding to aPgno[0] */
47851     int iKey;                     /* Hash slot index */
47852     int nCollide;                 /* Number of hash collisions remaining */
47853     int rc;                       /* Error code */
47854
47855     rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
47856     if( rc!=SQLITE_OK ){
47857       return rc;
47858     }
47859     nCollide = HASHTABLE_NSLOT;
47860     for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
47861       u32 iFrame = aHash[iKey] + iZero;
47862       if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
47863         /* assert( iFrame>iRead ); -- not true if there is corruption */
47864         iRead = iFrame;
47865       }
47866       if( (nCollide--)==0 ){
47867         return SQLITE_CORRUPT_BKPT;
47868       }
47869     }
47870   }
47871
47872 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
47873   /* If expensive assert() statements are available, do a linear search
47874   ** of the wal-index file content. Make sure the results agree with the
47875   ** result obtained using the hash indexes above.  */
47876   {
47877     u32 iRead2 = 0;
47878     u32 iTest;
47879     for(iTest=iLast; iTest>0; iTest--){
47880       if( walFramePgno(pWal, iTest)==pgno ){
47881         iRead2 = iTest;
47882         break;
47883       }
47884     }
47885     assert( iRead==iRead2 );
47886   }
47887 #endif
47888
47889   *piRead = iRead;
47890   return SQLITE_OK;
47891 }
47892
47893 /*
47894 ** Read the contents of frame iRead from the wal file into buffer pOut
47895 ** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
47896 ** error code otherwise.
47897 */
47898 SQLITE_PRIVATE int sqlite3WalReadFrame(
47899   Wal *pWal,                      /* WAL handle */
47900   u32 iRead,                      /* Frame to read */
47901   int nOut,                       /* Size of buffer pOut in bytes */
47902   u8 *pOut                        /* Buffer to write page data to */
47903 ){
47904   int sz;
47905   i64 iOffset;
47906   sz = pWal->hdr.szPage;
47907   sz = (sz&0xfe00) + ((sz&0x0001)<<16);
47908   testcase( sz<=32768 );
47909   testcase( sz>=65536 );
47910   iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
47911   /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
47912   return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
47913 }
47914
47915 /* 
47916 ** Return the size of the database in pages (or zero, if unknown).
47917 */
47918 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
47919   if( pWal && ALWAYS(pWal->readLock>=0) ){
47920     return pWal->hdr.nPage;
47921   }
47922   return 0;
47923 }
47924
47925
47926 /* 
47927 ** This function starts a write transaction on the WAL.
47928 **
47929 ** A read transaction must have already been started by a prior call
47930 ** to sqlite3WalBeginReadTransaction().
47931 **
47932 ** If another thread or process has written into the database since
47933 ** the read transaction was started, then it is not possible for this
47934 ** thread to write as doing so would cause a fork.  So this routine
47935 ** returns SQLITE_BUSY in that case and no write transaction is started.
47936 **
47937 ** There can only be a single writer active at a time.
47938 */
47939 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
47940   int rc;
47941
47942   /* Cannot start a write transaction without first holding a read
47943   ** transaction. */
47944   assert( pWal->readLock>=0 );
47945
47946   if( pWal->readOnly ){
47947     return SQLITE_READONLY;
47948   }
47949
47950   /* Only one writer allowed at a time.  Get the write lock.  Return
47951   ** SQLITE_BUSY if unable.
47952   */
47953   rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
47954   if( rc ){
47955     return rc;
47956   }
47957   pWal->writeLock = 1;
47958
47959   /* If another connection has written to the database file since the
47960   ** time the read transaction on this connection was started, then
47961   ** the write is disallowed.
47962   */
47963   if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
47964     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
47965     pWal->writeLock = 0;
47966     rc = SQLITE_BUSY;
47967   }
47968
47969   return rc;
47970 }
47971
47972 /*
47973 ** End a write transaction.  The commit has already been done.  This
47974 ** routine merely releases the lock.
47975 */
47976 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
47977   if( pWal->writeLock ){
47978     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
47979     pWal->writeLock = 0;
47980     pWal->truncateOnCommit = 0;
47981   }
47982   return SQLITE_OK;
47983 }
47984
47985 /*
47986 ** If any data has been written (but not committed) to the log file, this
47987 ** function moves the write-pointer back to the start of the transaction.
47988 **
47989 ** Additionally, the callback function is invoked for each frame written
47990 ** to the WAL since the start of the transaction. If the callback returns
47991 ** other than SQLITE_OK, it is not invoked again and the error code is
47992 ** returned to the caller.
47993 **
47994 ** Otherwise, if the callback function does not return an error, this
47995 ** function returns SQLITE_OK.
47996 */
47997 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
47998   int rc = SQLITE_OK;
47999   if( ALWAYS(pWal->writeLock) ){
48000     Pgno iMax = pWal->hdr.mxFrame;
48001     Pgno iFrame;
48002   
48003     /* Restore the clients cache of the wal-index header to the state it
48004     ** was in before the client began writing to the database. 
48005     */
48006     memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
48007
48008     for(iFrame=pWal->hdr.mxFrame+1; 
48009         ALWAYS(rc==SQLITE_OK) && iFrame<=iMax; 
48010         iFrame++
48011     ){
48012       /* This call cannot fail. Unless the page for which the page number
48013       ** is passed as the second argument is (a) in the cache and 
48014       ** (b) has an outstanding reference, then xUndo is either a no-op
48015       ** (if (a) is false) or simply expels the page from the cache (if (b)
48016       ** is false).
48017       **
48018       ** If the upper layer is doing a rollback, it is guaranteed that there
48019       ** are no outstanding references to any page other than page 1. And
48020       ** page 1 is never written to the log until the transaction is
48021       ** committed. As a result, the call to xUndo may not fail.
48022       */
48023       assert( walFramePgno(pWal, iFrame)!=1 );
48024       rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
48025     }
48026     if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
48027   }
48028   assert( rc==SQLITE_OK );
48029   return rc;
48030 }
48031
48032 /* 
48033 ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32 
48034 ** values. This function populates the array with values required to 
48035 ** "rollback" the write position of the WAL handle back to the current 
48036 ** point in the event of a savepoint rollback (via WalSavepointUndo()).
48037 */
48038 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
48039   assert( pWal->writeLock );
48040   aWalData[0] = pWal->hdr.mxFrame;
48041   aWalData[1] = pWal->hdr.aFrameCksum[0];
48042   aWalData[2] = pWal->hdr.aFrameCksum[1];
48043   aWalData[3] = pWal->nCkpt;
48044 }
48045
48046 /* 
48047 ** Move the write position of the WAL back to the point identified by
48048 ** the values in the aWalData[] array. aWalData must point to an array
48049 ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
48050 ** by a call to WalSavepoint().
48051 */
48052 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
48053   int rc = SQLITE_OK;
48054
48055   assert( pWal->writeLock );
48056   assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
48057
48058   if( aWalData[3]!=pWal->nCkpt ){
48059     /* This savepoint was opened immediately after the write-transaction
48060     ** was started. Right after that, the writer decided to wrap around
48061     ** to the start of the log. Update the savepoint values to match.
48062     */
48063     aWalData[0] = 0;
48064     aWalData[3] = pWal->nCkpt;
48065   }
48066
48067   if( aWalData[0]<pWal->hdr.mxFrame ){
48068     pWal->hdr.mxFrame = aWalData[0];
48069     pWal->hdr.aFrameCksum[0] = aWalData[1];
48070     pWal->hdr.aFrameCksum[1] = aWalData[2];
48071     walCleanupHash(pWal);
48072   }
48073
48074   return rc;
48075 }
48076
48077
48078 /*
48079 ** This function is called just before writing a set of frames to the log
48080 ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
48081 ** to the current log file, it is possible to overwrite the start of the
48082 ** existing log file with the new frames (i.e. "reset" the log). If so,
48083 ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
48084 ** unchanged.
48085 **
48086 ** SQLITE_OK is returned if no error is encountered (regardless of whether
48087 ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
48088 ** if an error occurs.
48089 */
48090 static int walRestartLog(Wal *pWal){
48091   int rc = SQLITE_OK;
48092   int cnt;
48093
48094   if( pWal->readLock==0 ){
48095     volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
48096     assert( pInfo->nBackfill==pWal->hdr.mxFrame );
48097     if( pInfo->nBackfill>0 ){
48098       u32 salt1;
48099       sqlite3_randomness(4, &salt1);
48100       rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
48101       if( rc==SQLITE_OK ){
48102         /* If all readers are using WAL_READ_LOCK(0) (in other words if no
48103         ** readers are currently using the WAL), then the transactions
48104         ** frames will overwrite the start of the existing log. Update the
48105         ** wal-index header to reflect this.
48106         **
48107         ** In theory it would be Ok to update the cache of the header only
48108         ** at this point. But updating the actual wal-index header is also
48109         ** safe and means there is no special case for sqlite3WalUndo()
48110         ** to handle if this transaction is rolled back.
48111         */
48112         int i;                    /* Loop counter */
48113         u32 *aSalt = pWal->hdr.aSalt;       /* Big-endian salt values */
48114
48115         pWal->nCkpt++;
48116         pWal->hdr.mxFrame = 0;
48117         sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
48118         aSalt[1] = salt1;
48119         walIndexWriteHdr(pWal);
48120         pInfo->nBackfill = 0;
48121         pInfo->aReadMark[1] = 0;
48122         for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
48123         assert( pInfo->aReadMark[0]==0 );
48124         walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
48125       }else if( rc!=SQLITE_BUSY ){
48126         return rc;
48127       }
48128     }
48129     walUnlockShared(pWal, WAL_READ_LOCK(0));
48130     pWal->readLock = -1;
48131     cnt = 0;
48132     do{
48133       int notUsed;
48134       rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
48135     }while( rc==WAL_RETRY );
48136     assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
48137     testcase( (rc&0xff)==SQLITE_IOERR );
48138     testcase( rc==SQLITE_PROTOCOL );
48139     testcase( rc==SQLITE_OK );
48140   }
48141   return rc;
48142 }
48143
48144 /*
48145 ** Information about the current state of the WAL file and where
48146 ** the next fsync should occur - passed from sqlite3WalFrames() into
48147 ** walWriteToLog().
48148 */
48149 typedef struct WalWriter {
48150   Wal *pWal;                   /* The complete WAL information */
48151   sqlite3_file *pFd;           /* The WAL file to which we write */
48152   sqlite3_int64 iSyncPoint;    /* Fsync at this offset */
48153   int syncFlags;               /* Flags for the fsync */
48154   int szPage;                  /* Size of one page */
48155 } WalWriter;
48156
48157 /*
48158 ** Write iAmt bytes of content into the WAL file beginning at iOffset.
48159 ** Do a sync when crossing the p->iSyncPoint boundary.
48160 **
48161 ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
48162 ** first write the part before iSyncPoint, then sync, then write the
48163 ** rest.
48164 */
48165 static int walWriteToLog(
48166   WalWriter *p,              /* WAL to write to */
48167   void *pContent,            /* Content to be written */
48168   int iAmt,                  /* Number of bytes to write */
48169   sqlite3_int64 iOffset      /* Start writing at this offset */
48170 ){
48171   int rc;
48172   if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
48173     int iFirstAmt = (int)(p->iSyncPoint - iOffset);
48174     rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
48175     if( rc ) return rc;
48176     iOffset += iFirstAmt;
48177     iAmt -= iFirstAmt;
48178     pContent = (void*)(iFirstAmt + (char*)pContent);
48179     assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) );
48180     rc = sqlite3OsSync(p->pFd, p->syncFlags);
48181     if( iAmt==0 || rc ) return rc;
48182   }
48183   rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
48184   return rc;
48185 }
48186
48187 /*
48188 ** Write out a single frame of the WAL
48189 */
48190 static int walWriteOneFrame(
48191   WalWriter *p,               /* Where to write the frame */
48192   PgHdr *pPage,               /* The page of the frame to be written */
48193   int nTruncate,              /* The commit flag.  Usually 0.  >0 for commit */
48194   sqlite3_int64 iOffset       /* Byte offset at which to write */
48195 ){
48196   int rc;                         /* Result code from subfunctions */
48197   void *pData;                    /* Data actually written */
48198   u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */
48199 #if defined(SQLITE_HAS_CODEC)
48200   if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM;
48201 #else
48202   pData = pPage->pData;
48203 #endif
48204   walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
48205   rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
48206   if( rc ) return rc;
48207   /* Write the page data */
48208   rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
48209   return rc;
48210 }
48211
48212 /* 
48213 ** Write a set of frames to the log. The caller must hold the write-lock
48214 ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
48215 */
48216 SQLITE_PRIVATE int sqlite3WalFrames(
48217   Wal *pWal,                      /* Wal handle to write to */
48218   int szPage,                     /* Database page-size in bytes */
48219   PgHdr *pList,                   /* List of dirty pages to write */
48220   Pgno nTruncate,                 /* Database size after this commit */
48221   int isCommit,                   /* True if this is a commit */
48222   int sync_flags                  /* Flags to pass to OsSync() (or 0) */
48223 ){
48224   int rc;                         /* Used to catch return codes */
48225   u32 iFrame;                     /* Next frame address */
48226   PgHdr *p;                       /* Iterator to run through pList with. */
48227   PgHdr *pLast = 0;               /* Last frame in list */
48228   int nExtra = 0;                 /* Number of extra copies of last page */
48229   int szFrame;                    /* The size of a single frame */
48230   i64 iOffset;                    /* Next byte to write in WAL file */
48231   WalWriter w;                    /* The writer */
48232
48233   assert( pList );
48234   assert( pWal->writeLock );
48235
48236   /* If this frame set completes a transaction, then nTruncate>0.  If
48237   ** nTruncate==0 then this frame set does not complete the transaction. */
48238   assert( (isCommit!=0)==(nTruncate!=0) );
48239
48240 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
48241   { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
48242     WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
48243               pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
48244   }
48245 #endif
48246
48247   /* See if it is possible to write these frames into the start of the
48248   ** log file, instead of appending to it at pWal->hdr.mxFrame.
48249   */
48250   if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
48251     return rc;
48252   }
48253
48254   /* If this is the first frame written into the log, write the WAL
48255   ** header to the start of the WAL file. See comments at the top of
48256   ** this source file for a description of the WAL header format.
48257   */
48258   iFrame = pWal->hdr.mxFrame;
48259   if( iFrame==0 ){
48260     u8 aWalHdr[WAL_HDRSIZE];      /* Buffer to assemble wal-header in */
48261     u32 aCksum[2];                /* Checksum for wal-header */
48262
48263     sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
48264     sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
48265     sqlite3Put4byte(&aWalHdr[8], szPage);
48266     sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
48267     if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
48268     memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
48269     walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
48270     sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
48271     sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
48272     
48273     pWal->szPage = szPage;
48274     pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
48275     pWal->hdr.aFrameCksum[0] = aCksum[0];
48276     pWal->hdr.aFrameCksum[1] = aCksum[1];
48277     pWal->truncateOnCommit = 1;
48278
48279     rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
48280     WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
48281     if( rc!=SQLITE_OK ){
48282       return rc;
48283     }
48284
48285     /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
48286     ** all syncing is turned off by PRAGMA synchronous=OFF).  Otherwise
48287     ** an out-of-order write following a WAL restart could result in
48288     ** database corruption.  See the ticket:
48289     **
48290     **     http://localhost:591/sqlite/info/ff5be73dee
48291     */
48292     if( pWal->syncHeader && sync_flags ){
48293       rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK);
48294       if( rc ) return rc;
48295     }
48296   }
48297   assert( (int)pWal->szPage==szPage );
48298
48299   /* Setup information needed to write frames into the WAL */
48300   w.pWal = pWal;
48301   w.pFd = pWal->pWalFd;
48302   w.iSyncPoint = 0;
48303   w.syncFlags = sync_flags;
48304   w.szPage = szPage;
48305   iOffset = walFrameOffset(iFrame+1, szPage);
48306   szFrame = szPage + WAL_FRAME_HDRSIZE;
48307
48308   /* Write all frames into the log file exactly once */
48309   for(p=pList; p; p=p->pDirty){
48310     int nDbSize;   /* 0 normally.  Positive == commit flag */
48311     iFrame++;
48312     assert( iOffset==walFrameOffset(iFrame, szPage) );
48313     nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
48314     rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
48315     if( rc ) return rc;
48316     pLast = p;
48317     iOffset += szFrame;
48318   }
48319
48320   /* If this is the end of a transaction, then we might need to pad
48321   ** the transaction and/or sync the WAL file.
48322   **
48323   ** Padding and syncing only occur if this set of frames complete a
48324   ** transaction and if PRAGMA synchronous=FULL.  If synchronous==NORMAL
48325   ** or synchonous==OFF, then no padding or syncing are needed.
48326   **
48327   ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
48328   ** needed and only the sync is done.  If padding is needed, then the
48329   ** final frame is repeated (with its commit mark) until the next sector
48330   ** boundary is crossed.  Only the part of the WAL prior to the last
48331   ** sector boundary is synced; the part of the last frame that extends
48332   ** past the sector boundary is written after the sync.
48333   */
48334   if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){
48335     if( pWal->padToSectorBoundary ){
48336       int sectorSize = sqlite3SectorSize(pWal->pWalFd);
48337       w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
48338       while( iOffset<w.iSyncPoint ){
48339         rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
48340         if( rc ) return rc;
48341         iOffset += szFrame;
48342         nExtra++;
48343       }
48344     }else{
48345       rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK);
48346     }
48347   }
48348
48349   /* If this frame set completes the first transaction in the WAL and
48350   ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
48351   ** journal size limit, if possible.
48352   */
48353   if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
48354     i64 sz = pWal->mxWalSize;
48355     if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
48356       sz = walFrameOffset(iFrame+nExtra+1, szPage);
48357     }
48358     walLimitSize(pWal, sz);
48359     pWal->truncateOnCommit = 0;
48360   }
48361
48362   /* Append data to the wal-index. It is not necessary to lock the 
48363   ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
48364   ** guarantees that there are no other writers, and no data that may
48365   ** be in use by existing readers is being overwritten.
48366   */
48367   iFrame = pWal->hdr.mxFrame;
48368   for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
48369     iFrame++;
48370     rc = walIndexAppend(pWal, iFrame, p->pgno);
48371   }
48372   while( rc==SQLITE_OK && nExtra>0 ){
48373     iFrame++;
48374     nExtra--;
48375     rc = walIndexAppend(pWal, iFrame, pLast->pgno);
48376   }
48377
48378   if( rc==SQLITE_OK ){
48379     /* Update the private copy of the header. */
48380     pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
48381     testcase( szPage<=32768 );
48382     testcase( szPage>=65536 );
48383     pWal->hdr.mxFrame = iFrame;
48384     if( isCommit ){
48385       pWal->hdr.iChange++;
48386       pWal->hdr.nPage = nTruncate;
48387     }
48388     /* If this is a commit, update the wal-index header too. */
48389     if( isCommit ){
48390       walIndexWriteHdr(pWal);
48391       pWal->iCallback = iFrame;
48392     }
48393   }
48394
48395   WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
48396   return rc;
48397 }
48398
48399 /* 
48400 ** This routine is called to implement sqlite3_wal_checkpoint() and
48401 ** related interfaces.
48402 **
48403 ** Obtain a CHECKPOINT lock and then backfill as much information as
48404 ** we can from WAL into the database.
48405 **
48406 ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
48407 ** callback. In this case this function runs a blocking checkpoint.
48408 */
48409 SQLITE_PRIVATE int sqlite3WalCheckpoint(
48410   Wal *pWal,                      /* Wal connection */
48411   int eMode,                      /* PASSIVE, FULL or RESTART */
48412   int (*xBusy)(void*),            /* Function to call when busy */
48413   void *pBusyArg,                 /* Context argument for xBusyHandler */
48414   int sync_flags,                 /* Flags to sync db file with (or 0) */
48415   int nBuf,                       /* Size of temporary buffer */
48416   u8 *zBuf,                       /* Temporary buffer to use */
48417   int *pnLog,                     /* OUT: Number of frames in WAL */
48418   int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
48419 ){
48420   int rc;                         /* Return code */
48421   int isChanged = 0;              /* True if a new wal-index header is loaded */
48422   int eMode2 = eMode;             /* Mode to pass to walCheckpoint() */
48423
48424   assert( pWal->ckptLock==0 );
48425   assert( pWal->writeLock==0 );
48426
48427   if( pWal->readOnly ) return SQLITE_READONLY;
48428   WALTRACE(("WAL%p: checkpoint begins\n", pWal));
48429   rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
48430   if( rc ){
48431     /* Usually this is SQLITE_BUSY meaning that another thread or process
48432     ** is already running a checkpoint, or maybe a recovery.  But it might
48433     ** also be SQLITE_IOERR. */
48434     return rc;
48435   }
48436   pWal->ckptLock = 1;
48437
48438   /* If this is a blocking-checkpoint, then obtain the write-lock as well
48439   ** to prevent any writers from running while the checkpoint is underway.
48440   ** This has to be done before the call to walIndexReadHdr() below.
48441   **
48442   ** If the writer lock cannot be obtained, then a passive checkpoint is
48443   ** run instead. Since the checkpointer is not holding the writer lock,
48444   ** there is no point in blocking waiting for any readers. Assuming no 
48445   ** other error occurs, this function will return SQLITE_BUSY to the caller.
48446   */
48447   if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
48448     rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
48449     if( rc==SQLITE_OK ){
48450       pWal->writeLock = 1;
48451     }else if( rc==SQLITE_BUSY ){
48452       eMode2 = SQLITE_CHECKPOINT_PASSIVE;
48453       rc = SQLITE_OK;
48454     }
48455   }
48456
48457   /* Read the wal-index header. */
48458   if( rc==SQLITE_OK ){
48459     rc = walIndexReadHdr(pWal, &isChanged);
48460     if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
48461       sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
48462     }
48463   }
48464
48465   /* Copy data from the log to the database file. */
48466   if( rc==SQLITE_OK ){
48467     if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
48468       rc = SQLITE_CORRUPT_BKPT;
48469     }else{
48470       rc = walCheckpoint(pWal, eMode2, xBusy, pBusyArg, sync_flags, zBuf);
48471     }
48472
48473     /* If no error occurred, set the output variables. */
48474     if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
48475       if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
48476       if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
48477     }
48478   }
48479
48480   if( isChanged ){
48481     /* If a new wal-index header was loaded before the checkpoint was 
48482     ** performed, then the pager-cache associated with pWal is now
48483     ** out of date. So zero the cached wal-index header to ensure that
48484     ** next time the pager opens a snapshot on this database it knows that
48485     ** the cache needs to be reset.
48486     */
48487     memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
48488   }
48489
48490   /* Release the locks. */
48491   sqlite3WalEndWriteTransaction(pWal);
48492   walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
48493   pWal->ckptLock = 0;
48494   WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
48495   return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
48496 }
48497
48498 /* Return the value to pass to a sqlite3_wal_hook callback, the
48499 ** number of frames in the WAL at the point of the last commit since
48500 ** sqlite3WalCallback() was called.  If no commits have occurred since
48501 ** the last call, then return 0.
48502 */
48503 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
48504   u32 ret = 0;
48505   if( pWal ){
48506     ret = pWal->iCallback;
48507     pWal->iCallback = 0;
48508   }
48509   return (int)ret;
48510 }
48511
48512 /*
48513 ** This function is called to change the WAL subsystem into or out
48514 ** of locking_mode=EXCLUSIVE.
48515 **
48516 ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
48517 ** into locking_mode=NORMAL.  This means that we must acquire a lock
48518 ** on the pWal->readLock byte.  If the WAL is already in locking_mode=NORMAL
48519 ** or if the acquisition of the lock fails, then return 0.  If the
48520 ** transition out of exclusive-mode is successful, return 1.  This
48521 ** operation must occur while the pager is still holding the exclusive
48522 ** lock on the main database file.
48523 **
48524 ** If op is one, then change from locking_mode=NORMAL into 
48525 ** locking_mode=EXCLUSIVE.  This means that the pWal->readLock must
48526 ** be released.  Return 1 if the transition is made and 0 if the
48527 ** WAL is already in exclusive-locking mode - meaning that this
48528 ** routine is a no-op.  The pager must already hold the exclusive lock
48529 ** on the main database file before invoking this operation.
48530 **
48531 ** If op is negative, then do a dry-run of the op==1 case but do
48532 ** not actually change anything. The pager uses this to see if it
48533 ** should acquire the database exclusive lock prior to invoking
48534 ** the op==1 case.
48535 */
48536 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
48537   int rc;
48538   assert( pWal->writeLock==0 );
48539   assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
48540
48541   /* pWal->readLock is usually set, but might be -1 if there was a 
48542   ** prior error while attempting to acquire are read-lock. This cannot 
48543   ** happen if the connection is actually in exclusive mode (as no xShmLock
48544   ** locks are taken in this case). Nor should the pager attempt to
48545   ** upgrade to exclusive-mode following such an error.
48546   */
48547   assert( pWal->readLock>=0 || pWal->lockError );
48548   assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
48549
48550   if( op==0 ){
48551     if( pWal->exclusiveMode ){
48552       pWal->exclusiveMode = 0;
48553       if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
48554         pWal->exclusiveMode = 1;
48555       }
48556       rc = pWal->exclusiveMode==0;
48557     }else{
48558       /* Already in locking_mode=NORMAL */
48559       rc = 0;
48560     }
48561   }else if( op>0 ){
48562     assert( pWal->exclusiveMode==0 );
48563     assert( pWal->readLock>=0 );
48564     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
48565     pWal->exclusiveMode = 1;
48566     rc = 1;
48567   }else{
48568     rc = pWal->exclusiveMode==0;
48569   }
48570   return rc;
48571 }
48572
48573 /* 
48574 ** Return true if the argument is non-NULL and the WAL module is using
48575 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
48576 ** WAL module is using shared-memory, return false. 
48577 */
48578 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
48579   return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
48580 }
48581
48582 #ifdef SQLITE_ENABLE_ZIPVFS
48583 /*
48584 ** If the argument is not NULL, it points to a Wal object that holds a
48585 ** read-lock. This function returns the database page-size if it is known,
48586 ** or zero if it is not (or if pWal is NULL).
48587 */
48588 SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
48589   assert( pWal==0 || pWal->readLock>=0 );
48590   return (pWal ? pWal->szPage : 0);
48591 }
48592 #endif
48593
48594 #endif /* #ifndef SQLITE_OMIT_WAL */
48595
48596 /************** End of wal.c *************************************************/
48597 /************** Begin file btmutex.c *****************************************/
48598 /*
48599 ** 2007 August 27
48600 **
48601 ** The author disclaims copyright to this source code.  In place of
48602 ** a legal notice, here is a blessing:
48603 **
48604 **    May you do good and not evil.
48605 **    May you find forgiveness for yourself and forgive others.
48606 **    May you share freely, never taking more than you give.
48607 **
48608 *************************************************************************
48609 **
48610 ** This file contains code used to implement mutexes on Btree objects.
48611 ** This code really belongs in btree.c.  But btree.c is getting too
48612 ** big and we want to break it down some.  This packaged seemed like
48613 ** a good breakout.
48614 */
48615 /************** Include btreeInt.h in the middle of btmutex.c ****************/
48616 /************** Begin file btreeInt.h ****************************************/
48617 /*
48618 ** 2004 April 6
48619 **
48620 ** The author disclaims copyright to this source code.  In place of
48621 ** a legal notice, here is a blessing:
48622 **
48623 **    May you do good and not evil.
48624 **    May you find forgiveness for yourself and forgive others.
48625 **    May you share freely, never taking more than you give.
48626 **
48627 *************************************************************************
48628 ** This file implements a external (disk-based) database using BTrees.
48629 ** For a detailed discussion of BTrees, refer to
48630 **
48631 **     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
48632 **     "Sorting And Searching", pages 473-480. Addison-Wesley
48633 **     Publishing Company, Reading, Massachusetts.
48634 **
48635 ** The basic idea is that each page of the file contains N database
48636 ** entries and N+1 pointers to subpages.
48637 **
48638 **   ----------------------------------------------------------------
48639 **   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
48640 **   ----------------------------------------------------------------
48641 **
48642 ** All of the keys on the page that Ptr(0) points to have values less
48643 ** than Key(0).  All of the keys on page Ptr(1) and its subpages have
48644 ** values greater than Key(0) and less than Key(1).  All of the keys
48645 ** on Ptr(N) and its subpages have values greater than Key(N-1).  And
48646 ** so forth.
48647 **
48648 ** Finding a particular key requires reading O(log(M)) pages from the 
48649 ** disk where M is the number of entries in the tree.
48650 **
48651 ** In this implementation, a single file can hold one or more separate 
48652 ** BTrees.  Each BTree is identified by the index of its root page.  The
48653 ** key and data for any entry are combined to form the "payload".  A
48654 ** fixed amount of payload can be carried directly on the database
48655 ** page.  If the payload is larger than the preset amount then surplus
48656 ** bytes are stored on overflow pages.  The payload for an entry
48657 ** and the preceding pointer are combined to form a "Cell".  Each 
48658 ** page has a small header which contains the Ptr(N) pointer and other
48659 ** information such as the size of key and data.
48660 **
48661 ** FORMAT DETAILS
48662 **
48663 ** The file is divided into pages.  The first page is called page 1,
48664 ** the second is page 2, and so forth.  A page number of zero indicates
48665 ** "no such page".  The page size can be any power of 2 between 512 and 65536.
48666 ** Each page can be either a btree page, a freelist page, an overflow
48667 ** page, or a pointer-map page.
48668 **
48669 ** The first page is always a btree page.  The first 100 bytes of the first
48670 ** page contain a special header (the "file header") that describes the file.
48671 ** The format of the file header is as follows:
48672 **
48673 **   OFFSET   SIZE    DESCRIPTION
48674 **      0      16     Header string: "SQLite format 3\000"
48675 **     16       2     Page size in bytes.  
48676 **     18       1     File format write version
48677 **     19       1     File format read version
48678 **     20       1     Bytes of unused space at the end of each page
48679 **     21       1     Max embedded payload fraction
48680 **     22       1     Min embedded payload fraction
48681 **     23       1     Min leaf payload fraction
48682 **     24       4     File change counter
48683 **     28       4     Reserved for future use
48684 **     32       4     First freelist page
48685 **     36       4     Number of freelist pages in the file
48686 **     40      60     15 4-byte meta values passed to higher layers
48687 **
48688 **     40       4     Schema cookie
48689 **     44       4     File format of schema layer
48690 **     48       4     Size of page cache
48691 **     52       4     Largest root-page (auto/incr_vacuum)
48692 **     56       4     1=UTF-8 2=UTF16le 3=UTF16be
48693 **     60       4     User version
48694 **     64       4     Incremental vacuum mode
48695 **     68       4     unused
48696 **     72       4     unused
48697 **     76       4     unused
48698 **
48699 ** All of the integer values are big-endian (most significant byte first).
48700 **
48701 ** The file change counter is incremented when the database is changed
48702 ** This counter allows other processes to know when the file has changed
48703 ** and thus when they need to flush their cache.
48704 **
48705 ** The max embedded payload fraction is the amount of the total usable
48706 ** space in a page that can be consumed by a single cell for standard
48707 ** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
48708 ** is to limit the maximum cell size so that at least 4 cells will fit
48709 ** on one page.  Thus the default max embedded payload fraction is 64.
48710 **
48711 ** If the payload for a cell is larger than the max payload, then extra
48712 ** payload is spilled to overflow pages.  Once an overflow page is allocated,
48713 ** as many bytes as possible are moved into the overflow pages without letting
48714 ** the cell size drop below the min embedded payload fraction.
48715 **
48716 ** The min leaf payload fraction is like the min embedded payload fraction
48717 ** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
48718 ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
48719 ** not specified in the header.
48720 **
48721 ** Each btree pages is divided into three sections:  The header, the
48722 ** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
48723 ** file header that occurs before the page header.
48724 **
48725 **      |----------------|
48726 **      | file header    |   100 bytes.  Page 1 only.
48727 **      |----------------|
48728 **      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
48729 **      |----------------|
48730 **      | cell pointer   |   |  2 bytes per cell.  Sorted order.
48731 **      | array          |   |  Grows downward
48732 **      |                |   v
48733 **      |----------------|
48734 **      | unallocated    |
48735 **      | space          |
48736 **      |----------------|   ^  Grows upwards
48737 **      | cell content   |   |  Arbitrary order interspersed with freeblocks.
48738 **      | area           |   |  and free space fragments.
48739 **      |----------------|
48740 **
48741 ** The page headers looks like this:
48742 **
48743 **   OFFSET   SIZE     DESCRIPTION
48744 **      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
48745 **      1       2      byte offset to the first freeblock
48746 **      3       2      number of cells on this page
48747 **      5       2      first byte of the cell content area
48748 **      7       1      number of fragmented free bytes
48749 **      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
48750 **
48751 ** The flags define the format of this btree page.  The leaf flag means that
48752 ** this page has no children.  The zerodata flag means that this page carries
48753 ** only keys and no data.  The intkey flag means that the key is a integer
48754 ** which is stored in the key size entry of the cell header rather than in
48755 ** the payload area.
48756 **
48757 ** The cell pointer array begins on the first byte after the page header.
48758 ** The cell pointer array contains zero or more 2-byte numbers which are
48759 ** offsets from the beginning of the page to the cell content in the cell
48760 ** content area.  The cell pointers occur in sorted order.  The system strives
48761 ** to keep free space after the last cell pointer so that new cells can
48762 ** be easily added without having to defragment the page.
48763 **
48764 ** Cell content is stored at the very end of the page and grows toward the
48765 ** beginning of the page.
48766 **
48767 ** Unused space within the cell content area is collected into a linked list of
48768 ** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
48769 ** to the first freeblock is given in the header.  Freeblocks occur in
48770 ** increasing order.  Because a freeblock must be at least 4 bytes in size,
48771 ** any group of 3 or fewer unused bytes in the cell content area cannot
48772 ** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
48773 ** a fragment.  The total number of bytes in all fragments is recorded.
48774 ** in the page header at offset 7.
48775 **
48776 **    SIZE    DESCRIPTION
48777 **      2     Byte offset of the next freeblock
48778 **      2     Bytes in this freeblock
48779 **
48780 ** Cells are of variable length.  Cells are stored in the cell content area at
48781 ** the end of the page.  Pointers to the cells are in the cell pointer array
48782 ** that immediately follows the page header.  Cells is not necessarily
48783 ** contiguous or in order, but cell pointers are contiguous and in order.
48784 **
48785 ** Cell content makes use of variable length integers.  A variable
48786 ** length integer is 1 to 9 bytes where the lower 7 bits of each 
48787 ** byte are used.  The integer consists of all bytes that have bit 8 set and
48788 ** the first byte with bit 8 clear.  The most significant byte of the integer
48789 ** appears first.  A variable-length integer may not be more than 9 bytes long.
48790 ** As a special case, all 8 bytes of the 9th byte are used as data.  This
48791 ** allows a 64-bit integer to be encoded in 9 bytes.
48792 **
48793 **    0x00                      becomes  0x00000000
48794 **    0x7f                      becomes  0x0000007f
48795 **    0x81 0x00                 becomes  0x00000080
48796 **    0x82 0x00                 becomes  0x00000100
48797 **    0x80 0x7f                 becomes  0x0000007f
48798 **    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
48799 **    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
48800 **
48801 ** Variable length integers are used for rowids and to hold the number of
48802 ** bytes of key and data in a btree cell.
48803 **
48804 ** The content of a cell looks like this:
48805 **
48806 **    SIZE    DESCRIPTION
48807 **      4     Page number of the left child. Omitted if leaf flag is set.
48808 **     var    Number of bytes of data. Omitted if the zerodata flag is set.
48809 **     var    Number of bytes of key. Or the key itself if intkey flag is set.
48810 **      *     Payload
48811 **      4     First page of the overflow chain.  Omitted if no overflow
48812 **
48813 ** Overflow pages form a linked list.  Each page except the last is completely
48814 ** filled with data (pagesize - 4 bytes).  The last page can have as little
48815 ** as 1 byte of data.
48816 **
48817 **    SIZE    DESCRIPTION
48818 **      4     Page number of next overflow page
48819 **      *     Data
48820 **
48821 ** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
48822 ** file header points to the first in a linked list of trunk page.  Each trunk
48823 ** page points to multiple leaf pages.  The content of a leaf page is
48824 ** unspecified.  A trunk page looks like this:
48825 **
48826 **    SIZE    DESCRIPTION
48827 **      4     Page number of next trunk page
48828 **      4     Number of leaf pointers on this page
48829 **      *     zero or more pages numbers of leaves
48830 */
48831
48832
48833 /* The following value is the maximum cell size assuming a maximum page
48834 ** size give above.
48835 */
48836 #define MX_CELL_SIZE(pBt)  ((int)(pBt->pageSize-8))
48837
48838 /* The maximum number of cells on a single page of the database.  This
48839 ** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
48840 ** plus 2 bytes for the index to the cell in the page header).  Such
48841 ** small cells will be rare, but they are possible.
48842 */
48843 #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
48844
48845 /* Forward declarations */
48846 typedef struct MemPage MemPage;
48847 typedef struct BtLock BtLock;
48848
48849 /*
48850 ** This is a magic string that appears at the beginning of every
48851 ** SQLite database in order to identify the file as a real database.
48852 **
48853 ** You can change this value at compile-time by specifying a
48854 ** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
48855 ** header must be exactly 16 bytes including the zero-terminator so
48856 ** the string itself should be 15 characters long.  If you change
48857 ** the header, then your custom library will not be able to read 
48858 ** databases generated by the standard tools and the standard tools
48859 ** will not be able to read databases created by your custom library.
48860 */
48861 #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
48862 #  define SQLITE_FILE_HEADER "SQLite format 3"
48863 #endif
48864
48865 /*
48866 ** Page type flags.  An ORed combination of these flags appear as the
48867 ** first byte of on-disk image of every BTree page.
48868 */
48869 #define PTF_INTKEY    0x01
48870 #define PTF_ZERODATA  0x02
48871 #define PTF_LEAFDATA  0x04
48872 #define PTF_LEAF      0x08
48873
48874 /*
48875 ** As each page of the file is loaded into memory, an instance of the following
48876 ** structure is appended and initialized to zero.  This structure stores
48877 ** information about the page that is decoded from the raw file page.
48878 **
48879 ** The pParent field points back to the parent page.  This allows us to
48880 ** walk up the BTree from any leaf to the root.  Care must be taken to
48881 ** unref() the parent page pointer when this page is no longer referenced.
48882 ** The pageDestructor() routine handles that chore.
48883 **
48884 ** Access to all fields of this structure is controlled by the mutex
48885 ** stored in MemPage.pBt->mutex.
48886 */
48887 struct MemPage {
48888   u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
48889   u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
48890   u8 intKey;           /* True if intkey flag is set */
48891   u8 leaf;             /* True if leaf flag is set */
48892   u8 hasData;          /* True if this page stores data */
48893   u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
48894   u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
48895   u8 max1bytePayload;  /* min(maxLocal,127) */
48896   u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
48897   u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
48898   u16 cellOffset;      /* Index in aData of first cell pointer */
48899   u16 nFree;           /* Number of free bytes on the page */
48900   u16 nCell;           /* Number of cells on this page, local and ovfl */
48901   u16 maskPage;        /* Mask for page offset */
48902   u16 aiOvfl[5];       /* Insert the i-th overflow cell before the aiOvfl-th
48903                        ** non-overflow cell */
48904   u8 *apOvfl[5];       /* Pointers to the body of overflow cells */
48905   BtShared *pBt;       /* Pointer to BtShared that this page is part of */
48906   u8 *aData;           /* Pointer to disk image of the page data */
48907   u8 *aDataEnd;        /* One byte past the end of usable data */
48908   u8 *aCellIdx;        /* The cell index area */
48909   DbPage *pDbPage;     /* Pager page handle */
48910   Pgno pgno;           /* Page number for this page */
48911 };
48912
48913 /*
48914 ** The in-memory image of a disk page has the auxiliary information appended
48915 ** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
48916 ** that extra information.
48917 */
48918 #define EXTRA_SIZE sizeof(MemPage)
48919
48920 /*
48921 ** A linked list of the following structures is stored at BtShared.pLock.
48922 ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor 
48923 ** is opened on the table with root page BtShared.iTable. Locks are removed
48924 ** from this list when a transaction is committed or rolled back, or when
48925 ** a btree handle is closed.
48926 */
48927 struct BtLock {
48928   Btree *pBtree;        /* Btree handle holding this lock */
48929   Pgno iTable;          /* Root page of table */
48930   u8 eLock;             /* READ_LOCK or WRITE_LOCK */
48931   BtLock *pNext;        /* Next in BtShared.pLock list */
48932 };
48933
48934 /* Candidate values for BtLock.eLock */
48935 #define READ_LOCK     1
48936 #define WRITE_LOCK    2
48937
48938 /* A Btree handle
48939 **
48940 ** A database connection contains a pointer to an instance of
48941 ** this object for every database file that it has open.  This structure
48942 ** is opaque to the database connection.  The database connection cannot
48943 ** see the internals of this structure and only deals with pointers to
48944 ** this structure.
48945 **
48946 ** For some database files, the same underlying database cache might be 
48947 ** shared between multiple connections.  In that case, each connection
48948 ** has it own instance of this object.  But each instance of this object
48949 ** points to the same BtShared object.  The database cache and the
48950 ** schema associated with the database file are all contained within
48951 ** the BtShared object.
48952 **
48953 ** All fields in this structure are accessed under sqlite3.mutex.
48954 ** The pBt pointer itself may not be changed while there exists cursors 
48955 ** in the referenced BtShared that point back to this Btree since those
48956 ** cursors have to go through this Btree to find their BtShared and
48957 ** they often do so without holding sqlite3.mutex.
48958 */
48959 struct Btree {
48960   sqlite3 *db;       /* The database connection holding this btree */
48961   BtShared *pBt;     /* Sharable content of this btree */
48962   u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
48963   u8 sharable;       /* True if we can share pBt with another db */
48964   u8 locked;         /* True if db currently has pBt locked */
48965   int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
48966   int nBackup;       /* Number of backup operations reading this btree */
48967   Btree *pNext;      /* List of other sharable Btrees from the same db */
48968   Btree *pPrev;      /* Back pointer of the same list */
48969 #ifndef SQLITE_OMIT_SHARED_CACHE
48970   BtLock lock;       /* Object used to lock page 1 */
48971 #endif
48972 };
48973
48974 /*
48975 ** Btree.inTrans may take one of the following values.
48976 **
48977 ** If the shared-data extension is enabled, there may be multiple users
48978 ** of the Btree structure. At most one of these may open a write transaction,
48979 ** but any number may have active read transactions.
48980 */
48981 #define TRANS_NONE  0
48982 #define TRANS_READ  1
48983 #define TRANS_WRITE 2
48984
48985 /*
48986 ** An instance of this object represents a single database file.
48987 ** 
48988 ** A single database file can be in use at the same time by two
48989 ** or more database connections.  When two or more connections are
48990 ** sharing the same database file, each connection has it own
48991 ** private Btree object for the file and each of those Btrees points
48992 ** to this one BtShared object.  BtShared.nRef is the number of
48993 ** connections currently sharing this database file.
48994 **
48995 ** Fields in this structure are accessed under the BtShared.mutex
48996 ** mutex, except for nRef and pNext which are accessed under the
48997 ** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
48998 ** may not be modified once it is initially set as long as nRef>0.
48999 ** The pSchema field may be set once under BtShared.mutex and
49000 ** thereafter is unchanged as long as nRef>0.
49001 **
49002 ** isPending:
49003 **
49004 **   If a BtShared client fails to obtain a write-lock on a database
49005 **   table (because there exists one or more read-locks on the table),
49006 **   the shared-cache enters 'pending-lock' state and isPending is
49007 **   set to true.
49008 **
49009 **   The shared-cache leaves the 'pending lock' state when either of
49010 **   the following occur:
49011 **
49012 **     1) The current writer (BtShared.pWriter) concludes its transaction, OR
49013 **     2) The number of locks held by other connections drops to zero.
49014 **
49015 **   while in the 'pending-lock' state, no connection may start a new
49016 **   transaction.
49017 **
49018 **   This feature is included to help prevent writer-starvation.
49019 */
49020 struct BtShared {
49021   Pager *pPager;        /* The page cache */
49022   sqlite3 *db;          /* Database connection currently using this Btree */
49023   BtCursor *pCursor;    /* A list of all open cursors */
49024   MemPage *pPage1;      /* First page of the database */
49025   u8 openFlags;         /* Flags to sqlite3BtreeOpen() */
49026 #ifndef SQLITE_OMIT_AUTOVACUUM
49027   u8 autoVacuum;        /* True if auto-vacuum is enabled */
49028   u8 incrVacuum;        /* True if incr-vacuum is enabled */
49029   u8 bDoTruncate;       /* True to truncate db on commit */
49030 #endif
49031   u8 inTransaction;     /* Transaction state */
49032   u8 max1bytePayload;   /* Maximum first byte of cell for a 1-byte payload */
49033   u16 btsFlags;         /* Boolean parameters.  See BTS_* macros below */
49034   u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
49035   u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
49036   u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
49037   u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
49038   u32 pageSize;         /* Total number of bytes on a page */
49039   u32 usableSize;       /* Number of usable bytes on each page */
49040   int nTransaction;     /* Number of open transactions (read + write) */
49041   u32 nPage;            /* Number of pages in the database */
49042   void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
49043   void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
49044   sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
49045   Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
49046 #ifndef SQLITE_OMIT_SHARED_CACHE
49047   int nRef;             /* Number of references to this structure */
49048   BtShared *pNext;      /* Next on a list of sharable BtShared structs */
49049   BtLock *pLock;        /* List of locks held on this shared-btree struct */
49050   Btree *pWriter;       /* Btree with currently open write transaction */
49051 #endif
49052   u8 *pTmpSpace;        /* BtShared.pageSize bytes of space for tmp use */
49053 };
49054
49055 /*
49056 ** Allowed values for BtShared.btsFlags
49057 */
49058 #define BTS_READ_ONLY        0x0001   /* Underlying file is readonly */
49059 #define BTS_PAGESIZE_FIXED   0x0002   /* Page size can no longer be changed */
49060 #define BTS_SECURE_DELETE    0x0004   /* PRAGMA secure_delete is enabled */
49061 #define BTS_INITIALLY_EMPTY  0x0008   /* Database was empty at trans start */
49062 #define BTS_NO_WAL           0x0010   /* Do not open write-ahead-log files */
49063 #define BTS_EXCLUSIVE        0x0020   /* pWriter has an exclusive lock */
49064 #define BTS_PENDING          0x0040   /* Waiting for read-locks to clear */
49065
49066 /*
49067 ** An instance of the following structure is used to hold information
49068 ** about a cell.  The parseCellPtr() function fills in this structure
49069 ** based on information extract from the raw disk page.
49070 */
49071 typedef struct CellInfo CellInfo;
49072 struct CellInfo {
49073   i64 nKey;      /* The key for INTKEY tables, or number of bytes in key */
49074   u8 *pCell;     /* Pointer to the start of cell content */
49075   u32 nData;     /* Number of bytes of data */
49076   u32 nPayload;  /* Total amount of payload */
49077   u16 nHeader;   /* Size of the cell content header in bytes */
49078   u16 nLocal;    /* Amount of payload held locally */
49079   u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
49080   u16 nSize;     /* Size of the cell content on the main b-tree page */
49081 };
49082
49083 /*
49084 ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
49085 ** this will be declared corrupt. This value is calculated based on a
49086 ** maximum database size of 2^31 pages a minimum fanout of 2 for a
49087 ** root-node and 3 for all other internal nodes.
49088 **
49089 ** If a tree that appears to be taller than this is encountered, it is
49090 ** assumed that the database is corrupt.
49091 */
49092 #define BTCURSOR_MAX_DEPTH 20
49093
49094 /*
49095 ** A cursor is a pointer to a particular entry within a particular
49096 ** b-tree within a database file.
49097 **
49098 ** The entry is identified by its MemPage and the index in
49099 ** MemPage.aCell[] of the entry.
49100 **
49101 ** A single database file can be shared by two more database connections,
49102 ** but cursors cannot be shared.  Each cursor is associated with a
49103 ** particular database connection identified BtCursor.pBtree.db.
49104 **
49105 ** Fields in this structure are accessed under the BtShared.mutex
49106 ** found at self->pBt->mutex. 
49107 */
49108 struct BtCursor {
49109   Btree *pBtree;            /* The Btree to which this cursor belongs */
49110   BtShared *pBt;            /* The BtShared this cursor points to */
49111   BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
49112   struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
49113 #ifndef SQLITE_OMIT_INCRBLOB
49114   Pgno *aOverflow;          /* Cache of overflow page locations */
49115 #endif
49116   Pgno pgnoRoot;            /* The root page of this tree */
49117   sqlite3_int64 cachedRowid; /* Next rowid cache.  0 means not valid */
49118   CellInfo info;            /* A parse of the cell we are pointing at */
49119   i64 nKey;        /* Size of pKey, or last integer key */
49120   void *pKey;      /* Saved key that was cursor's last known position */
49121   int skipNext;    /* Prev() is noop if negative. Next() is noop if positive */
49122   u8 wrFlag;                /* True if writable */
49123   u8 atLast;                /* Cursor pointing to the last entry */
49124   u8 validNKey;             /* True if info.nKey is valid */
49125   u8 eState;                /* One of the CURSOR_XXX constants (see below) */
49126 #ifndef SQLITE_OMIT_INCRBLOB
49127   u8 isIncrblobHandle;      /* True if this cursor is an incr. io handle */
49128 #endif
49129   u8 hints;                             /* As configured by CursorSetHints() */
49130   i16 iPage;                            /* Index of current page in apPage */
49131   u16 aiIdx[BTCURSOR_MAX_DEPTH];        /* Current index in apPage[i] */
49132   MemPage *apPage[BTCURSOR_MAX_DEPTH];  /* Pages from root to current page */
49133 };
49134
49135 /*
49136 ** Potential values for BtCursor.eState.
49137 **
49138 ** CURSOR_VALID:
49139 **   Cursor points to a valid entry. getPayload() etc. may be called.
49140 **
49141 ** CURSOR_INVALID:
49142 **   Cursor does not point to a valid entry. This can happen (for example) 
49143 **   because the table is empty or because BtreeCursorFirst() has not been
49144 **   called.
49145 **
49146 ** CURSOR_REQUIRESEEK:
49147 **   The table that this cursor was opened on still exists, but has been 
49148 **   modified since the cursor was last used. The cursor position is saved
49149 **   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in 
49150 **   this state, restoreCursorPosition() can be called to attempt to
49151 **   seek the cursor to the saved position.
49152 **
49153 ** CURSOR_FAULT:
49154 **   A unrecoverable error (an I/O error or a malloc failure) has occurred
49155 **   on a different connection that shares the BtShared cache with this
49156 **   cursor.  The error has left the cache in an inconsistent state.
49157 **   Do nothing else with this cursor.  Any attempt to use the cursor
49158 **   should return the error code stored in BtCursor.skip
49159 */
49160 #define CURSOR_INVALID           0
49161 #define CURSOR_VALID             1
49162 #define CURSOR_REQUIRESEEK       2
49163 #define CURSOR_FAULT             3
49164
49165 /* 
49166 ** The database page the PENDING_BYTE occupies. This page is never used.
49167 */
49168 # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
49169
49170 /*
49171 ** These macros define the location of the pointer-map entry for a 
49172 ** database page. The first argument to each is the number of usable
49173 ** bytes on each page of the database (often 1024). The second is the
49174 ** page number to look up in the pointer map.
49175 **
49176 ** PTRMAP_PAGENO returns the database page number of the pointer-map
49177 ** page that stores the required pointer. PTRMAP_PTROFFSET returns
49178 ** the offset of the requested map entry.
49179 **
49180 ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
49181 ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
49182 ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
49183 ** this test.
49184 */
49185 #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
49186 #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
49187 #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
49188
49189 /*
49190 ** The pointer map is a lookup table that identifies the parent page for
49191 ** each child page in the database file.  The parent page is the page that
49192 ** contains a pointer to the child.  Every page in the database contains
49193 ** 0 or 1 parent pages.  (In this context 'database page' refers
49194 ** to any page that is not part of the pointer map itself.)  Each pointer map
49195 ** entry consists of a single byte 'type' and a 4 byte parent page number.
49196 ** The PTRMAP_XXX identifiers below are the valid types.
49197 **
49198 ** The purpose of the pointer map is to facility moving pages from one
49199 ** position in the file to another as part of autovacuum.  When a page
49200 ** is moved, the pointer in its parent must be updated to point to the
49201 ** new location.  The pointer map is used to locate the parent page quickly.
49202 **
49203 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
49204 **                  used in this case.
49205 **
49206 ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number 
49207 **                  is not used in this case.
49208 **
49209 ** PTRMAP_OVERFLOW1: The database page is the first page in a list of 
49210 **                   overflow pages. The page number identifies the page that
49211 **                   contains the cell with a pointer to this overflow page.
49212 **
49213 ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
49214 **                   overflow pages. The page-number identifies the previous
49215 **                   page in the overflow page list.
49216 **
49217 ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
49218 **               identifies the parent page in the btree.
49219 */
49220 #define PTRMAP_ROOTPAGE 1
49221 #define PTRMAP_FREEPAGE 2
49222 #define PTRMAP_OVERFLOW1 3
49223 #define PTRMAP_OVERFLOW2 4
49224 #define PTRMAP_BTREE 5
49225
49226 /* A bunch of assert() statements to check the transaction state variables
49227 ** of handle p (type Btree*) are internally consistent.
49228 */
49229 #define btreeIntegrity(p) \
49230   assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
49231   assert( p->pBt->inTransaction>=p->inTrans ); 
49232
49233
49234 /*
49235 ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
49236 ** if the database supports auto-vacuum or not. Because it is used
49237 ** within an expression that is an argument to another macro 
49238 ** (sqliteMallocRaw), it is not possible to use conditional compilation.
49239 ** So, this macro is defined instead.
49240 */
49241 #ifndef SQLITE_OMIT_AUTOVACUUM
49242 #define ISAUTOVACUUM (pBt->autoVacuum)
49243 #else
49244 #define ISAUTOVACUUM 0
49245 #endif
49246
49247
49248 /*
49249 ** This structure is passed around through all the sanity checking routines
49250 ** in order to keep track of some global state information.
49251 **
49252 ** The aRef[] array is allocated so that there is 1 bit for each page in
49253 ** the database. As the integrity-check proceeds, for each page used in
49254 ** the database the corresponding bit is set. This allows integrity-check to 
49255 ** detect pages that are used twice and orphaned pages (both of which 
49256 ** indicate corruption).
49257 */
49258 typedef struct IntegrityCk IntegrityCk;
49259 struct IntegrityCk {
49260   BtShared *pBt;    /* The tree being checked out */
49261   Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
49262   u8 *aPgRef;       /* 1 bit per page in the db (see above) */
49263   Pgno nPage;       /* Number of pages in the database */
49264   int mxErr;        /* Stop accumulating errors when this reaches zero */
49265   int nErr;         /* Number of messages written to zErrMsg so far */
49266   int mallocFailed; /* A memory allocation error has occurred */
49267   StrAccum errMsg;  /* Accumulate the error message text here */
49268 };
49269
49270 /*
49271 ** Routines to read or write a two- and four-byte big-endian integer values.
49272 */
49273 #define get2byte(x)   ((x)[0]<<8 | (x)[1])
49274 #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
49275 #define get4byte sqlite3Get4byte
49276 #define put4byte sqlite3Put4byte
49277
49278 /************** End of btreeInt.h ********************************************/
49279 /************** Continuing where we left off in btmutex.c ********************/
49280 #ifndef SQLITE_OMIT_SHARED_CACHE
49281 #if SQLITE_THREADSAFE
49282
49283 /*
49284 ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
49285 ** set BtShared.db to the database handle associated with p and the
49286 ** p->locked boolean to true.
49287 */
49288 static void lockBtreeMutex(Btree *p){
49289   assert( p->locked==0 );
49290   assert( sqlite3_mutex_notheld(p->pBt->mutex) );
49291   assert( sqlite3_mutex_held(p->db->mutex) );
49292
49293   sqlite3_mutex_enter(p->pBt->mutex);
49294   p->pBt->db = p->db;
49295   p->locked = 1;
49296 }
49297
49298 /*
49299 ** Release the BtShared mutex associated with B-Tree handle p and
49300 ** clear the p->locked boolean.
49301 */
49302 static void unlockBtreeMutex(Btree *p){
49303   BtShared *pBt = p->pBt;
49304   assert( p->locked==1 );
49305   assert( sqlite3_mutex_held(pBt->mutex) );
49306   assert( sqlite3_mutex_held(p->db->mutex) );
49307   assert( p->db==pBt->db );
49308
49309   sqlite3_mutex_leave(pBt->mutex);
49310   p->locked = 0;
49311 }
49312
49313 /*
49314 ** Enter a mutex on the given BTree object.
49315 **
49316 ** If the object is not sharable, then no mutex is ever required
49317 ** and this routine is a no-op.  The underlying mutex is non-recursive.
49318 ** But we keep a reference count in Btree.wantToLock so the behavior
49319 ** of this interface is recursive.
49320 **
49321 ** To avoid deadlocks, multiple Btrees are locked in the same order
49322 ** by all database connections.  The p->pNext is a list of other
49323 ** Btrees belonging to the same database connection as the p Btree
49324 ** which need to be locked after p.  If we cannot get a lock on
49325 ** p, then first unlock all of the others on p->pNext, then wait
49326 ** for the lock to become available on p, then relock all of the
49327 ** subsequent Btrees that desire a lock.
49328 */
49329 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
49330   Btree *pLater;
49331
49332   /* Some basic sanity checking on the Btree.  The list of Btrees
49333   ** connected by pNext and pPrev should be in sorted order by
49334   ** Btree.pBt value. All elements of the list should belong to
49335   ** the same connection. Only shared Btrees are on the list. */
49336   assert( p->pNext==0 || p->pNext->pBt>p->pBt );
49337   assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
49338   assert( p->pNext==0 || p->pNext->db==p->db );
49339   assert( p->pPrev==0 || p->pPrev->db==p->db );
49340   assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
49341
49342   /* Check for locking consistency */
49343   assert( !p->locked || p->wantToLock>0 );
49344   assert( p->sharable || p->wantToLock==0 );
49345
49346   /* We should already hold a lock on the database connection */
49347   assert( sqlite3_mutex_held(p->db->mutex) );
49348
49349   /* Unless the database is sharable and unlocked, then BtShared.db
49350   ** should already be set correctly. */
49351   assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
49352
49353   if( !p->sharable ) return;
49354   p->wantToLock++;
49355   if( p->locked ) return;
49356
49357   /* In most cases, we should be able to acquire the lock we
49358   ** want without having to go throught the ascending lock
49359   ** procedure that follows.  Just be sure not to block.
49360   */
49361   if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
49362     p->pBt->db = p->db;
49363     p->locked = 1;
49364     return;
49365   }
49366
49367   /* To avoid deadlock, first release all locks with a larger
49368   ** BtShared address.  Then acquire our lock.  Then reacquire
49369   ** the other BtShared locks that we used to hold in ascending
49370   ** order.
49371   */
49372   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
49373     assert( pLater->sharable );
49374     assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
49375     assert( !pLater->locked || pLater->wantToLock>0 );
49376     if( pLater->locked ){
49377       unlockBtreeMutex(pLater);
49378     }
49379   }
49380   lockBtreeMutex(p);
49381   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
49382     if( pLater->wantToLock ){
49383       lockBtreeMutex(pLater);
49384     }
49385   }
49386 }
49387
49388 /*
49389 ** Exit the recursive mutex on a Btree.
49390 */
49391 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
49392   if( p->sharable ){
49393     assert( p->wantToLock>0 );
49394     p->wantToLock--;
49395     if( p->wantToLock==0 ){
49396       unlockBtreeMutex(p);
49397     }
49398   }
49399 }
49400
49401 #ifndef NDEBUG
49402 /*
49403 ** Return true if the BtShared mutex is held on the btree, or if the
49404 ** B-Tree is not marked as sharable.
49405 **
49406 ** This routine is used only from within assert() statements.
49407 */
49408 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
49409   assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
49410   assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
49411   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
49412   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
49413
49414   return (p->sharable==0 || p->locked);
49415 }
49416 #endif
49417
49418
49419 #ifndef SQLITE_OMIT_INCRBLOB
49420 /*
49421 ** Enter and leave a mutex on a Btree given a cursor owned by that
49422 ** Btree.  These entry points are used by incremental I/O and can be
49423 ** omitted if that module is not used.
49424 */
49425 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
49426   sqlite3BtreeEnter(pCur->pBtree);
49427 }
49428 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
49429   sqlite3BtreeLeave(pCur->pBtree);
49430 }
49431 #endif /* SQLITE_OMIT_INCRBLOB */
49432
49433
49434 /*
49435 ** Enter the mutex on every Btree associated with a database
49436 ** connection.  This is needed (for example) prior to parsing
49437 ** a statement since we will be comparing table and column names
49438 ** against all schemas and we do not want those schemas being
49439 ** reset out from under us.
49440 **
49441 ** There is a corresponding leave-all procedures.
49442 **
49443 ** Enter the mutexes in accending order by BtShared pointer address
49444 ** to avoid the possibility of deadlock when two threads with
49445 ** two or more btrees in common both try to lock all their btrees
49446 ** at the same instant.
49447 */
49448 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
49449   int i;
49450   Btree *p;
49451   assert( sqlite3_mutex_held(db->mutex) );
49452   for(i=0; i<db->nDb; i++){
49453     p = db->aDb[i].pBt;
49454     if( p ) sqlite3BtreeEnter(p);
49455   }
49456 }
49457 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
49458   int i;
49459   Btree *p;
49460   assert( sqlite3_mutex_held(db->mutex) );
49461   for(i=0; i<db->nDb; i++){
49462     p = db->aDb[i].pBt;
49463     if( p ) sqlite3BtreeLeave(p);
49464   }
49465 }
49466
49467 /*
49468 ** Return true if a particular Btree requires a lock.  Return FALSE if
49469 ** no lock is ever required since it is not sharable.
49470 */
49471 SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
49472   return p->sharable;
49473 }
49474
49475 #ifndef NDEBUG
49476 /*
49477 ** Return true if the current thread holds the database connection
49478 ** mutex and all required BtShared mutexes.
49479 **
49480 ** This routine is used inside assert() statements only.
49481 */
49482 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
49483   int i;
49484   if( !sqlite3_mutex_held(db->mutex) ){
49485     return 0;
49486   }
49487   for(i=0; i<db->nDb; i++){
49488     Btree *p;
49489     p = db->aDb[i].pBt;
49490     if( p && p->sharable &&
49491          (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
49492       return 0;
49493     }
49494   }
49495   return 1;
49496 }
49497 #endif /* NDEBUG */
49498
49499 #ifndef NDEBUG
49500 /*
49501 ** Return true if the correct mutexes are held for accessing the
49502 ** db->aDb[iDb].pSchema structure.  The mutexes required for schema
49503 ** access are:
49504 **
49505 **   (1) The mutex on db
49506 **   (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
49507 **
49508 ** If pSchema is not NULL, then iDb is computed from pSchema and
49509 ** db using sqlite3SchemaToIndex().
49510 */
49511 SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
49512   Btree *p;
49513   assert( db!=0 );
49514   if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
49515   assert( iDb>=0 && iDb<db->nDb );
49516   if( !sqlite3_mutex_held(db->mutex) ) return 0;
49517   if( iDb==1 ) return 1;
49518   p = db->aDb[iDb].pBt;
49519   assert( p!=0 );
49520   return p->sharable==0 || p->locked==1;
49521 }
49522 #endif /* NDEBUG */
49523
49524 #else /* SQLITE_THREADSAFE>0 above.  SQLITE_THREADSAFE==0 below */
49525 /*
49526 ** The following are special cases for mutex enter routines for use
49527 ** in single threaded applications that use shared cache.  Except for
49528 ** these two routines, all mutex operations are no-ops in that case and
49529 ** are null #defines in btree.h.
49530 **
49531 ** If shared cache is disabled, then all btree mutex routines, including
49532 ** the ones below, are no-ops and are null #defines in btree.h.
49533 */
49534
49535 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
49536   p->pBt->db = p->db;
49537 }
49538 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
49539   int i;
49540   for(i=0; i<db->nDb; i++){
49541     Btree *p = db->aDb[i].pBt;
49542     if( p ){
49543       p->pBt->db = p->db;
49544     }
49545   }
49546 }
49547 #endif /* if SQLITE_THREADSAFE */
49548 #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
49549
49550 /************** End of btmutex.c *********************************************/
49551 /************** Begin file btree.c *******************************************/
49552 /*
49553 ** 2004 April 6
49554 **
49555 ** The author disclaims copyright to this source code.  In place of
49556 ** a legal notice, here is a blessing:
49557 **
49558 **    May you do good and not evil.
49559 **    May you find forgiveness for yourself and forgive others.
49560 **    May you share freely, never taking more than you give.
49561 **
49562 *************************************************************************
49563 ** This file implements a external (disk-based) database using BTrees.
49564 ** See the header comment on "btreeInt.h" for additional information.
49565 ** Including a description of file format and an overview of operation.
49566 */
49567
49568 /*
49569 ** The header string that appears at the beginning of every
49570 ** SQLite database.
49571 */
49572 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
49573
49574 /*
49575 ** Set this global variable to 1 to enable tracing using the TRACE
49576 ** macro.
49577 */
49578 #if 0
49579 int sqlite3BtreeTrace=1;  /* True to enable tracing */
49580 # define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
49581 #else
49582 # define TRACE(X)
49583 #endif
49584
49585 /*
49586 ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
49587 ** But if the value is zero, make it 65536.
49588 **
49589 ** This routine is used to extract the "offset to cell content area" value
49590 ** from the header of a btree page.  If the page size is 65536 and the page
49591 ** is empty, the offset should be 65536, but the 2-byte value stores zero.
49592 ** This routine makes the necessary adjustment to 65536.
49593 */
49594 #define get2byteNotZero(X)  (((((int)get2byte(X))-1)&0xffff)+1)
49595
49596 /*
49597 ** Values passed as the 5th argument to allocateBtreePage()
49598 */
49599 #define BTALLOC_ANY   0           /* Allocate any page */
49600 #define BTALLOC_EXACT 1           /* Allocate exact page if possible */
49601 #define BTALLOC_LE    2           /* Allocate any page <= the parameter */
49602
49603 /*
49604 ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not 
49605 ** defined, or 0 if it is. For example:
49606 **
49607 **   bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
49608 */
49609 #ifndef SQLITE_OMIT_AUTOVACUUM
49610 #define IfNotOmitAV(expr) (expr)
49611 #else
49612 #define IfNotOmitAV(expr) 0
49613 #endif
49614
49615 #ifndef SQLITE_OMIT_SHARED_CACHE
49616 /*
49617 ** A list of BtShared objects that are eligible for participation
49618 ** in shared cache.  This variable has file scope during normal builds,
49619 ** but the test harness needs to access it so we make it global for 
49620 ** test builds.
49621 **
49622 ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
49623 */
49624 #ifdef SQLITE_TEST
49625 SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
49626 #else
49627 static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
49628 #endif
49629 #endif /* SQLITE_OMIT_SHARED_CACHE */
49630
49631 #ifndef SQLITE_OMIT_SHARED_CACHE
49632 /*
49633 ** Enable or disable the shared pager and schema features.
49634 **
49635 ** This routine has no effect on existing database connections.
49636 ** The shared cache setting effects only future calls to
49637 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
49638 */
49639 SQLITE_API int sqlite3_enable_shared_cache(int enable){
49640   sqlite3GlobalConfig.sharedCacheEnabled = enable;
49641   return SQLITE_OK;
49642 }
49643 #endif
49644
49645
49646
49647 #ifdef SQLITE_OMIT_SHARED_CACHE
49648   /*
49649   ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
49650   ** and clearAllSharedCacheTableLocks()
49651   ** manipulate entries in the BtShared.pLock linked list used to store
49652   ** shared-cache table level locks. If the library is compiled with the
49653   ** shared-cache feature disabled, then there is only ever one user
49654   ** of each BtShared structure and so this locking is not necessary. 
49655   ** So define the lock related functions as no-ops.
49656   */
49657   #define querySharedCacheTableLock(a,b,c) SQLITE_OK
49658   #define setSharedCacheTableLock(a,b,c) SQLITE_OK
49659   #define clearAllSharedCacheTableLocks(a)
49660   #define downgradeAllSharedCacheTableLocks(a)
49661   #define hasSharedCacheTableLock(a,b,c,d) 1
49662   #define hasReadConflicts(a, b) 0
49663 #endif
49664
49665 #ifndef SQLITE_OMIT_SHARED_CACHE
49666
49667 #ifdef SQLITE_DEBUG
49668 /*
49669 **** This function is only used as part of an assert() statement. ***
49670 **
49671 ** Check to see if pBtree holds the required locks to read or write to the 
49672 ** table with root page iRoot.   Return 1 if it does and 0 if not.
49673 **
49674 ** For example, when writing to a table with root-page iRoot via 
49675 ** Btree connection pBtree:
49676 **
49677 **    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
49678 **
49679 ** When writing to an index that resides in a sharable database, the 
49680 ** caller should have first obtained a lock specifying the root page of
49681 ** the corresponding table. This makes things a bit more complicated,
49682 ** as this module treats each table as a separate structure. To determine
49683 ** the table corresponding to the index being written, this
49684 ** function has to search through the database schema.
49685 **
49686 ** Instead of a lock on the table/index rooted at page iRoot, the caller may
49687 ** hold a write-lock on the schema table (root page 1). This is also
49688 ** acceptable.
49689 */
49690 static int hasSharedCacheTableLock(
49691   Btree *pBtree,         /* Handle that must hold lock */
49692   Pgno iRoot,            /* Root page of b-tree */
49693   int isIndex,           /* True if iRoot is the root of an index b-tree */
49694   int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
49695 ){
49696   Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
49697   Pgno iTab = 0;
49698   BtLock *pLock;
49699
49700   /* If this database is not shareable, or if the client is reading
49701   ** and has the read-uncommitted flag set, then no lock is required. 
49702   ** Return true immediately.
49703   */
49704   if( (pBtree->sharable==0)
49705    || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
49706   ){
49707     return 1;
49708   }
49709
49710   /* If the client is reading  or writing an index and the schema is
49711   ** not loaded, then it is too difficult to actually check to see if
49712   ** the correct locks are held.  So do not bother - just return true.
49713   ** This case does not come up very often anyhow.
49714   */
49715   if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){
49716     return 1;
49717   }
49718
49719   /* Figure out the root-page that the lock should be held on. For table
49720   ** b-trees, this is just the root page of the b-tree being read or
49721   ** written. For index b-trees, it is the root page of the associated
49722   ** table.  */
49723   if( isIndex ){
49724     HashElem *p;
49725     for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
49726       Index *pIdx = (Index *)sqliteHashData(p);
49727       if( pIdx->tnum==(int)iRoot ){
49728         iTab = pIdx->pTable->tnum;
49729       }
49730     }
49731   }else{
49732     iTab = iRoot;
49733   }
49734
49735   /* Search for the required lock. Either a write-lock on root-page iTab, a 
49736   ** write-lock on the schema table, or (if the client is reading) a
49737   ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
49738   for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
49739     if( pLock->pBtree==pBtree 
49740      && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
49741      && pLock->eLock>=eLockType 
49742     ){
49743       return 1;
49744     }
49745   }
49746
49747   /* Failed to find the required lock. */
49748   return 0;
49749 }
49750 #endif /* SQLITE_DEBUG */
49751
49752 #ifdef SQLITE_DEBUG
49753 /*
49754 **** This function may be used as part of assert() statements only. ****
49755 **
49756 ** Return true if it would be illegal for pBtree to write into the
49757 ** table or index rooted at iRoot because other shared connections are
49758 ** simultaneously reading that same table or index.
49759 **
49760 ** It is illegal for pBtree to write if some other Btree object that
49761 ** shares the same BtShared object is currently reading or writing
49762 ** the iRoot table.  Except, if the other Btree object has the
49763 ** read-uncommitted flag set, then it is OK for the other object to
49764 ** have a read cursor.
49765 **
49766 ** For example, before writing to any part of the table or index
49767 ** rooted at page iRoot, one should call:
49768 **
49769 **    assert( !hasReadConflicts(pBtree, iRoot) );
49770 */
49771 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
49772   BtCursor *p;
49773   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
49774     if( p->pgnoRoot==iRoot 
49775      && p->pBtree!=pBtree
49776      && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
49777     ){
49778       return 1;
49779     }
49780   }
49781   return 0;
49782 }
49783 #endif    /* #ifdef SQLITE_DEBUG */
49784
49785 /*
49786 ** Query to see if Btree handle p may obtain a lock of type eLock 
49787 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
49788 ** SQLITE_OK if the lock may be obtained (by calling
49789 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
49790 */
49791 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
49792   BtShared *pBt = p->pBt;
49793   BtLock *pIter;
49794
49795   assert( sqlite3BtreeHoldsMutex(p) );
49796   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
49797   assert( p->db!=0 );
49798   assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
49799   
49800   /* If requesting a write-lock, then the Btree must have an open write
49801   ** transaction on this file. And, obviously, for this to be so there 
49802   ** must be an open write transaction on the file itself.
49803   */
49804   assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
49805   assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
49806   
49807   /* This routine is a no-op if the shared-cache is not enabled */
49808   if( !p->sharable ){
49809     return SQLITE_OK;
49810   }
49811
49812   /* If some other connection is holding an exclusive lock, the
49813   ** requested lock may not be obtained.
49814   */
49815   if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
49816     sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
49817     return SQLITE_LOCKED_SHAREDCACHE;
49818   }
49819
49820   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
49821     /* The condition (pIter->eLock!=eLock) in the following if(...) 
49822     ** statement is a simplification of:
49823     **
49824     **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
49825     **
49826     ** since we know that if eLock==WRITE_LOCK, then no other connection
49827     ** may hold a WRITE_LOCK on any table in this file (since there can
49828     ** only be a single writer).
49829     */
49830     assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
49831     assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
49832     if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
49833       sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
49834       if( eLock==WRITE_LOCK ){
49835         assert( p==pBt->pWriter );
49836         pBt->btsFlags |= BTS_PENDING;
49837       }
49838       return SQLITE_LOCKED_SHAREDCACHE;
49839     }
49840   }
49841   return SQLITE_OK;
49842 }
49843 #endif /* !SQLITE_OMIT_SHARED_CACHE */
49844
49845 #ifndef SQLITE_OMIT_SHARED_CACHE
49846 /*
49847 ** Add a lock on the table with root-page iTable to the shared-btree used
49848 ** by Btree handle p. Parameter eLock must be either READ_LOCK or 
49849 ** WRITE_LOCK.
49850 **
49851 ** This function assumes the following:
49852 **
49853 **   (a) The specified Btree object p is connected to a sharable
49854 **       database (one with the BtShared.sharable flag set), and
49855 **
49856 **   (b) No other Btree objects hold a lock that conflicts
49857 **       with the requested lock (i.e. querySharedCacheTableLock() has
49858 **       already been called and returned SQLITE_OK).
49859 **
49860 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM 
49861 ** is returned if a malloc attempt fails.
49862 */
49863 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
49864   BtShared *pBt = p->pBt;
49865   BtLock *pLock = 0;
49866   BtLock *pIter;
49867
49868   assert( sqlite3BtreeHoldsMutex(p) );
49869   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
49870   assert( p->db!=0 );
49871
49872   /* A connection with the read-uncommitted flag set will never try to
49873   ** obtain a read-lock using this function. The only read-lock obtained
49874   ** by a connection in read-uncommitted mode is on the sqlite_master 
49875   ** table, and that lock is obtained in BtreeBeginTrans().  */
49876   assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
49877
49878   /* This function should only be called on a sharable b-tree after it 
49879   ** has been determined that no other b-tree holds a conflicting lock.  */
49880   assert( p->sharable );
49881   assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
49882
49883   /* First search the list for an existing lock on this table. */
49884   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
49885     if( pIter->iTable==iTable && pIter->pBtree==p ){
49886       pLock = pIter;
49887       break;
49888     }
49889   }
49890
49891   /* If the above search did not find a BtLock struct associating Btree p
49892   ** with table iTable, allocate one and link it into the list.
49893   */
49894   if( !pLock ){
49895     pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
49896     if( !pLock ){
49897       return SQLITE_NOMEM;
49898     }
49899     pLock->iTable = iTable;
49900     pLock->pBtree = p;
49901     pLock->pNext = pBt->pLock;
49902     pBt->pLock = pLock;
49903   }
49904
49905   /* Set the BtLock.eLock variable to the maximum of the current lock
49906   ** and the requested lock. This means if a write-lock was already held
49907   ** and a read-lock requested, we don't incorrectly downgrade the lock.
49908   */
49909   assert( WRITE_LOCK>READ_LOCK );
49910   if( eLock>pLock->eLock ){
49911     pLock->eLock = eLock;
49912   }
49913
49914   return SQLITE_OK;
49915 }
49916 #endif /* !SQLITE_OMIT_SHARED_CACHE */
49917
49918 #ifndef SQLITE_OMIT_SHARED_CACHE
49919 /*
49920 ** Release all the table locks (locks obtained via calls to
49921 ** the setSharedCacheTableLock() procedure) held by Btree object p.
49922 **
49923 ** This function assumes that Btree p has an open read or write 
49924 ** transaction. If it does not, then the BTS_PENDING flag
49925 ** may be incorrectly cleared.
49926 */
49927 static void clearAllSharedCacheTableLocks(Btree *p){
49928   BtShared *pBt = p->pBt;
49929   BtLock **ppIter = &pBt->pLock;
49930
49931   assert( sqlite3BtreeHoldsMutex(p) );
49932   assert( p->sharable || 0==*ppIter );
49933   assert( p->inTrans>0 );
49934
49935   while( *ppIter ){
49936     BtLock *pLock = *ppIter;
49937     assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
49938     assert( pLock->pBtree->inTrans>=pLock->eLock );
49939     if( pLock->pBtree==p ){
49940       *ppIter = pLock->pNext;
49941       assert( pLock->iTable!=1 || pLock==&p->lock );
49942       if( pLock->iTable!=1 ){
49943         sqlite3_free(pLock);
49944       }
49945     }else{
49946       ppIter = &pLock->pNext;
49947     }
49948   }
49949
49950   assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
49951   if( pBt->pWriter==p ){
49952     pBt->pWriter = 0;
49953     pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
49954   }else if( pBt->nTransaction==2 ){
49955     /* This function is called when Btree p is concluding its 
49956     ** transaction. If there currently exists a writer, and p is not
49957     ** that writer, then the number of locks held by connections other
49958     ** than the writer must be about to drop to zero. In this case
49959     ** set the BTS_PENDING flag to 0.
49960     **
49961     ** If there is not currently a writer, then BTS_PENDING must
49962     ** be zero already. So this next line is harmless in that case.
49963     */
49964     pBt->btsFlags &= ~BTS_PENDING;
49965   }
49966 }
49967
49968 /*
49969 ** This function changes all write-locks held by Btree p into read-locks.
49970 */
49971 static void downgradeAllSharedCacheTableLocks(Btree *p){
49972   BtShared *pBt = p->pBt;
49973   if( pBt->pWriter==p ){
49974     BtLock *pLock;
49975     pBt->pWriter = 0;
49976     pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
49977     for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
49978       assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
49979       pLock->eLock = READ_LOCK;
49980     }
49981   }
49982 }
49983
49984 #endif /* SQLITE_OMIT_SHARED_CACHE */
49985
49986 static void releasePage(MemPage *pPage);  /* Forward reference */
49987
49988 /*
49989 ***** This routine is used inside of assert() only ****
49990 **
49991 ** Verify that the cursor holds the mutex on its BtShared
49992 */
49993 #ifdef SQLITE_DEBUG
49994 static int cursorHoldsMutex(BtCursor *p){
49995   return sqlite3_mutex_held(p->pBt->mutex);
49996 }
49997 #endif
49998
49999
50000 #ifndef SQLITE_OMIT_INCRBLOB
50001 /*
50002 ** Invalidate the overflow page-list cache for cursor pCur, if any.
50003 */
50004 static void invalidateOverflowCache(BtCursor *pCur){
50005   assert( cursorHoldsMutex(pCur) );
50006   sqlite3_free(pCur->aOverflow);
50007   pCur->aOverflow = 0;
50008 }
50009
50010 /*
50011 ** Invalidate the overflow page-list cache for all cursors opened
50012 ** on the shared btree structure pBt.
50013 */
50014 static void invalidateAllOverflowCache(BtShared *pBt){
50015   BtCursor *p;
50016   assert( sqlite3_mutex_held(pBt->mutex) );
50017   for(p=pBt->pCursor; p; p=p->pNext){
50018     invalidateOverflowCache(p);
50019   }
50020 }
50021
50022 /*
50023 ** This function is called before modifying the contents of a table
50024 ** to invalidate any incrblob cursors that are open on the
50025 ** row or one of the rows being modified.
50026 **
50027 ** If argument isClearTable is true, then the entire contents of the
50028 ** table is about to be deleted. In this case invalidate all incrblob
50029 ** cursors open on any row within the table with root-page pgnoRoot.
50030 **
50031 ** Otherwise, if argument isClearTable is false, then the row with
50032 ** rowid iRow is being replaced or deleted. In this case invalidate
50033 ** only those incrblob cursors open on that specific row.
50034 */
50035 static void invalidateIncrblobCursors(
50036   Btree *pBtree,          /* The database file to check */
50037   i64 iRow,               /* The rowid that might be changing */
50038   int isClearTable        /* True if all rows are being deleted */
50039 ){
50040   BtCursor *p;
50041   BtShared *pBt = pBtree->pBt;
50042   assert( sqlite3BtreeHoldsMutex(pBtree) );
50043   for(p=pBt->pCursor; p; p=p->pNext){
50044     if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
50045       p->eState = CURSOR_INVALID;
50046     }
50047   }
50048 }
50049
50050 #else
50051   /* Stub functions when INCRBLOB is omitted */
50052   #define invalidateOverflowCache(x)
50053   #define invalidateAllOverflowCache(x)
50054   #define invalidateIncrblobCursors(x,y,z)
50055 #endif /* SQLITE_OMIT_INCRBLOB */
50056
50057 /*
50058 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called 
50059 ** when a page that previously contained data becomes a free-list leaf 
50060 ** page.
50061 **
50062 ** The BtShared.pHasContent bitvec exists to work around an obscure
50063 ** bug caused by the interaction of two useful IO optimizations surrounding
50064 ** free-list leaf pages:
50065 **
50066 **   1) When all data is deleted from a page and the page becomes
50067 **      a free-list leaf page, the page is not written to the database
50068 **      (as free-list leaf pages contain no meaningful data). Sometimes
50069 **      such a page is not even journalled (as it will not be modified,
50070 **      why bother journalling it?).
50071 **
50072 **   2) When a free-list leaf page is reused, its content is not read
50073 **      from the database or written to the journal file (why should it
50074 **      be, if it is not at all meaningful?).
50075 **
50076 ** By themselves, these optimizations work fine and provide a handy
50077 ** performance boost to bulk delete or insert operations. However, if
50078 ** a page is moved to the free-list and then reused within the same
50079 ** transaction, a problem comes up. If the page is not journalled when
50080 ** it is moved to the free-list and it is also not journalled when it
50081 ** is extracted from the free-list and reused, then the original data
50082 ** may be lost. In the event of a rollback, it may not be possible
50083 ** to restore the database to its original configuration.
50084 **
50085 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is 
50086 ** moved to become a free-list leaf page, the corresponding bit is
50087 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
50088 ** optimization 2 above is omitted if the corresponding bit is already
50089 ** set in BtShared.pHasContent. The contents of the bitvec are cleared
50090 ** at the end of every transaction.
50091 */
50092 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
50093   int rc = SQLITE_OK;
50094   if( !pBt->pHasContent ){
50095     assert( pgno<=pBt->nPage );
50096     pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
50097     if( !pBt->pHasContent ){
50098       rc = SQLITE_NOMEM;
50099     }
50100   }
50101   if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
50102     rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
50103   }
50104   return rc;
50105 }
50106
50107 /*
50108 ** Query the BtShared.pHasContent vector.
50109 **
50110 ** This function is called when a free-list leaf page is removed from the
50111 ** free-list for reuse. It returns false if it is safe to retrieve the
50112 ** page from the pager layer with the 'no-content' flag set. True otherwise.
50113 */
50114 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
50115   Bitvec *p = pBt->pHasContent;
50116   return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
50117 }
50118
50119 /*
50120 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
50121 ** invoked at the conclusion of each write-transaction.
50122 */
50123 static void btreeClearHasContent(BtShared *pBt){
50124   sqlite3BitvecDestroy(pBt->pHasContent);
50125   pBt->pHasContent = 0;
50126 }
50127
50128 /*
50129 ** Release all of the apPage[] pages for a cursor.
50130 */
50131 static void btreeReleaseAllCursorPages(BtCursor *pCur){
50132   int i;
50133   for(i=0; i<=pCur->iPage; i++){
50134     releasePage(pCur->apPage[i]);
50135     pCur->apPage[i] = 0;
50136   }
50137   pCur->iPage = -1;
50138 }
50139
50140
50141 /*
50142 ** Save the current cursor position in the variables BtCursor.nKey 
50143 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
50144 **
50145 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
50146 ** prior to calling this routine.  
50147 */
50148 static int saveCursorPosition(BtCursor *pCur){
50149   int rc;
50150
50151   assert( CURSOR_VALID==pCur->eState );
50152   assert( 0==pCur->pKey );
50153   assert( cursorHoldsMutex(pCur) );
50154
50155   rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
50156   assert( rc==SQLITE_OK );  /* KeySize() cannot fail */
50157
50158   /* If this is an intKey table, then the above call to BtreeKeySize()
50159   ** stores the integer key in pCur->nKey. In this case this value is
50160   ** all that is required. Otherwise, if pCur is not open on an intKey
50161   ** table, then malloc space for and store the pCur->nKey bytes of key 
50162   ** data.
50163   */
50164   if( 0==pCur->apPage[0]->intKey ){
50165     void *pKey = sqlite3Malloc( (int)pCur->nKey );
50166     if( pKey ){
50167       rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
50168       if( rc==SQLITE_OK ){
50169         pCur->pKey = pKey;
50170       }else{
50171         sqlite3_free(pKey);
50172       }
50173     }else{
50174       rc = SQLITE_NOMEM;
50175     }
50176   }
50177   assert( !pCur->apPage[0]->intKey || !pCur->pKey );
50178
50179   if( rc==SQLITE_OK ){
50180     btreeReleaseAllCursorPages(pCur);
50181     pCur->eState = CURSOR_REQUIRESEEK;
50182   }
50183
50184   invalidateOverflowCache(pCur);
50185   return rc;
50186 }
50187
50188 /*
50189 ** Save the positions of all cursors (except pExcept) that are open on
50190 ** the table  with root-page iRoot. Usually, this is called just before cursor
50191 ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
50192 */
50193 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
50194   BtCursor *p;
50195   assert( sqlite3_mutex_held(pBt->mutex) );
50196   assert( pExcept==0 || pExcept->pBt==pBt );
50197   for(p=pBt->pCursor; p; p=p->pNext){
50198     if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
50199       if( p->eState==CURSOR_VALID ){
50200         int rc = saveCursorPosition(p);
50201         if( SQLITE_OK!=rc ){
50202           return rc;
50203         }
50204       }else{
50205         testcase( p->iPage>0 );
50206         btreeReleaseAllCursorPages(p);
50207       }
50208     }
50209   }
50210   return SQLITE_OK;
50211 }
50212
50213 /*
50214 ** Clear the current cursor position.
50215 */
50216 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
50217   assert( cursorHoldsMutex(pCur) );
50218   sqlite3_free(pCur->pKey);
50219   pCur->pKey = 0;
50220   pCur->eState = CURSOR_INVALID;
50221 }
50222
50223 /*
50224 ** In this version of BtreeMoveto, pKey is a packed index record
50225 ** such as is generated by the OP_MakeRecord opcode.  Unpack the
50226 ** record and then call BtreeMovetoUnpacked() to do the work.
50227 */
50228 static int btreeMoveto(
50229   BtCursor *pCur,     /* Cursor open on the btree to be searched */
50230   const void *pKey,   /* Packed key if the btree is an index */
50231   i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
50232   int bias,           /* Bias search to the high end */
50233   int *pRes           /* Write search results here */
50234 ){
50235   int rc;                    /* Status code */
50236   UnpackedRecord *pIdxKey;   /* Unpacked index key */
50237   char aSpace[150];          /* Temp space for pIdxKey - to avoid a malloc */
50238   char *pFree = 0;
50239
50240   if( pKey ){
50241     assert( nKey==(i64)(int)nKey );
50242     pIdxKey = sqlite3VdbeAllocUnpackedRecord(
50243         pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
50244     );
50245     if( pIdxKey==0 ) return SQLITE_NOMEM;
50246     sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
50247   }else{
50248     pIdxKey = 0;
50249   }
50250   rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
50251   if( pFree ){
50252     sqlite3DbFree(pCur->pKeyInfo->db, pFree);
50253   }
50254   return rc;
50255 }
50256
50257 /*
50258 ** Restore the cursor to the position it was in (or as close to as possible)
50259 ** when saveCursorPosition() was called. Note that this call deletes the 
50260 ** saved position info stored by saveCursorPosition(), so there can be
50261 ** at most one effective restoreCursorPosition() call after each 
50262 ** saveCursorPosition().
50263 */
50264 static int btreeRestoreCursorPosition(BtCursor *pCur){
50265   int rc;
50266   assert( cursorHoldsMutex(pCur) );
50267   assert( pCur->eState>=CURSOR_REQUIRESEEK );
50268   if( pCur->eState==CURSOR_FAULT ){
50269     return pCur->skipNext;
50270   }
50271   pCur->eState = CURSOR_INVALID;
50272   rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
50273   if( rc==SQLITE_OK ){
50274     sqlite3_free(pCur->pKey);
50275     pCur->pKey = 0;
50276     assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
50277   }
50278   return rc;
50279 }
50280
50281 #define restoreCursorPosition(p) \
50282   (p->eState>=CURSOR_REQUIRESEEK ? \
50283          btreeRestoreCursorPosition(p) : \
50284          SQLITE_OK)
50285
50286 /*
50287 ** Determine whether or not a cursor has moved from the position it
50288 ** was last placed at.  Cursors can move when the row they are pointing
50289 ** at is deleted out from under them.
50290 **
50291 ** This routine returns an error code if something goes wrong.  The
50292 ** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
50293 */
50294 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
50295   int rc;
50296
50297   rc = restoreCursorPosition(pCur);
50298   if( rc ){
50299     *pHasMoved = 1;
50300     return rc;
50301   }
50302   if( pCur->eState!=CURSOR_VALID || pCur->skipNext!=0 ){
50303     *pHasMoved = 1;
50304   }else{
50305     *pHasMoved = 0;
50306   }
50307   return SQLITE_OK;
50308 }
50309
50310 #ifndef SQLITE_OMIT_AUTOVACUUM
50311 /*
50312 ** Given a page number of a regular database page, return the page
50313 ** number for the pointer-map page that contains the entry for the
50314 ** input page number.
50315 **
50316 ** Return 0 (not a valid page) for pgno==1 since there is
50317 ** no pointer map associated with page 1.  The integrity_check logic
50318 ** requires that ptrmapPageno(*,1)!=1.
50319 */
50320 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
50321   int nPagesPerMapPage;
50322   Pgno iPtrMap, ret;
50323   assert( sqlite3_mutex_held(pBt->mutex) );
50324   if( pgno<2 ) return 0;
50325   nPagesPerMapPage = (pBt->usableSize/5)+1;
50326   iPtrMap = (pgno-2)/nPagesPerMapPage;
50327   ret = (iPtrMap*nPagesPerMapPage) + 2; 
50328   if( ret==PENDING_BYTE_PAGE(pBt) ){
50329     ret++;
50330   }
50331   return ret;
50332 }
50333
50334 /*
50335 ** Write an entry into the pointer map.
50336 **
50337 ** This routine updates the pointer map entry for page number 'key'
50338 ** so that it maps to type 'eType' and parent page number 'pgno'.
50339 **
50340 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
50341 ** a no-op.  If an error occurs, the appropriate error code is written
50342 ** into *pRC.
50343 */
50344 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
50345   DbPage *pDbPage;  /* The pointer map page */
50346   u8 *pPtrmap;      /* The pointer map data */
50347   Pgno iPtrmap;     /* The pointer map page number */
50348   int offset;       /* Offset in pointer map page */
50349   int rc;           /* Return code from subfunctions */
50350
50351   if( *pRC ) return;
50352
50353   assert( sqlite3_mutex_held(pBt->mutex) );
50354   /* The master-journal page number must never be used as a pointer map page */
50355   assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
50356
50357   assert( pBt->autoVacuum );
50358   if( key==0 ){
50359     *pRC = SQLITE_CORRUPT_BKPT;
50360     return;
50361   }
50362   iPtrmap = PTRMAP_PAGENO(pBt, key);
50363   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
50364   if( rc!=SQLITE_OK ){
50365     *pRC = rc;
50366     return;
50367   }
50368   offset = PTRMAP_PTROFFSET(iPtrmap, key);
50369   if( offset<0 ){
50370     *pRC = SQLITE_CORRUPT_BKPT;
50371     goto ptrmap_exit;
50372   }
50373   assert( offset <= (int)pBt->usableSize-5 );
50374   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
50375
50376   if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
50377     TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
50378     *pRC= rc = sqlite3PagerWrite(pDbPage);
50379     if( rc==SQLITE_OK ){
50380       pPtrmap[offset] = eType;
50381       put4byte(&pPtrmap[offset+1], parent);
50382     }
50383   }
50384
50385 ptrmap_exit:
50386   sqlite3PagerUnref(pDbPage);
50387 }
50388
50389 /*
50390 ** Read an entry from the pointer map.
50391 **
50392 ** This routine retrieves the pointer map entry for page 'key', writing
50393 ** the type and parent page number to *pEType and *pPgno respectively.
50394 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
50395 */
50396 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
50397   DbPage *pDbPage;   /* The pointer map page */
50398   int iPtrmap;       /* Pointer map page index */
50399   u8 *pPtrmap;       /* Pointer map page data */
50400   int offset;        /* Offset of entry in pointer map */
50401   int rc;
50402
50403   assert( sqlite3_mutex_held(pBt->mutex) );
50404
50405   iPtrmap = PTRMAP_PAGENO(pBt, key);
50406   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
50407   if( rc!=0 ){
50408     return rc;
50409   }
50410   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
50411
50412   offset = PTRMAP_PTROFFSET(iPtrmap, key);
50413   if( offset<0 ){
50414     sqlite3PagerUnref(pDbPage);
50415     return SQLITE_CORRUPT_BKPT;
50416   }
50417   assert( offset <= (int)pBt->usableSize-5 );
50418   assert( pEType!=0 );
50419   *pEType = pPtrmap[offset];
50420   if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
50421
50422   sqlite3PagerUnref(pDbPage);
50423   if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
50424   return SQLITE_OK;
50425 }
50426
50427 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
50428   #define ptrmapPut(w,x,y,z,rc)
50429   #define ptrmapGet(w,x,y,z) SQLITE_OK
50430   #define ptrmapPutOvflPtr(x, y, rc)
50431 #endif
50432
50433 /*
50434 ** Given a btree page and a cell index (0 means the first cell on
50435 ** the page, 1 means the second cell, and so forth) return a pointer
50436 ** to the cell content.
50437 **
50438 ** This routine works only for pages that do not contain overflow cells.
50439 */
50440 #define findCell(P,I) \
50441   ((P)->aData + ((P)->maskPage & get2byte(&(P)->aCellIdx[2*(I)])))
50442 #define findCellv2(D,M,O,I) (D+(M&get2byte(D+(O+2*(I)))))
50443
50444
50445 /*
50446 ** This a more complex version of findCell() that works for
50447 ** pages that do contain overflow cells.
50448 */
50449 static u8 *findOverflowCell(MemPage *pPage, int iCell){
50450   int i;
50451   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50452   for(i=pPage->nOverflow-1; i>=0; i--){
50453     int k;
50454     k = pPage->aiOvfl[i];
50455     if( k<=iCell ){
50456       if( k==iCell ){
50457         return pPage->apOvfl[i];
50458       }
50459       iCell--;
50460     }
50461   }
50462   return findCell(pPage, iCell);
50463 }
50464
50465 /*
50466 ** Parse a cell content block and fill in the CellInfo structure.  There
50467 ** are two versions of this function.  btreeParseCell() takes a 
50468 ** cell index as the second argument and btreeParseCellPtr() 
50469 ** takes a pointer to the body of the cell as its second argument.
50470 **
50471 ** Within this file, the parseCell() macro can be called instead of
50472 ** btreeParseCellPtr(). Using some compilers, this will be faster.
50473 */
50474 static void btreeParseCellPtr(
50475   MemPage *pPage,         /* Page containing the cell */
50476   u8 *pCell,              /* Pointer to the cell text. */
50477   CellInfo *pInfo         /* Fill in this structure */
50478 ){
50479   u16 n;                  /* Number bytes in cell content header */
50480   u32 nPayload;           /* Number of bytes of cell payload */
50481
50482   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50483
50484   pInfo->pCell = pCell;
50485   assert( pPage->leaf==0 || pPage->leaf==1 );
50486   n = pPage->childPtrSize;
50487   assert( n==4-4*pPage->leaf );
50488   if( pPage->intKey ){
50489     if( pPage->hasData ){
50490       n += getVarint32(&pCell[n], nPayload);
50491     }else{
50492       nPayload = 0;
50493     }
50494     n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
50495     pInfo->nData = nPayload;
50496   }else{
50497     pInfo->nData = 0;
50498     n += getVarint32(&pCell[n], nPayload);
50499     pInfo->nKey = nPayload;
50500   }
50501   pInfo->nPayload = nPayload;
50502   pInfo->nHeader = n;
50503   testcase( nPayload==pPage->maxLocal );
50504   testcase( nPayload==pPage->maxLocal+1 );
50505   if( likely(nPayload<=pPage->maxLocal) ){
50506     /* This is the (easy) common case where the entire payload fits
50507     ** on the local page.  No overflow is required.
50508     */
50509     if( (pInfo->nSize = (u16)(n+nPayload))<4 ) pInfo->nSize = 4;
50510     pInfo->nLocal = (u16)nPayload;
50511     pInfo->iOverflow = 0;
50512   }else{
50513     /* If the payload will not fit completely on the local page, we have
50514     ** to decide how much to store locally and how much to spill onto
50515     ** overflow pages.  The strategy is to minimize the amount of unused
50516     ** space on overflow pages while keeping the amount of local storage
50517     ** in between minLocal and maxLocal.
50518     **
50519     ** Warning:  changing the way overflow payload is distributed in any
50520     ** way will result in an incompatible file format.
50521     */
50522     int minLocal;  /* Minimum amount of payload held locally */
50523     int maxLocal;  /* Maximum amount of payload held locally */
50524     int surplus;   /* Overflow payload available for local storage */
50525
50526     minLocal = pPage->minLocal;
50527     maxLocal = pPage->maxLocal;
50528     surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
50529     testcase( surplus==maxLocal );
50530     testcase( surplus==maxLocal+1 );
50531     if( surplus <= maxLocal ){
50532       pInfo->nLocal = (u16)surplus;
50533     }else{
50534       pInfo->nLocal = (u16)minLocal;
50535     }
50536     pInfo->iOverflow = (u16)(pInfo->nLocal + n);
50537     pInfo->nSize = pInfo->iOverflow + 4;
50538   }
50539 }
50540 #define parseCell(pPage, iCell, pInfo) \
50541   btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
50542 static void btreeParseCell(
50543   MemPage *pPage,         /* Page containing the cell */
50544   int iCell,              /* The cell index.  First cell is 0 */
50545   CellInfo *pInfo         /* Fill in this structure */
50546 ){
50547   parseCell(pPage, iCell, pInfo);
50548 }
50549
50550 /*
50551 ** Compute the total number of bytes that a Cell needs in the cell
50552 ** data area of the btree-page.  The return number includes the cell
50553 ** data header and the local payload, but not any overflow page or
50554 ** the space used by the cell pointer.
50555 */
50556 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
50557   u8 *pIter = &pCell[pPage->childPtrSize];
50558   u32 nSize;
50559
50560 #ifdef SQLITE_DEBUG
50561   /* The value returned by this function should always be the same as
50562   ** the (CellInfo.nSize) value found by doing a full parse of the
50563   ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
50564   ** this function verifies that this invariant is not violated. */
50565   CellInfo debuginfo;
50566   btreeParseCellPtr(pPage, pCell, &debuginfo);
50567 #endif
50568
50569   if( pPage->intKey ){
50570     u8 *pEnd;
50571     if( pPage->hasData ){
50572       pIter += getVarint32(pIter, nSize);
50573     }else{
50574       nSize = 0;
50575     }
50576
50577     /* pIter now points at the 64-bit integer key value, a variable length 
50578     ** integer. The following block moves pIter to point at the first byte
50579     ** past the end of the key value. */
50580     pEnd = &pIter[9];
50581     while( (*pIter++)&0x80 && pIter<pEnd );
50582   }else{
50583     pIter += getVarint32(pIter, nSize);
50584   }
50585
50586   testcase( nSize==pPage->maxLocal );
50587   testcase( nSize==pPage->maxLocal+1 );
50588   if( nSize>pPage->maxLocal ){
50589     int minLocal = pPage->minLocal;
50590     nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
50591     testcase( nSize==pPage->maxLocal );
50592     testcase( nSize==pPage->maxLocal+1 );
50593     if( nSize>pPage->maxLocal ){
50594       nSize = minLocal;
50595     }
50596     nSize += 4;
50597   }
50598   nSize += (u32)(pIter - pCell);
50599
50600   /* The minimum size of any cell is 4 bytes. */
50601   if( nSize<4 ){
50602     nSize = 4;
50603   }
50604
50605   assert( nSize==debuginfo.nSize );
50606   return (u16)nSize;
50607 }
50608
50609 #ifdef SQLITE_DEBUG
50610 /* This variation on cellSizePtr() is used inside of assert() statements
50611 ** only. */
50612 static u16 cellSize(MemPage *pPage, int iCell){
50613   return cellSizePtr(pPage, findCell(pPage, iCell));
50614 }
50615 #endif
50616
50617 #ifndef SQLITE_OMIT_AUTOVACUUM
50618 /*
50619 ** If the cell pCell, part of page pPage contains a pointer
50620 ** to an overflow page, insert an entry into the pointer-map
50621 ** for the overflow page.
50622 */
50623 static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
50624   CellInfo info;
50625   if( *pRC ) return;
50626   assert( pCell!=0 );
50627   btreeParseCellPtr(pPage, pCell, &info);
50628   assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
50629   if( info.iOverflow ){
50630     Pgno ovfl = get4byte(&pCell[info.iOverflow]);
50631     ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
50632   }
50633 }
50634 #endif
50635
50636
50637 /*
50638 ** Defragment the page given.  All Cells are moved to the
50639 ** end of the page and all free space is collected into one
50640 ** big FreeBlk that occurs in between the header and cell
50641 ** pointer array and the cell content area.
50642 */
50643 static int defragmentPage(MemPage *pPage){
50644   int i;                     /* Loop counter */
50645   int pc;                    /* Address of a i-th cell */
50646   int hdr;                   /* Offset to the page header */
50647   int size;                  /* Size of a cell */
50648   int usableSize;            /* Number of usable bytes on a page */
50649   int cellOffset;            /* Offset to the cell pointer array */
50650   int cbrk;                  /* Offset to the cell content area */
50651   int nCell;                 /* Number of cells on the page */
50652   unsigned char *data;       /* The page data */
50653   unsigned char *temp;       /* Temp area for cell content */
50654   int iCellFirst;            /* First allowable cell index */
50655   int iCellLast;             /* Last possible cell index */
50656
50657
50658   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
50659   assert( pPage->pBt!=0 );
50660   assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
50661   assert( pPage->nOverflow==0 );
50662   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50663   temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
50664   data = pPage->aData;
50665   hdr = pPage->hdrOffset;
50666   cellOffset = pPage->cellOffset;
50667   nCell = pPage->nCell;
50668   assert( nCell==get2byte(&data[hdr+3]) );
50669   usableSize = pPage->pBt->usableSize;
50670   cbrk = get2byte(&data[hdr+5]);
50671   memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
50672   cbrk = usableSize;
50673   iCellFirst = cellOffset + 2*nCell;
50674   iCellLast = usableSize - 4;
50675   for(i=0; i<nCell; i++){
50676     u8 *pAddr;     /* The i-th cell pointer */
50677     pAddr = &data[cellOffset + i*2];
50678     pc = get2byte(pAddr);
50679     testcase( pc==iCellFirst );
50680     testcase( pc==iCellLast );
50681 #if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
50682     /* These conditions have already been verified in btreeInitPage()
50683     ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined 
50684     */
50685     if( pc<iCellFirst || pc>iCellLast ){
50686       return SQLITE_CORRUPT_BKPT;
50687     }
50688 #endif
50689     assert( pc>=iCellFirst && pc<=iCellLast );
50690     size = cellSizePtr(pPage, &temp[pc]);
50691     cbrk -= size;
50692 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
50693     if( cbrk<iCellFirst ){
50694       return SQLITE_CORRUPT_BKPT;
50695     }
50696 #else
50697     if( cbrk<iCellFirst || pc+size>usableSize ){
50698       return SQLITE_CORRUPT_BKPT;
50699     }
50700 #endif
50701     assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
50702     testcase( cbrk+size==usableSize );
50703     testcase( pc+size==usableSize );
50704     memcpy(&data[cbrk], &temp[pc], size);
50705     put2byte(pAddr, cbrk);
50706   }
50707   assert( cbrk>=iCellFirst );
50708   put2byte(&data[hdr+5], cbrk);
50709   data[hdr+1] = 0;
50710   data[hdr+2] = 0;
50711   data[hdr+7] = 0;
50712   memset(&data[iCellFirst], 0, cbrk-iCellFirst);
50713   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
50714   if( cbrk-iCellFirst!=pPage->nFree ){
50715     return SQLITE_CORRUPT_BKPT;
50716   }
50717   return SQLITE_OK;
50718 }
50719
50720 /*
50721 ** Allocate nByte bytes of space from within the B-Tree page passed
50722 ** as the first argument. Write into *pIdx the index into pPage->aData[]
50723 ** of the first byte of allocated space. Return either SQLITE_OK or
50724 ** an error code (usually SQLITE_CORRUPT).
50725 **
50726 ** The caller guarantees that there is sufficient space to make the
50727 ** allocation.  This routine might need to defragment in order to bring
50728 ** all the space together, however.  This routine will avoid using
50729 ** the first two bytes past the cell pointer area since presumably this
50730 ** allocation is being made in order to insert a new cell, so we will
50731 ** also end up needing a new cell pointer.
50732 */
50733 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
50734   const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
50735   u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
50736   int nFrag;                           /* Number of fragmented bytes on pPage */
50737   int top;                             /* First byte of cell content area */
50738   int gap;        /* First byte of gap between cell pointers and cell content */
50739   int rc;         /* Integer return code */
50740   int usableSize; /* Usable size of the page */
50741   
50742   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
50743   assert( pPage->pBt );
50744   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50745   assert( nByte>=0 );  /* Minimum cell size is 4 */
50746   assert( pPage->nFree>=nByte );
50747   assert( pPage->nOverflow==0 );
50748   usableSize = pPage->pBt->usableSize;
50749   assert( nByte < usableSize-8 );
50750
50751   nFrag = data[hdr+7];
50752   assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
50753   gap = pPage->cellOffset + 2*pPage->nCell;
50754   top = get2byteNotZero(&data[hdr+5]);
50755   if( gap>top ) return SQLITE_CORRUPT_BKPT;
50756   testcase( gap+2==top );
50757   testcase( gap+1==top );
50758   testcase( gap==top );
50759
50760   if( nFrag>=60 ){
50761     /* Always defragment highly fragmented pages */
50762     rc = defragmentPage(pPage);
50763     if( rc ) return rc;
50764     top = get2byteNotZero(&data[hdr+5]);
50765   }else if( gap+2<=top ){
50766     /* Search the freelist looking for a free slot big enough to satisfy 
50767     ** the request. The allocation is made from the first free slot in 
50768     ** the list that is large enough to accomadate it.
50769     */
50770     int pc, addr;
50771     for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
50772       int size;            /* Size of the free slot */
50773       if( pc>usableSize-4 || pc<addr+4 ){
50774         return SQLITE_CORRUPT_BKPT;
50775       }
50776       size = get2byte(&data[pc+2]);
50777       if( size>=nByte ){
50778         int x = size - nByte;
50779         testcase( x==4 );
50780         testcase( x==3 );
50781         if( x<4 ){
50782           /* Remove the slot from the free-list. Update the number of
50783           ** fragmented bytes within the page. */
50784           memcpy(&data[addr], &data[pc], 2);
50785           data[hdr+7] = (u8)(nFrag + x);
50786         }else if( size+pc > usableSize ){
50787           return SQLITE_CORRUPT_BKPT;
50788         }else{
50789           /* The slot remains on the free-list. Reduce its size to account
50790           ** for the portion used by the new allocation. */
50791           put2byte(&data[pc+2], x);
50792         }
50793         *pIdx = pc + x;
50794         return SQLITE_OK;
50795       }
50796     }
50797   }
50798
50799   /* Check to make sure there is enough space in the gap to satisfy
50800   ** the allocation.  If not, defragment.
50801   */
50802   testcase( gap+2+nByte==top );
50803   if( gap+2+nByte>top ){
50804     rc = defragmentPage(pPage);
50805     if( rc ) return rc;
50806     top = get2byteNotZero(&data[hdr+5]);
50807     assert( gap+nByte<=top );
50808   }
50809
50810
50811   /* Allocate memory from the gap in between the cell pointer array
50812   ** and the cell content area.  The btreeInitPage() call has already
50813   ** validated the freelist.  Given that the freelist is valid, there
50814   ** is no way that the allocation can extend off the end of the page.
50815   ** The assert() below verifies the previous sentence.
50816   */
50817   top -= nByte;
50818   put2byte(&data[hdr+5], top);
50819   assert( top+nByte <= (int)pPage->pBt->usableSize );
50820   *pIdx = top;
50821   return SQLITE_OK;
50822 }
50823
50824 /*
50825 ** Return a section of the pPage->aData to the freelist.
50826 ** The first byte of the new free block is pPage->aDisk[start]
50827 ** and the size of the block is "size" bytes.
50828 **
50829 ** Most of the effort here is involved in coalesing adjacent
50830 ** free blocks into a single big free block.
50831 */
50832 static int freeSpace(MemPage *pPage, int start, int size){
50833   int addr, pbegin, hdr;
50834   int iLast;                        /* Largest possible freeblock offset */
50835   unsigned char *data = pPage->aData;
50836
50837   assert( pPage->pBt!=0 );
50838   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
50839   assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
50840   assert( (start + size) <= (int)pPage->pBt->usableSize );
50841   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50842   assert( size>=0 );   /* Minimum cell size is 4 */
50843
50844   if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
50845     /* Overwrite deleted information with zeros when the secure_delete
50846     ** option is enabled */
50847     memset(&data[start], 0, size);
50848   }
50849
50850   /* Add the space back into the linked list of freeblocks.  Note that
50851   ** even though the freeblock list was checked by btreeInitPage(),
50852   ** btreeInitPage() did not detect overlapping cells or
50853   ** freeblocks that overlapped cells.   Nor does it detect when the
50854   ** cell content area exceeds the value in the page header.  If these
50855   ** situations arise, then subsequent insert operations might corrupt
50856   ** the freelist.  So we do need to check for corruption while scanning
50857   ** the freelist.
50858   */
50859   hdr = pPage->hdrOffset;
50860   addr = hdr + 1;
50861   iLast = pPage->pBt->usableSize - 4;
50862   assert( start<=iLast );
50863   while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
50864     if( pbegin<addr+4 ){
50865       return SQLITE_CORRUPT_BKPT;
50866     }
50867     addr = pbegin;
50868   }
50869   if( pbegin>iLast ){
50870     return SQLITE_CORRUPT_BKPT;
50871   }
50872   assert( pbegin>addr || pbegin==0 );
50873   put2byte(&data[addr], start);
50874   put2byte(&data[start], pbegin);
50875   put2byte(&data[start+2], size);
50876   pPage->nFree = pPage->nFree + (u16)size;
50877
50878   /* Coalesce adjacent free blocks */
50879   addr = hdr + 1;
50880   while( (pbegin = get2byte(&data[addr]))>0 ){
50881     int pnext, psize, x;
50882     assert( pbegin>addr );
50883     assert( pbegin <= (int)pPage->pBt->usableSize-4 );
50884     pnext = get2byte(&data[pbegin]);
50885     psize = get2byte(&data[pbegin+2]);
50886     if( pbegin + psize + 3 >= pnext && pnext>0 ){
50887       int frag = pnext - (pbegin+psize);
50888       if( (frag<0) || (frag>(int)data[hdr+7]) ){
50889         return SQLITE_CORRUPT_BKPT;
50890       }
50891       data[hdr+7] -= (u8)frag;
50892       x = get2byte(&data[pnext]);
50893       put2byte(&data[pbegin], x);
50894       x = pnext + get2byte(&data[pnext+2]) - pbegin;
50895       put2byte(&data[pbegin+2], x);
50896     }else{
50897       addr = pbegin;
50898     }
50899   }
50900
50901   /* If the cell content area begins with a freeblock, remove it. */
50902   if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
50903     int top;
50904     pbegin = get2byte(&data[hdr+1]);
50905     memcpy(&data[hdr+1], &data[pbegin], 2);
50906     top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
50907     put2byte(&data[hdr+5], top);
50908   }
50909   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
50910   return SQLITE_OK;
50911 }
50912
50913 /*
50914 ** Decode the flags byte (the first byte of the header) for a page
50915 ** and initialize fields of the MemPage structure accordingly.
50916 **
50917 ** Only the following combinations are supported.  Anything different
50918 ** indicates a corrupt database files:
50919 **
50920 **         PTF_ZERODATA
50921 **         PTF_ZERODATA | PTF_LEAF
50922 **         PTF_LEAFDATA | PTF_INTKEY
50923 **         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
50924 */
50925 static int decodeFlags(MemPage *pPage, int flagByte){
50926   BtShared *pBt;     /* A copy of pPage->pBt */
50927
50928   assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
50929   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50930   pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
50931   flagByte &= ~PTF_LEAF;
50932   pPage->childPtrSize = 4-4*pPage->leaf;
50933   pBt = pPage->pBt;
50934   if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
50935     pPage->intKey = 1;
50936     pPage->hasData = pPage->leaf;
50937     pPage->maxLocal = pBt->maxLeaf;
50938     pPage->minLocal = pBt->minLeaf;
50939   }else if( flagByte==PTF_ZERODATA ){
50940     pPage->intKey = 0;
50941     pPage->hasData = 0;
50942     pPage->maxLocal = pBt->maxLocal;
50943     pPage->minLocal = pBt->minLocal;
50944   }else{
50945     return SQLITE_CORRUPT_BKPT;
50946   }
50947   pPage->max1bytePayload = pBt->max1bytePayload;
50948   return SQLITE_OK;
50949 }
50950
50951 /*
50952 ** Initialize the auxiliary information for a disk block.
50953 **
50954 ** Return SQLITE_OK on success.  If we see that the page does
50955 ** not contain a well-formed database page, then return 
50956 ** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
50957 ** guarantee that the page is well-formed.  It only shows that
50958 ** we failed to detect any corruption.
50959 */
50960 static int btreeInitPage(MemPage *pPage){
50961
50962   assert( pPage->pBt!=0 );
50963   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
50964   assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
50965   assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
50966   assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
50967
50968   if( !pPage->isInit ){
50969     u16 pc;            /* Address of a freeblock within pPage->aData[] */
50970     u8 hdr;            /* Offset to beginning of page header */
50971     u8 *data;          /* Equal to pPage->aData */
50972     BtShared *pBt;        /* The main btree structure */
50973     int usableSize;    /* Amount of usable space on each page */
50974     u16 cellOffset;    /* Offset from start of page to first cell pointer */
50975     int nFree;         /* Number of unused bytes on the page */
50976     int top;           /* First byte of the cell content area */
50977     int iCellFirst;    /* First allowable cell or freeblock offset */
50978     int iCellLast;     /* Last possible cell or freeblock offset */
50979
50980     pBt = pPage->pBt;
50981
50982     hdr = pPage->hdrOffset;
50983     data = pPage->aData;
50984     if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
50985     assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
50986     pPage->maskPage = (u16)(pBt->pageSize - 1);
50987     pPage->nOverflow = 0;
50988     usableSize = pBt->usableSize;
50989     pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
50990     pPage->aDataEnd = &data[usableSize];
50991     pPage->aCellIdx = &data[cellOffset];
50992     top = get2byteNotZero(&data[hdr+5]);
50993     pPage->nCell = get2byte(&data[hdr+3]);
50994     if( pPage->nCell>MX_CELL(pBt) ){
50995       /* To many cells for a single page.  The page must be corrupt */
50996       return SQLITE_CORRUPT_BKPT;
50997     }
50998     testcase( pPage->nCell==MX_CELL(pBt) );
50999
51000     /* A malformed database page might cause us to read past the end
51001     ** of page when parsing a cell.  
51002     **
51003     ** The following block of code checks early to see if a cell extends
51004     ** past the end of a page boundary and causes SQLITE_CORRUPT to be 
51005     ** returned if it does.
51006     */
51007     iCellFirst = cellOffset + 2*pPage->nCell;
51008     iCellLast = usableSize - 4;
51009 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
51010     {
51011       int i;            /* Index into the cell pointer array */
51012       int sz;           /* Size of a cell */
51013
51014       if( !pPage->leaf ) iCellLast--;
51015       for(i=0; i<pPage->nCell; i++){
51016         pc = get2byte(&data[cellOffset+i*2]);
51017         testcase( pc==iCellFirst );
51018         testcase( pc==iCellLast );
51019         if( pc<iCellFirst || pc>iCellLast ){
51020           return SQLITE_CORRUPT_BKPT;
51021         }
51022         sz = cellSizePtr(pPage, &data[pc]);
51023         testcase( pc+sz==usableSize );
51024         if( pc+sz>usableSize ){
51025           return SQLITE_CORRUPT_BKPT;
51026         }
51027       }
51028       if( !pPage->leaf ) iCellLast++;
51029     }  
51030 #endif
51031
51032     /* Compute the total free space on the page */
51033     pc = get2byte(&data[hdr+1]);
51034     nFree = data[hdr+7] + top;
51035     while( pc>0 ){
51036       u16 next, size;
51037       if( pc<iCellFirst || pc>iCellLast ){
51038         /* Start of free block is off the page */
51039         return SQLITE_CORRUPT_BKPT; 
51040       }
51041       next = get2byte(&data[pc]);
51042       size = get2byte(&data[pc+2]);
51043       if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
51044         /* Free blocks must be in ascending order. And the last byte of
51045         ** the free-block must lie on the database page.  */
51046         return SQLITE_CORRUPT_BKPT; 
51047       }
51048       nFree = nFree + size;
51049       pc = next;
51050     }
51051
51052     /* At this point, nFree contains the sum of the offset to the start
51053     ** of the cell-content area plus the number of free bytes within
51054     ** the cell-content area. If this is greater than the usable-size
51055     ** of the page, then the page must be corrupted. This check also
51056     ** serves to verify that the offset to the start of the cell-content
51057     ** area, according to the page header, lies within the page.
51058     */
51059     if( nFree>usableSize ){
51060       return SQLITE_CORRUPT_BKPT; 
51061     }
51062     pPage->nFree = (u16)(nFree - iCellFirst);
51063     pPage->isInit = 1;
51064   }
51065   return SQLITE_OK;
51066 }
51067
51068 /*
51069 ** Set up a raw page so that it looks like a database page holding
51070 ** no entries.
51071 */
51072 static void zeroPage(MemPage *pPage, int flags){
51073   unsigned char *data = pPage->aData;
51074   BtShared *pBt = pPage->pBt;
51075   u8 hdr = pPage->hdrOffset;
51076   u16 first;
51077
51078   assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
51079   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
51080   assert( sqlite3PagerGetData(pPage->pDbPage) == data );
51081   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
51082   assert( sqlite3_mutex_held(pBt->mutex) );
51083   if( pBt->btsFlags & BTS_SECURE_DELETE ){
51084     memset(&data[hdr], 0, pBt->usableSize - hdr);
51085   }
51086   data[hdr] = (char)flags;
51087   first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
51088   memset(&data[hdr+1], 0, 4);
51089   data[hdr+7] = 0;
51090   put2byte(&data[hdr+5], pBt->usableSize);
51091   pPage->nFree = (u16)(pBt->usableSize - first);
51092   decodeFlags(pPage, flags);
51093   pPage->hdrOffset = hdr;
51094   pPage->cellOffset = first;
51095   pPage->aDataEnd = &data[pBt->usableSize];
51096   pPage->aCellIdx = &data[first];
51097   pPage->nOverflow = 0;
51098   assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
51099   pPage->maskPage = (u16)(pBt->pageSize - 1);
51100   pPage->nCell = 0;
51101   pPage->isInit = 1;
51102 }
51103
51104
51105 /*
51106 ** Convert a DbPage obtained from the pager into a MemPage used by
51107 ** the btree layer.
51108 */
51109 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
51110   MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
51111   pPage->aData = sqlite3PagerGetData(pDbPage);
51112   pPage->pDbPage = pDbPage;
51113   pPage->pBt = pBt;
51114   pPage->pgno = pgno;
51115   pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
51116   return pPage; 
51117 }
51118
51119 /*
51120 ** Get a page from the pager.  Initialize the MemPage.pBt and
51121 ** MemPage.aData elements if needed.
51122 **
51123 ** If the noContent flag is set, it means that we do not care about
51124 ** the content of the page at this time.  So do not go to the disk
51125 ** to fetch the content.  Just fill in the content with zeros for now.
51126 ** If in the future we call sqlite3PagerWrite() on this page, that
51127 ** means we have started to be concerned about content and the disk
51128 ** read should occur at that point.
51129 */
51130 static int btreeGetPage(
51131   BtShared *pBt,       /* The btree */
51132   Pgno pgno,           /* Number of the page to fetch */
51133   MemPage **ppPage,    /* Return the page in this parameter */
51134   int noContent,       /* Do not load page content if true */
51135   int bReadonly        /* True if a read-only (mmap) page is ok */
51136 ){
51137   int rc;
51138   DbPage *pDbPage;
51139   int flags = (noContent ? PAGER_ACQUIRE_NOCONTENT : 0) 
51140             | (bReadonly ? PAGER_ACQUIRE_READONLY : 0);
51141
51142   assert( noContent==0 || bReadonly==0 );
51143   assert( sqlite3_mutex_held(pBt->mutex) );
51144   rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
51145   if( rc ) return rc;
51146   *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
51147   return SQLITE_OK;
51148 }
51149
51150 /*
51151 ** Retrieve a page from the pager cache. If the requested page is not
51152 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
51153 ** MemPage.aData elements if needed.
51154 */
51155 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
51156   DbPage *pDbPage;
51157   assert( sqlite3_mutex_held(pBt->mutex) );
51158   pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
51159   if( pDbPage ){
51160     return btreePageFromDbPage(pDbPage, pgno, pBt);
51161   }
51162   return 0;
51163 }
51164
51165 /*
51166 ** Return the size of the database file in pages. If there is any kind of
51167 ** error, return ((unsigned int)-1).
51168 */
51169 static Pgno btreePagecount(BtShared *pBt){
51170   return pBt->nPage;
51171 }
51172 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
51173   assert( sqlite3BtreeHoldsMutex(p) );
51174   assert( ((p->pBt->nPage)&0x8000000)==0 );
51175   return (int)btreePagecount(p->pBt);
51176 }
51177
51178 /*
51179 ** Get a page from the pager and initialize it.  This routine is just a
51180 ** convenience wrapper around separate calls to btreeGetPage() and 
51181 ** btreeInitPage().
51182 **
51183 ** If an error occurs, then the value *ppPage is set to is undefined. It
51184 ** may remain unchanged, or it may be set to an invalid value.
51185 */
51186 static int getAndInitPage(
51187   BtShared *pBt,                  /* The database file */
51188   Pgno pgno,                      /* Number of the page to get */
51189   MemPage **ppPage,               /* Write the page pointer here */
51190   int bReadonly                   /* True if a read-only (mmap) page is ok */
51191 ){
51192   int rc;
51193   assert( sqlite3_mutex_held(pBt->mutex) );
51194
51195   if( pgno>btreePagecount(pBt) ){
51196     rc = SQLITE_CORRUPT_BKPT;
51197   }else{
51198     rc = btreeGetPage(pBt, pgno, ppPage, 0, bReadonly);
51199     if( rc==SQLITE_OK ){
51200       rc = btreeInitPage(*ppPage);
51201       if( rc!=SQLITE_OK ){
51202         releasePage(*ppPage);
51203       }
51204     }
51205   }
51206
51207   testcase( pgno==0 );
51208   assert( pgno!=0 || rc==SQLITE_CORRUPT );
51209   return rc;
51210 }
51211
51212 /*
51213 ** Release a MemPage.  This should be called once for each prior
51214 ** call to btreeGetPage.
51215 */
51216 static void releasePage(MemPage *pPage){
51217   if( pPage ){
51218     assert( pPage->aData );
51219     assert( pPage->pBt );
51220     assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
51221     assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
51222     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
51223     sqlite3PagerUnref(pPage->pDbPage);
51224   }
51225 }
51226
51227 /*
51228 ** During a rollback, when the pager reloads information into the cache
51229 ** so that the cache is restored to its original state at the start of
51230 ** the transaction, for each page restored this routine is called.
51231 **
51232 ** This routine needs to reset the extra data section at the end of the
51233 ** page to agree with the restored data.
51234 */
51235 static void pageReinit(DbPage *pData){
51236   MemPage *pPage;
51237   pPage = (MemPage *)sqlite3PagerGetExtra(pData);
51238   assert( sqlite3PagerPageRefcount(pData)>0 );
51239   if( pPage->isInit ){
51240     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
51241     pPage->isInit = 0;
51242     if( sqlite3PagerPageRefcount(pData)>1 ){
51243       /* pPage might not be a btree page;  it might be an overflow page
51244       ** or ptrmap page or a free page.  In those cases, the following
51245       ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
51246       ** But no harm is done by this.  And it is very important that
51247       ** btreeInitPage() be called on every btree page so we make
51248       ** the call for every page that comes in for re-initing. */
51249       btreeInitPage(pPage);
51250     }
51251   }
51252 }
51253
51254 /*
51255 ** Invoke the busy handler for a btree.
51256 */
51257 static int btreeInvokeBusyHandler(void *pArg){
51258   BtShared *pBt = (BtShared*)pArg;
51259   assert( pBt->db );
51260   assert( sqlite3_mutex_held(pBt->db->mutex) );
51261   return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
51262 }
51263
51264 /*
51265 ** Open a database file.
51266 ** 
51267 ** zFilename is the name of the database file.  If zFilename is NULL
51268 ** then an ephemeral database is created.  The ephemeral database might
51269 ** be exclusively in memory, or it might use a disk-based memory cache.
51270 ** Either way, the ephemeral database will be automatically deleted 
51271 ** when sqlite3BtreeClose() is called.
51272 **
51273 ** If zFilename is ":memory:" then an in-memory database is created
51274 ** that is automatically destroyed when it is closed.
51275 **
51276 ** The "flags" parameter is a bitmask that might contain bits like
51277 ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
51278 **
51279 ** If the database is already opened in the same database connection
51280 ** and we are in shared cache mode, then the open will fail with an
51281 ** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
51282 ** objects in the same database connection since doing so will lead
51283 ** to problems with locking.
51284 */
51285 SQLITE_PRIVATE int sqlite3BtreeOpen(
51286   sqlite3_vfs *pVfs,      /* VFS to use for this b-tree */
51287   const char *zFilename,  /* Name of the file containing the BTree database */
51288   sqlite3 *db,            /* Associated database handle */
51289   Btree **ppBtree,        /* Pointer to new Btree object written here */
51290   int flags,              /* Options */
51291   int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
51292 ){
51293   BtShared *pBt = 0;             /* Shared part of btree structure */
51294   Btree *p;                      /* Handle to return */
51295   sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
51296   int rc = SQLITE_OK;            /* Result code from this function */
51297   u8 nReserve;                   /* Byte of unused space on each page */
51298   unsigned char zDbHeader[100];  /* Database header content */
51299
51300   /* True if opening an ephemeral, temporary database */
51301   const int isTempDb = zFilename==0 || zFilename[0]==0;
51302
51303   /* Set the variable isMemdb to true for an in-memory database, or 
51304   ** false for a file-based database.
51305   */
51306 #ifdef SQLITE_OMIT_MEMORYDB
51307   const int isMemdb = 0;
51308 #else
51309   const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
51310                        || (isTempDb && sqlite3TempInMemory(db))
51311                        || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
51312 #endif
51313
51314   assert( db!=0 );
51315   assert( pVfs!=0 );
51316   assert( sqlite3_mutex_held(db->mutex) );
51317   assert( (flags&0xff)==flags );   /* flags fit in 8 bits */
51318
51319   /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
51320   assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
51321
51322   /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
51323   assert( (flags & BTREE_SINGLE)==0 || isTempDb );
51324
51325   if( isMemdb ){
51326     flags |= BTREE_MEMORY;
51327   }
51328   if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
51329     vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
51330   }
51331   p = sqlite3MallocZero(sizeof(Btree));
51332   if( !p ){
51333     return SQLITE_NOMEM;
51334   }
51335   p->inTrans = TRANS_NONE;
51336   p->db = db;
51337 #ifndef SQLITE_OMIT_SHARED_CACHE
51338   p->lock.pBtree = p;
51339   p->lock.iTable = 1;
51340 #endif
51341
51342 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
51343   /*
51344   ** If this Btree is a candidate for shared cache, try to find an
51345   ** existing BtShared object that we can share with
51346   */
51347   if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
51348     if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
51349       int nFullPathname = pVfs->mxPathname+1;
51350       char *zFullPathname = sqlite3Malloc(nFullPathname);
51351       MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
51352       p->sharable = 1;
51353       if( !zFullPathname ){
51354         sqlite3_free(p);
51355         return SQLITE_NOMEM;
51356       }
51357       if( isMemdb ){
51358         memcpy(zFullPathname, zFilename, sqlite3Strlen30(zFilename)+1);
51359       }else{
51360         rc = sqlite3OsFullPathname(pVfs, zFilename,
51361                                    nFullPathname, zFullPathname);
51362         if( rc ){
51363           sqlite3_free(zFullPathname);
51364           sqlite3_free(p);
51365           return rc;
51366         }
51367       }
51368 #if SQLITE_THREADSAFE
51369       mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
51370       sqlite3_mutex_enter(mutexOpen);
51371       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
51372       sqlite3_mutex_enter(mutexShared);
51373 #endif
51374       for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
51375         assert( pBt->nRef>0 );
51376         if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
51377                  && sqlite3PagerVfs(pBt->pPager)==pVfs ){
51378           int iDb;
51379           for(iDb=db->nDb-1; iDb>=0; iDb--){
51380             Btree *pExisting = db->aDb[iDb].pBt;
51381             if( pExisting && pExisting->pBt==pBt ){
51382               sqlite3_mutex_leave(mutexShared);
51383               sqlite3_mutex_leave(mutexOpen);
51384               sqlite3_free(zFullPathname);
51385               sqlite3_free(p);
51386               return SQLITE_CONSTRAINT;
51387             }
51388           }
51389           p->pBt = pBt;
51390           pBt->nRef++;
51391           break;
51392         }
51393       }
51394       sqlite3_mutex_leave(mutexShared);
51395       sqlite3_free(zFullPathname);
51396     }
51397 #ifdef SQLITE_DEBUG
51398     else{
51399       /* In debug mode, we mark all persistent databases as sharable
51400       ** even when they are not.  This exercises the locking code and
51401       ** gives more opportunity for asserts(sqlite3_mutex_held())
51402       ** statements to find locking problems.
51403       */
51404       p->sharable = 1;
51405     }
51406 #endif
51407   }
51408 #endif
51409   if( pBt==0 ){
51410     /*
51411     ** The following asserts make sure that structures used by the btree are
51412     ** the right size.  This is to guard against size changes that result
51413     ** when compiling on a different architecture.
51414     */
51415     assert( sizeof(i64)==8 || sizeof(i64)==4 );
51416     assert( sizeof(u64)==8 || sizeof(u64)==4 );
51417     assert( sizeof(u32)==4 );
51418     assert( sizeof(u16)==2 );
51419     assert( sizeof(Pgno)==4 );
51420   
51421     pBt = sqlite3MallocZero( sizeof(*pBt) );
51422     if( pBt==0 ){
51423       rc = SQLITE_NOMEM;
51424       goto btree_open_out;
51425     }
51426     rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
51427                           EXTRA_SIZE, flags, vfsFlags, pageReinit);
51428     if( rc==SQLITE_OK ){
51429       sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
51430       rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
51431     }
51432     if( rc!=SQLITE_OK ){
51433       goto btree_open_out;
51434     }
51435     pBt->openFlags = (u8)flags;
51436     pBt->db = db;
51437     sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
51438     p->pBt = pBt;
51439   
51440     pBt->pCursor = 0;
51441     pBt->pPage1 = 0;
51442     if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
51443 #ifdef SQLITE_SECURE_DELETE
51444     pBt->btsFlags |= BTS_SECURE_DELETE;
51445 #endif
51446     pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
51447     if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
51448          || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
51449       pBt->pageSize = 0;
51450 #ifndef SQLITE_OMIT_AUTOVACUUM
51451       /* If the magic name ":memory:" will create an in-memory database, then
51452       ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
51453       ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
51454       ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
51455       ** regular file-name. In this case the auto-vacuum applies as per normal.
51456       */
51457       if( zFilename && !isMemdb ){
51458         pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
51459         pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
51460       }
51461 #endif
51462       nReserve = 0;
51463     }else{
51464       nReserve = zDbHeader[20];
51465       pBt->btsFlags |= BTS_PAGESIZE_FIXED;
51466 #ifndef SQLITE_OMIT_AUTOVACUUM
51467       pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
51468       pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
51469 #endif
51470     }
51471     rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
51472     if( rc ) goto btree_open_out;
51473     pBt->usableSize = pBt->pageSize - nReserve;
51474     assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
51475    
51476 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
51477     /* Add the new BtShared object to the linked list sharable BtShareds.
51478     */
51479     if( p->sharable ){
51480       MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
51481       pBt->nRef = 1;
51482       MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
51483       if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
51484         pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
51485         if( pBt->mutex==0 ){
51486           rc = SQLITE_NOMEM;
51487           db->mallocFailed = 0;
51488           goto btree_open_out;
51489         }
51490       }
51491       sqlite3_mutex_enter(mutexShared);
51492       pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
51493       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
51494       sqlite3_mutex_leave(mutexShared);
51495     }
51496 #endif
51497   }
51498
51499 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
51500   /* If the new Btree uses a sharable pBtShared, then link the new
51501   ** Btree into the list of all sharable Btrees for the same connection.
51502   ** The list is kept in ascending order by pBt address.
51503   */
51504   if( p->sharable ){
51505     int i;
51506     Btree *pSib;
51507     for(i=0; i<db->nDb; i++){
51508       if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
51509         while( pSib->pPrev ){ pSib = pSib->pPrev; }
51510         if( p->pBt<pSib->pBt ){
51511           p->pNext = pSib;
51512           p->pPrev = 0;
51513           pSib->pPrev = p;
51514         }else{
51515           while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
51516             pSib = pSib->pNext;
51517           }
51518           p->pNext = pSib->pNext;
51519           p->pPrev = pSib;
51520           if( p->pNext ){
51521             p->pNext->pPrev = p;
51522           }
51523           pSib->pNext = p;
51524         }
51525         break;
51526       }
51527     }
51528   }
51529 #endif
51530   *ppBtree = p;
51531
51532 btree_open_out:
51533   if( rc!=SQLITE_OK ){
51534     if( pBt && pBt->pPager ){
51535       sqlite3PagerClose(pBt->pPager);
51536     }
51537     sqlite3_free(pBt);
51538     sqlite3_free(p);
51539     *ppBtree = 0;
51540   }else{
51541     /* If the B-Tree was successfully opened, set the pager-cache size to the
51542     ** default value. Except, when opening on an existing shared pager-cache,
51543     ** do not change the pager-cache size.
51544     */
51545     if( sqlite3BtreeSchema(p, 0, 0)==0 ){
51546       sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
51547     }
51548   }
51549   if( mutexOpen ){
51550     assert( sqlite3_mutex_held(mutexOpen) );
51551     sqlite3_mutex_leave(mutexOpen);
51552   }
51553   return rc;
51554 }
51555
51556 /*
51557 ** Decrement the BtShared.nRef counter.  When it reaches zero,
51558 ** remove the BtShared structure from the sharing list.  Return
51559 ** true if the BtShared.nRef counter reaches zero and return
51560 ** false if it is still positive.
51561 */
51562 static int removeFromSharingList(BtShared *pBt){
51563 #ifndef SQLITE_OMIT_SHARED_CACHE
51564   MUTEX_LOGIC( sqlite3_mutex *pMaster; )
51565   BtShared *pList;
51566   int removed = 0;
51567
51568   assert( sqlite3_mutex_notheld(pBt->mutex) );
51569   MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
51570   sqlite3_mutex_enter(pMaster);
51571   pBt->nRef--;
51572   if( pBt->nRef<=0 ){
51573     if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
51574       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
51575     }else{
51576       pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
51577       while( ALWAYS(pList) && pList->pNext!=pBt ){
51578         pList=pList->pNext;
51579       }
51580       if( ALWAYS(pList) ){
51581         pList->pNext = pBt->pNext;
51582       }
51583     }
51584     if( SQLITE_THREADSAFE ){
51585       sqlite3_mutex_free(pBt->mutex);
51586     }
51587     removed = 1;
51588   }
51589   sqlite3_mutex_leave(pMaster);
51590   return removed;
51591 #else
51592   return 1;
51593 #endif
51594 }
51595
51596 /*
51597 ** Make sure pBt->pTmpSpace points to an allocation of 
51598 ** MX_CELL_SIZE(pBt) bytes.
51599 */
51600 static void allocateTempSpace(BtShared *pBt){
51601   if( !pBt->pTmpSpace ){
51602     pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
51603   }
51604 }
51605
51606 /*
51607 ** Free the pBt->pTmpSpace allocation
51608 */
51609 static void freeTempSpace(BtShared *pBt){
51610   sqlite3PageFree( pBt->pTmpSpace);
51611   pBt->pTmpSpace = 0;
51612 }
51613
51614 /*
51615 ** Close an open database and invalidate all cursors.
51616 */
51617 SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
51618   BtShared *pBt = p->pBt;
51619   BtCursor *pCur;
51620
51621   /* Close all cursors opened via this handle.  */
51622   assert( sqlite3_mutex_held(p->db->mutex) );
51623   sqlite3BtreeEnter(p);
51624   pCur = pBt->pCursor;
51625   while( pCur ){
51626     BtCursor *pTmp = pCur;
51627     pCur = pCur->pNext;
51628     if( pTmp->pBtree==p ){
51629       sqlite3BtreeCloseCursor(pTmp);
51630     }
51631   }
51632
51633   /* Rollback any active transaction and free the handle structure.
51634   ** The call to sqlite3BtreeRollback() drops any table-locks held by
51635   ** this handle.
51636   */
51637   sqlite3BtreeRollback(p, SQLITE_OK);
51638   sqlite3BtreeLeave(p);
51639
51640   /* If there are still other outstanding references to the shared-btree
51641   ** structure, return now. The remainder of this procedure cleans 
51642   ** up the shared-btree.
51643   */
51644   assert( p->wantToLock==0 && p->locked==0 );
51645   if( !p->sharable || removeFromSharingList(pBt) ){
51646     /* The pBt is no longer on the sharing list, so we can access
51647     ** it without having to hold the mutex.
51648     **
51649     ** Clean out and delete the BtShared object.
51650     */
51651     assert( !pBt->pCursor );
51652     sqlite3PagerClose(pBt->pPager);
51653     if( pBt->xFreeSchema && pBt->pSchema ){
51654       pBt->xFreeSchema(pBt->pSchema);
51655     }
51656     sqlite3DbFree(0, pBt->pSchema);
51657     freeTempSpace(pBt);
51658     sqlite3_free(pBt);
51659   }
51660
51661 #ifndef SQLITE_OMIT_SHARED_CACHE
51662   assert( p->wantToLock==0 );
51663   assert( p->locked==0 );
51664   if( p->pPrev ) p->pPrev->pNext = p->pNext;
51665   if( p->pNext ) p->pNext->pPrev = p->pPrev;
51666 #endif
51667
51668   sqlite3_free(p);
51669   return SQLITE_OK;
51670 }
51671
51672 /*
51673 ** Change the limit on the number of pages allowed in the cache.
51674 **
51675 ** The maximum number of cache pages is set to the absolute
51676 ** value of mxPage.  If mxPage is negative, the pager will
51677 ** operate asynchronously - it will not stop to do fsync()s
51678 ** to insure data is written to the disk surface before
51679 ** continuing.  Transactions still work if synchronous is off,
51680 ** and the database cannot be corrupted if this program
51681 ** crashes.  But if the operating system crashes or there is
51682 ** an abrupt power failure when synchronous is off, the database
51683 ** could be left in an inconsistent and unrecoverable state.
51684 ** Synchronous is on by default so database corruption is not
51685 ** normally a worry.
51686 */
51687 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
51688   BtShared *pBt = p->pBt;
51689   assert( sqlite3_mutex_held(p->db->mutex) );
51690   sqlite3BtreeEnter(p);
51691   sqlite3PagerSetCachesize(pBt->pPager, mxPage);
51692   sqlite3BtreeLeave(p);
51693   return SQLITE_OK;
51694 }
51695
51696 /*
51697 ** Change the limit on the amount of the database file that may be
51698 ** memory mapped.
51699 */
51700 SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
51701   BtShared *pBt = p->pBt;
51702   assert( sqlite3_mutex_held(p->db->mutex) );
51703   sqlite3BtreeEnter(p);
51704   sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
51705   sqlite3BtreeLeave(p);
51706   return SQLITE_OK;
51707 }
51708
51709 /*
51710 ** Change the way data is synced to disk in order to increase or decrease
51711 ** how well the database resists damage due to OS crashes and power
51712 ** failures.  Level 1 is the same as asynchronous (no syncs() occur and
51713 ** there is a high probability of damage)  Level 2 is the default.  There
51714 ** is a very low but non-zero probability of damage.  Level 3 reduces the
51715 ** probability of damage to near zero but with a write performance reduction.
51716 */
51717 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
51718 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(
51719   Btree *p,              /* The btree to set the safety level on */
51720   int level,             /* PRAGMA synchronous.  1=OFF, 2=NORMAL, 3=FULL */
51721   int fullSync,          /* PRAGMA fullfsync. */
51722   int ckptFullSync       /* PRAGMA checkpoint_fullfync */
51723 ){
51724   BtShared *pBt = p->pBt;
51725   assert( sqlite3_mutex_held(p->db->mutex) );
51726   assert( level>=1 && level<=3 );
51727   sqlite3BtreeEnter(p);
51728   sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync, ckptFullSync);
51729   sqlite3BtreeLeave(p);
51730   return SQLITE_OK;
51731 }
51732 #endif
51733
51734 /*
51735 ** Return TRUE if the given btree is set to safety level 1.  In other
51736 ** words, return TRUE if no sync() occurs on the disk files.
51737 */
51738 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
51739   BtShared *pBt = p->pBt;
51740   int rc;
51741   assert( sqlite3_mutex_held(p->db->mutex) );  
51742   sqlite3BtreeEnter(p);
51743   assert( pBt && pBt->pPager );
51744   rc = sqlite3PagerNosync(pBt->pPager);
51745   sqlite3BtreeLeave(p);
51746   return rc;
51747 }
51748
51749 /*
51750 ** Change the default pages size and the number of reserved bytes per page.
51751 ** Or, if the page size has already been fixed, return SQLITE_READONLY 
51752 ** without changing anything.
51753 **
51754 ** The page size must be a power of 2 between 512 and 65536.  If the page
51755 ** size supplied does not meet this constraint then the page size is not
51756 ** changed.
51757 **
51758 ** Page sizes are constrained to be a power of two so that the region
51759 ** of the database file used for locking (beginning at PENDING_BYTE,
51760 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
51761 ** at the beginning of a page.
51762 **
51763 ** If parameter nReserve is less than zero, then the number of reserved
51764 ** bytes per page is left unchanged.
51765 **
51766 ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
51767 ** and autovacuum mode can no longer be changed.
51768 */
51769 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
51770   int rc = SQLITE_OK;
51771   BtShared *pBt = p->pBt;
51772   assert( nReserve>=-1 && nReserve<=255 );
51773   sqlite3BtreeEnter(p);
51774   if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
51775     sqlite3BtreeLeave(p);
51776     return SQLITE_READONLY;
51777   }
51778   if( nReserve<0 ){
51779     nReserve = pBt->pageSize - pBt->usableSize;
51780   }
51781   assert( nReserve>=0 && nReserve<=255 );
51782   if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
51783         ((pageSize-1)&pageSize)==0 ){
51784     assert( (pageSize & 7)==0 );
51785     assert( !pBt->pPage1 && !pBt->pCursor );
51786     pBt->pageSize = (u32)pageSize;
51787     freeTempSpace(pBt);
51788   }
51789   rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
51790   pBt->usableSize = pBt->pageSize - (u16)nReserve;
51791   if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
51792   sqlite3BtreeLeave(p);
51793   return rc;
51794 }
51795
51796 /*
51797 ** Return the currently defined page size
51798 */
51799 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
51800   return p->pBt->pageSize;
51801 }
51802
51803 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG)
51804 /*
51805 ** This function is similar to sqlite3BtreeGetReserve(), except that it
51806 ** may only be called if it is guaranteed that the b-tree mutex is already
51807 ** held.
51808 **
51809 ** This is useful in one special case in the backup API code where it is
51810 ** known that the shared b-tree mutex is held, but the mutex on the 
51811 ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
51812 ** were to be called, it might collide with some other operation on the
51813 ** database handle that owns *p, causing undefined behavior.
51814 */
51815 SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
51816   assert( sqlite3_mutex_held(p->pBt->mutex) );
51817   return p->pBt->pageSize - p->pBt->usableSize;
51818 }
51819 #endif /* SQLITE_HAS_CODEC || SQLITE_DEBUG */
51820
51821 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
51822 /*
51823 ** Return the number of bytes of space at the end of every page that
51824 ** are intentually left unused.  This is the "reserved" space that is
51825 ** sometimes used by extensions.
51826 */
51827 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
51828   int n;
51829   sqlite3BtreeEnter(p);
51830   n = p->pBt->pageSize - p->pBt->usableSize;
51831   sqlite3BtreeLeave(p);
51832   return n;
51833 }
51834
51835 /*
51836 ** Set the maximum page count for a database if mxPage is positive.
51837 ** No changes are made if mxPage is 0 or negative.
51838 ** Regardless of the value of mxPage, return the maximum page count.
51839 */
51840 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
51841   int n;
51842   sqlite3BtreeEnter(p);
51843   n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
51844   sqlite3BtreeLeave(p);
51845   return n;
51846 }
51847
51848 /*
51849 ** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1.  If newFlag is -1,
51850 ** then make no changes.  Always return the value of the BTS_SECURE_DELETE
51851 ** setting after the change.
51852 */
51853 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
51854   int b;
51855   if( p==0 ) return 0;
51856   sqlite3BtreeEnter(p);
51857   if( newFlag>=0 ){
51858     p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
51859     if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
51860   } 
51861   b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
51862   sqlite3BtreeLeave(p);
51863   return b;
51864 }
51865 #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
51866
51867 /*
51868 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
51869 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
51870 ** is disabled. The default value for the auto-vacuum property is 
51871 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
51872 */
51873 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
51874 #ifdef SQLITE_OMIT_AUTOVACUUM
51875   return SQLITE_READONLY;
51876 #else
51877   BtShared *pBt = p->pBt;
51878   int rc = SQLITE_OK;
51879   u8 av = (u8)autoVacuum;
51880
51881   sqlite3BtreeEnter(p);
51882   if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
51883     rc = SQLITE_READONLY;
51884   }else{
51885     pBt->autoVacuum = av ?1:0;
51886     pBt->incrVacuum = av==2 ?1:0;
51887   }
51888   sqlite3BtreeLeave(p);
51889   return rc;
51890 #endif
51891 }
51892
51893 /*
51894 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is 
51895 ** enabled 1 is returned. Otherwise 0.
51896 */
51897 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
51898 #ifdef SQLITE_OMIT_AUTOVACUUM
51899   return BTREE_AUTOVACUUM_NONE;
51900 #else
51901   int rc;
51902   sqlite3BtreeEnter(p);
51903   rc = (
51904     (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
51905     (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
51906     BTREE_AUTOVACUUM_INCR
51907   );
51908   sqlite3BtreeLeave(p);
51909   return rc;
51910 #endif
51911 }
51912
51913
51914 /*
51915 ** Get a reference to pPage1 of the database file.  This will
51916 ** also acquire a readlock on that file.
51917 **
51918 ** SQLITE_OK is returned on success.  If the file is not a
51919 ** well-formed database file, then SQLITE_CORRUPT is returned.
51920 ** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
51921 ** is returned if we run out of memory. 
51922 */
51923 static int lockBtree(BtShared *pBt){
51924   int rc;              /* Result code from subfunctions */
51925   MemPage *pPage1;     /* Page 1 of the database file */
51926   int nPage;           /* Number of pages in the database */
51927   int nPageFile = 0;   /* Number of pages in the database file */
51928   int nPageHeader;     /* Number of pages in the database according to hdr */
51929
51930   assert( sqlite3_mutex_held(pBt->mutex) );
51931   assert( pBt->pPage1==0 );
51932   rc = sqlite3PagerSharedLock(pBt->pPager);
51933   if( rc!=SQLITE_OK ) return rc;
51934   rc = btreeGetPage(pBt, 1, &pPage1, 0, 0);
51935   if( rc!=SQLITE_OK ) return rc;
51936
51937   /* Do some checking to help insure the file we opened really is
51938   ** a valid database file. 
51939   */
51940   nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
51941   sqlite3PagerPagecount(pBt->pPager, &nPageFile);
51942   if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
51943     nPage = nPageFile;
51944   }
51945   if( nPage>0 ){
51946     u32 pageSize;
51947     u32 usableSize;
51948     u8 *page1 = pPage1->aData;
51949     rc = SQLITE_NOTADB;
51950     if( memcmp(page1, zMagicHeader, 16)!=0 ){
51951       goto page1_init_failed;
51952     }
51953
51954 #ifdef SQLITE_OMIT_WAL
51955     if( page1[18]>1 ){
51956       pBt->btsFlags |= BTS_READ_ONLY;
51957     }
51958     if( page1[19]>1 ){
51959       goto page1_init_failed;
51960     }
51961 #else
51962     if( page1[18]>2 ){
51963       pBt->btsFlags |= BTS_READ_ONLY;
51964     }
51965     if( page1[19]>2 ){
51966       goto page1_init_failed;
51967     }
51968
51969     /* If the write version is set to 2, this database should be accessed
51970     ** in WAL mode. If the log is not already open, open it now. Then 
51971     ** return SQLITE_OK and return without populating BtShared.pPage1.
51972     ** The caller detects this and calls this function again. This is
51973     ** required as the version of page 1 currently in the page1 buffer
51974     ** may not be the latest version - there may be a newer one in the log
51975     ** file.
51976     */
51977     if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
51978       int isOpen = 0;
51979       rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
51980       if( rc!=SQLITE_OK ){
51981         goto page1_init_failed;
51982       }else if( isOpen==0 ){
51983         releasePage(pPage1);
51984         return SQLITE_OK;
51985       }
51986       rc = SQLITE_NOTADB;
51987     }
51988 #endif
51989
51990     /* The maximum embedded fraction must be exactly 25%.  And the minimum
51991     ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
51992     ** The original design allowed these amounts to vary, but as of
51993     ** version 3.6.0, we require them to be fixed.
51994     */
51995     if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
51996       goto page1_init_failed;
51997     }
51998     pageSize = (page1[16]<<8) | (page1[17]<<16);
51999     if( ((pageSize-1)&pageSize)!=0
52000      || pageSize>SQLITE_MAX_PAGE_SIZE 
52001      || pageSize<=256 
52002     ){
52003       goto page1_init_failed;
52004     }
52005     assert( (pageSize & 7)==0 );
52006     usableSize = pageSize - page1[20];
52007     if( (u32)pageSize!=pBt->pageSize ){
52008       /* After reading the first page of the database assuming a page size
52009       ** of BtShared.pageSize, we have discovered that the page-size is
52010       ** actually pageSize. Unlock the database, leave pBt->pPage1 at
52011       ** zero and return SQLITE_OK. The caller will call this function
52012       ** again with the correct page-size.
52013       */
52014       releasePage(pPage1);
52015       pBt->usableSize = usableSize;
52016       pBt->pageSize = pageSize;
52017       freeTempSpace(pBt);
52018       rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
52019                                    pageSize-usableSize);
52020       return rc;
52021     }
52022     if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
52023       rc = SQLITE_CORRUPT_BKPT;
52024       goto page1_init_failed;
52025     }
52026     if( usableSize<480 ){
52027       goto page1_init_failed;
52028     }
52029     pBt->pageSize = pageSize;
52030     pBt->usableSize = usableSize;
52031 #ifndef SQLITE_OMIT_AUTOVACUUM
52032     pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
52033     pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
52034 #endif
52035   }
52036
52037   /* maxLocal is the maximum amount of payload to store locally for
52038   ** a cell.  Make sure it is small enough so that at least minFanout
52039   ** cells can will fit on one page.  We assume a 10-byte page header.
52040   ** Besides the payload, the cell must store:
52041   **     2-byte pointer to the cell
52042   **     4-byte child pointer
52043   **     9-byte nKey value
52044   **     4-byte nData value
52045   **     4-byte overflow page pointer
52046   ** So a cell consists of a 2-byte pointer, a header which is as much as
52047   ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
52048   ** page pointer.
52049   */
52050   pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
52051   pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
52052   pBt->maxLeaf = (u16)(pBt->usableSize - 35);
52053   pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
52054   if( pBt->maxLocal>127 ){
52055     pBt->max1bytePayload = 127;
52056   }else{
52057     pBt->max1bytePayload = (u8)pBt->maxLocal;
52058   }
52059   assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
52060   pBt->pPage1 = pPage1;
52061   pBt->nPage = nPage;
52062   return SQLITE_OK;
52063
52064 page1_init_failed:
52065   releasePage(pPage1);
52066   pBt->pPage1 = 0;
52067   return rc;
52068 }
52069
52070 #ifndef NDEBUG
52071 /*
52072 ** Return the number of cursors open on pBt. This is for use
52073 ** in assert() expressions, so it is only compiled if NDEBUG is not
52074 ** defined.
52075 **
52076 ** Only write cursors are counted if wrOnly is true.  If wrOnly is
52077 ** false then all cursors are counted.
52078 **
52079 ** For the purposes of this routine, a cursor is any cursor that
52080 ** is capable of reading or writing to the databse.  Cursors that
52081 ** have been tripped into the CURSOR_FAULT state are not counted.
52082 */
52083 static int countValidCursors(BtShared *pBt, int wrOnly){
52084   BtCursor *pCur;
52085   int r = 0;
52086   for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
52087     if( (wrOnly==0 || pCur->wrFlag) && pCur->eState!=CURSOR_FAULT ) r++; 
52088   }
52089   return r;
52090 }
52091 #endif
52092
52093 /*
52094 ** If there are no outstanding cursors and we are not in the middle
52095 ** of a transaction but there is a read lock on the database, then
52096 ** this routine unrefs the first page of the database file which 
52097 ** has the effect of releasing the read lock.
52098 **
52099 ** If there is a transaction in progress, this routine is a no-op.
52100 */
52101 static void unlockBtreeIfUnused(BtShared *pBt){
52102   assert( sqlite3_mutex_held(pBt->mutex) );
52103   assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
52104   if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
52105     assert( pBt->pPage1->aData );
52106     assert( sqlite3PagerRefcount(pBt->pPager)==1 );
52107     assert( pBt->pPage1->aData );
52108     releasePage(pBt->pPage1);
52109     pBt->pPage1 = 0;
52110   }
52111 }
52112
52113 /*
52114 ** If pBt points to an empty file then convert that empty file
52115 ** into a new empty database by initializing the first page of
52116 ** the database.
52117 */
52118 static int newDatabase(BtShared *pBt){
52119   MemPage *pP1;
52120   unsigned char *data;
52121   int rc;
52122
52123   assert( sqlite3_mutex_held(pBt->mutex) );
52124   if( pBt->nPage>0 ){
52125     return SQLITE_OK;
52126   }
52127   pP1 = pBt->pPage1;
52128   assert( pP1!=0 );
52129   data = pP1->aData;
52130   rc = sqlite3PagerWrite(pP1->pDbPage);
52131   if( rc ) return rc;
52132   memcpy(data, zMagicHeader, sizeof(zMagicHeader));
52133   assert( sizeof(zMagicHeader)==16 );
52134   data[16] = (u8)((pBt->pageSize>>8)&0xff);
52135   data[17] = (u8)((pBt->pageSize>>16)&0xff);
52136   data[18] = 1;
52137   data[19] = 1;
52138   assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
52139   data[20] = (u8)(pBt->pageSize - pBt->usableSize);
52140   data[21] = 64;
52141   data[22] = 32;
52142   data[23] = 32;
52143   memset(&data[24], 0, 100-24);
52144   zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
52145   pBt->btsFlags |= BTS_PAGESIZE_FIXED;
52146 #ifndef SQLITE_OMIT_AUTOVACUUM
52147   assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
52148   assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
52149   put4byte(&data[36 + 4*4], pBt->autoVacuum);
52150   put4byte(&data[36 + 7*4], pBt->incrVacuum);
52151 #endif
52152   pBt->nPage = 1;
52153   data[31] = 1;
52154   return SQLITE_OK;
52155 }
52156
52157 /*
52158 ** Initialize the first page of the database file (creating a database
52159 ** consisting of a single page and no schema objects). Return SQLITE_OK
52160 ** if successful, or an SQLite error code otherwise.
52161 */
52162 SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
52163   int rc;
52164   sqlite3BtreeEnter(p);
52165   p->pBt->nPage = 0;
52166   rc = newDatabase(p->pBt);
52167   sqlite3BtreeLeave(p);
52168   return rc;
52169 }
52170
52171 /*
52172 ** Attempt to start a new transaction. A write-transaction
52173 ** is started if the second argument is nonzero, otherwise a read-
52174 ** transaction.  If the second argument is 2 or more and exclusive
52175 ** transaction is started, meaning that no other process is allowed
52176 ** to access the database.  A preexisting transaction may not be
52177 ** upgraded to exclusive by calling this routine a second time - the
52178 ** exclusivity flag only works for a new transaction.
52179 **
52180 ** A write-transaction must be started before attempting any 
52181 ** changes to the database.  None of the following routines 
52182 ** will work unless a transaction is started first:
52183 **
52184 **      sqlite3BtreeCreateTable()
52185 **      sqlite3BtreeCreateIndex()
52186 **      sqlite3BtreeClearTable()
52187 **      sqlite3BtreeDropTable()
52188 **      sqlite3BtreeInsert()
52189 **      sqlite3BtreeDelete()
52190 **      sqlite3BtreeUpdateMeta()
52191 **
52192 ** If an initial attempt to acquire the lock fails because of lock contention
52193 ** and the database was previously unlocked, then invoke the busy handler
52194 ** if there is one.  But if there was previously a read-lock, do not
52195 ** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is 
52196 ** returned when there is already a read-lock in order to avoid a deadlock.
52197 **
52198 ** Suppose there are two processes A and B.  A has a read lock and B has
52199 ** a reserved lock.  B tries to promote to exclusive but is blocked because
52200 ** of A's read lock.  A tries to promote to reserved but is blocked by B.
52201 ** One or the other of the two processes must give way or there can be
52202 ** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
52203 ** when A already has a read lock, we encourage A to give up and let B
52204 ** proceed.
52205 */
52206 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
52207   sqlite3 *pBlock = 0;
52208   BtShared *pBt = p->pBt;
52209   int rc = SQLITE_OK;
52210
52211   sqlite3BtreeEnter(p);
52212   btreeIntegrity(p);
52213
52214   /* If the btree is already in a write-transaction, or it
52215   ** is already in a read-transaction and a read-transaction
52216   ** is requested, this is a no-op.
52217   */
52218   if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
52219     goto trans_begun;
52220   }
52221   assert( IfNotOmitAV(pBt->bDoTruncate)==0 );
52222
52223   /* Write transactions are not possible on a read-only database */
52224   if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
52225     rc = SQLITE_READONLY;
52226     goto trans_begun;
52227   }
52228
52229 #ifndef SQLITE_OMIT_SHARED_CACHE
52230   /* If another database handle has already opened a write transaction 
52231   ** on this shared-btree structure and a second write transaction is
52232   ** requested, return SQLITE_LOCKED.
52233   */
52234   if( (wrflag && pBt->inTransaction==TRANS_WRITE)
52235    || (pBt->btsFlags & BTS_PENDING)!=0
52236   ){
52237     pBlock = pBt->pWriter->db;
52238   }else if( wrflag>1 ){
52239     BtLock *pIter;
52240     for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
52241       if( pIter->pBtree!=p ){
52242         pBlock = pIter->pBtree->db;
52243         break;
52244       }
52245     }
52246   }
52247   if( pBlock ){
52248     sqlite3ConnectionBlocked(p->db, pBlock);
52249     rc = SQLITE_LOCKED_SHAREDCACHE;
52250     goto trans_begun;
52251   }
52252 #endif
52253
52254   /* Any read-only or read-write transaction implies a read-lock on 
52255   ** page 1. So if some other shared-cache client already has a write-lock 
52256   ** on page 1, the transaction cannot be opened. */
52257   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
52258   if( SQLITE_OK!=rc ) goto trans_begun;
52259
52260   pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
52261   if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
52262   do {
52263     /* Call lockBtree() until either pBt->pPage1 is populated or
52264     ** lockBtree() returns something other than SQLITE_OK. lockBtree()
52265     ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
52266     ** reading page 1 it discovers that the page-size of the database 
52267     ** file is not pBt->pageSize. In this case lockBtree() will update
52268     ** pBt->pageSize to the page-size of the file on disk.
52269     */
52270     while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
52271
52272     if( rc==SQLITE_OK && wrflag ){
52273       if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
52274         rc = SQLITE_READONLY;
52275       }else{
52276         rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
52277         if( rc==SQLITE_OK ){
52278           rc = newDatabase(pBt);
52279         }
52280       }
52281     }
52282   
52283     if( rc!=SQLITE_OK ){
52284       unlockBtreeIfUnused(pBt);
52285     }
52286   }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
52287           btreeInvokeBusyHandler(pBt) );
52288
52289   if( rc==SQLITE_OK ){
52290     if( p->inTrans==TRANS_NONE ){
52291       pBt->nTransaction++;
52292 #ifndef SQLITE_OMIT_SHARED_CACHE
52293       if( p->sharable ){
52294         assert( p->lock.pBtree==p && p->lock.iTable==1 );
52295         p->lock.eLock = READ_LOCK;
52296         p->lock.pNext = pBt->pLock;
52297         pBt->pLock = &p->lock;
52298       }
52299 #endif
52300     }
52301     p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
52302     if( p->inTrans>pBt->inTransaction ){
52303       pBt->inTransaction = p->inTrans;
52304     }
52305     if( wrflag ){
52306       MemPage *pPage1 = pBt->pPage1;
52307 #ifndef SQLITE_OMIT_SHARED_CACHE
52308       assert( !pBt->pWriter );
52309       pBt->pWriter = p;
52310       pBt->btsFlags &= ~BTS_EXCLUSIVE;
52311       if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
52312 #endif
52313
52314       /* If the db-size header field is incorrect (as it may be if an old
52315       ** client has been writing the database file), update it now. Doing
52316       ** this sooner rather than later means the database size can safely 
52317       ** re-read the database size from page 1 if a savepoint or transaction
52318       ** rollback occurs within the transaction.
52319       */
52320       if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
52321         rc = sqlite3PagerWrite(pPage1->pDbPage);
52322         if( rc==SQLITE_OK ){
52323           put4byte(&pPage1->aData[28], pBt->nPage);
52324         }
52325       }
52326     }
52327   }
52328
52329
52330 trans_begun:
52331   if( rc==SQLITE_OK && wrflag ){
52332     /* This call makes sure that the pager has the correct number of
52333     ** open savepoints. If the second parameter is greater than 0 and
52334     ** the sub-journal is not already open, then it will be opened here.
52335     */
52336     rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
52337   }
52338
52339   btreeIntegrity(p);
52340   sqlite3BtreeLeave(p);
52341   return rc;
52342 }
52343
52344 #ifndef SQLITE_OMIT_AUTOVACUUM
52345
52346 /*
52347 ** Set the pointer-map entries for all children of page pPage. Also, if
52348 ** pPage contains cells that point to overflow pages, set the pointer
52349 ** map entries for the overflow pages as well.
52350 */
52351 static int setChildPtrmaps(MemPage *pPage){
52352   int i;                             /* Counter variable */
52353   int nCell;                         /* Number of cells in page pPage */
52354   int rc;                            /* Return code */
52355   BtShared *pBt = pPage->pBt;
52356   u8 isInitOrig = pPage->isInit;
52357   Pgno pgno = pPage->pgno;
52358
52359   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52360   rc = btreeInitPage(pPage);
52361   if( rc!=SQLITE_OK ){
52362     goto set_child_ptrmaps_out;
52363   }
52364   nCell = pPage->nCell;
52365
52366   for(i=0; i<nCell; i++){
52367     u8 *pCell = findCell(pPage, i);
52368
52369     ptrmapPutOvflPtr(pPage, pCell, &rc);
52370
52371     if( !pPage->leaf ){
52372       Pgno childPgno = get4byte(pCell);
52373       ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
52374     }
52375   }
52376
52377   if( !pPage->leaf ){
52378     Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
52379     ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
52380   }
52381
52382 set_child_ptrmaps_out:
52383   pPage->isInit = isInitOrig;
52384   return rc;
52385 }
52386
52387 /*
52388 ** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
52389 ** that it points to iTo. Parameter eType describes the type of pointer to
52390 ** be modified, as  follows:
52391 **
52392 ** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child 
52393 **                   page of pPage.
52394 **
52395 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
52396 **                   page pointed to by one of the cells on pPage.
52397 **
52398 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
52399 **                   overflow page in the list.
52400 */
52401 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
52402   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
52403   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
52404   if( eType==PTRMAP_OVERFLOW2 ){
52405     /* The pointer is always the first 4 bytes of the page in this case.  */
52406     if( get4byte(pPage->aData)!=iFrom ){
52407       return SQLITE_CORRUPT_BKPT;
52408     }
52409     put4byte(pPage->aData, iTo);
52410   }else{
52411     u8 isInitOrig = pPage->isInit;
52412     int i;
52413     int nCell;
52414
52415     btreeInitPage(pPage);
52416     nCell = pPage->nCell;
52417
52418     for(i=0; i<nCell; i++){
52419       u8 *pCell = findCell(pPage, i);
52420       if( eType==PTRMAP_OVERFLOW1 ){
52421         CellInfo info;
52422         btreeParseCellPtr(pPage, pCell, &info);
52423         if( info.iOverflow
52424          && pCell+info.iOverflow+3<=pPage->aData+pPage->maskPage
52425          && iFrom==get4byte(&pCell[info.iOverflow])
52426         ){
52427           put4byte(&pCell[info.iOverflow], iTo);
52428           break;
52429         }
52430       }else{
52431         if( get4byte(pCell)==iFrom ){
52432           put4byte(pCell, iTo);
52433           break;
52434         }
52435       }
52436     }
52437   
52438     if( i==nCell ){
52439       if( eType!=PTRMAP_BTREE || 
52440           get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
52441         return SQLITE_CORRUPT_BKPT;
52442       }
52443       put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
52444     }
52445
52446     pPage->isInit = isInitOrig;
52447   }
52448   return SQLITE_OK;
52449 }
52450
52451
52452 /*
52453 ** Move the open database page pDbPage to location iFreePage in the 
52454 ** database. The pDbPage reference remains valid.
52455 **
52456 ** The isCommit flag indicates that there is no need to remember that
52457 ** the journal needs to be sync()ed before database page pDbPage->pgno 
52458 ** can be written to. The caller has already promised not to write to that
52459 ** page.
52460 */
52461 static int relocatePage(
52462   BtShared *pBt,           /* Btree */
52463   MemPage *pDbPage,        /* Open page to move */
52464   u8 eType,                /* Pointer map 'type' entry for pDbPage */
52465   Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
52466   Pgno iFreePage,          /* The location to move pDbPage to */
52467   int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
52468 ){
52469   MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
52470   Pgno iDbPage = pDbPage->pgno;
52471   Pager *pPager = pBt->pPager;
52472   int rc;
52473
52474   assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 || 
52475       eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
52476   assert( sqlite3_mutex_held(pBt->mutex) );
52477   assert( pDbPage->pBt==pBt );
52478
52479   /* Move page iDbPage from its current location to page number iFreePage */
52480   TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n", 
52481       iDbPage, iFreePage, iPtrPage, eType));
52482   rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
52483   if( rc!=SQLITE_OK ){
52484     return rc;
52485   }
52486   pDbPage->pgno = iFreePage;
52487
52488   /* If pDbPage was a btree-page, then it may have child pages and/or cells
52489   ** that point to overflow pages. The pointer map entries for all these
52490   ** pages need to be changed.
52491   **
52492   ** If pDbPage is an overflow page, then the first 4 bytes may store a
52493   ** pointer to a subsequent overflow page. If this is the case, then
52494   ** the pointer map needs to be updated for the subsequent overflow page.
52495   */
52496   if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
52497     rc = setChildPtrmaps(pDbPage);
52498     if( rc!=SQLITE_OK ){
52499       return rc;
52500     }
52501   }else{
52502     Pgno nextOvfl = get4byte(pDbPage->aData);
52503     if( nextOvfl!=0 ){
52504       ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
52505       if( rc!=SQLITE_OK ){
52506         return rc;
52507       }
52508     }
52509   }
52510
52511   /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
52512   ** that it points at iFreePage. Also fix the pointer map entry for
52513   ** iPtrPage.
52514   */
52515   if( eType!=PTRMAP_ROOTPAGE ){
52516     rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0, 0);
52517     if( rc!=SQLITE_OK ){
52518       return rc;
52519     }
52520     rc = sqlite3PagerWrite(pPtrPage->pDbPage);
52521     if( rc!=SQLITE_OK ){
52522       releasePage(pPtrPage);
52523       return rc;
52524     }
52525     rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
52526     releasePage(pPtrPage);
52527     if( rc==SQLITE_OK ){
52528       ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
52529     }
52530   }
52531   return rc;
52532 }
52533
52534 /* Forward declaration required by incrVacuumStep(). */
52535 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
52536
52537 /*
52538 ** Perform a single step of an incremental-vacuum. If successful, return
52539 ** SQLITE_OK. If there is no work to do (and therefore no point in 
52540 ** calling this function again), return SQLITE_DONE. Or, if an error 
52541 ** occurs, return some other error code.
52542 **
52543 ** More specificly, this function attempts to re-organize the database so 
52544 ** that the last page of the file currently in use is no longer in use.
52545 **
52546 ** Parameter nFin is the number of pages that this database would contain
52547 ** were this function called until it returns SQLITE_DONE.
52548 **
52549 ** If the bCommit parameter is non-zero, this function assumes that the 
52550 ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE 
52551 ** or an error. bCommit is passed true for an auto-vacuum-on-commmit 
52552 ** operation, or false for an incremental vacuum.
52553 */
52554 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
52555   Pgno nFreeList;           /* Number of pages still on the free-list */
52556   int rc;
52557
52558   assert( sqlite3_mutex_held(pBt->mutex) );
52559   assert( iLastPg>nFin );
52560
52561   if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
52562     u8 eType;
52563     Pgno iPtrPage;
52564
52565     nFreeList = get4byte(&pBt->pPage1->aData[36]);
52566     if( nFreeList==0 ){
52567       return SQLITE_DONE;
52568     }
52569
52570     rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
52571     if( rc!=SQLITE_OK ){
52572       return rc;
52573     }
52574     if( eType==PTRMAP_ROOTPAGE ){
52575       return SQLITE_CORRUPT_BKPT;
52576     }
52577
52578     if( eType==PTRMAP_FREEPAGE ){
52579       if( bCommit==0 ){
52580         /* Remove the page from the files free-list. This is not required
52581         ** if bCommit is non-zero. In that case, the free-list will be
52582         ** truncated to zero after this function returns, so it doesn't 
52583         ** matter if it still contains some garbage entries.
52584         */
52585         Pgno iFreePg;
52586         MemPage *pFreePg;
52587         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
52588         if( rc!=SQLITE_OK ){
52589           return rc;
52590         }
52591         assert( iFreePg==iLastPg );
52592         releasePage(pFreePg);
52593       }
52594     } else {
52595       Pgno iFreePg;             /* Index of free page to move pLastPg to */
52596       MemPage *pLastPg;
52597       u8 eMode = BTALLOC_ANY;   /* Mode parameter for allocateBtreePage() */
52598       Pgno iNear = 0;           /* nearby parameter for allocateBtreePage() */
52599
52600       rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0, 0);
52601       if( rc!=SQLITE_OK ){
52602         return rc;
52603       }
52604
52605       /* If bCommit is zero, this loop runs exactly once and page pLastPg
52606       ** is swapped with the first free page pulled off the free list.
52607       **
52608       ** On the other hand, if bCommit is greater than zero, then keep
52609       ** looping until a free-page located within the first nFin pages
52610       ** of the file is found.
52611       */
52612       if( bCommit==0 ){
52613         eMode = BTALLOC_LE;
52614         iNear = nFin;
52615       }
52616       do {
52617         MemPage *pFreePg;
52618         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
52619         if( rc!=SQLITE_OK ){
52620           releasePage(pLastPg);
52621           return rc;
52622         }
52623         releasePage(pFreePg);
52624       }while( bCommit && iFreePg>nFin );
52625       assert( iFreePg<iLastPg );
52626       
52627       rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
52628       releasePage(pLastPg);
52629       if( rc!=SQLITE_OK ){
52630         return rc;
52631       }
52632     }
52633   }
52634
52635   if( bCommit==0 ){
52636     do {
52637       iLastPg--;
52638     }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
52639     pBt->bDoTruncate = 1;
52640     pBt->nPage = iLastPg;
52641   }
52642   return SQLITE_OK;
52643 }
52644
52645 /*
52646 ** The database opened by the first argument is an auto-vacuum database
52647 ** nOrig pages in size containing nFree free pages. Return the expected 
52648 ** size of the database in pages following an auto-vacuum operation.
52649 */
52650 static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
52651   int nEntry;                     /* Number of entries on one ptrmap page */
52652   Pgno nPtrmap;                   /* Number of PtrMap pages to be freed */
52653   Pgno nFin;                      /* Return value */
52654
52655   nEntry = pBt->usableSize/5;
52656   nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
52657   nFin = nOrig - nFree - nPtrmap;
52658   if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
52659     nFin--;
52660   }
52661   while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
52662     nFin--;
52663   }
52664
52665   return nFin;
52666 }
52667
52668 /*
52669 ** A write-transaction must be opened before calling this function.
52670 ** It performs a single unit of work towards an incremental vacuum.
52671 **
52672 ** If the incremental vacuum is finished after this function has run,
52673 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
52674 ** SQLITE_OK is returned. Otherwise an SQLite error code. 
52675 */
52676 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
52677   int rc;
52678   BtShared *pBt = p->pBt;
52679
52680   sqlite3BtreeEnter(p);
52681   assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
52682   if( !pBt->autoVacuum ){
52683     rc = SQLITE_DONE;
52684   }else{
52685     Pgno nOrig = btreePagecount(pBt);
52686     Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
52687     Pgno nFin = finalDbSize(pBt, nOrig, nFree);
52688
52689     if( nOrig<nFin ){
52690       rc = SQLITE_CORRUPT_BKPT;
52691     }else if( nFree>0 ){
52692       rc = saveAllCursors(pBt, 0, 0);
52693       if( rc==SQLITE_OK ){
52694         invalidateAllOverflowCache(pBt);
52695         rc = incrVacuumStep(pBt, nFin, nOrig, 0);
52696       }
52697       if( rc==SQLITE_OK ){
52698         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
52699         put4byte(&pBt->pPage1->aData[28], pBt->nPage);
52700       }
52701     }else{
52702       rc = SQLITE_DONE;
52703     }
52704   }
52705   sqlite3BtreeLeave(p);
52706   return rc;
52707 }
52708
52709 /*
52710 ** This routine is called prior to sqlite3PagerCommit when a transaction
52711 ** is commited for an auto-vacuum database.
52712 **
52713 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
52714 ** the database file should be truncated to during the commit process. 
52715 ** i.e. the database has been reorganized so that only the first *pnTrunc
52716 ** pages are in use.
52717 */
52718 static int autoVacuumCommit(BtShared *pBt){
52719   int rc = SQLITE_OK;
52720   Pager *pPager = pBt->pPager;
52721   VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
52722
52723   assert( sqlite3_mutex_held(pBt->mutex) );
52724   invalidateAllOverflowCache(pBt);
52725   assert(pBt->autoVacuum);
52726   if( !pBt->incrVacuum ){
52727     Pgno nFin;         /* Number of pages in database after autovacuuming */
52728     Pgno nFree;        /* Number of pages on the freelist initially */
52729     Pgno iFree;        /* The next page to be freed */
52730     Pgno nOrig;        /* Database size before freeing */
52731
52732     nOrig = btreePagecount(pBt);
52733     if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
52734       /* It is not possible to create a database for which the final page
52735       ** is either a pointer-map page or the pending-byte page. If one
52736       ** is encountered, this indicates corruption.
52737       */
52738       return SQLITE_CORRUPT_BKPT;
52739     }
52740
52741     nFree = get4byte(&pBt->pPage1->aData[36]);
52742     nFin = finalDbSize(pBt, nOrig, nFree);
52743     if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
52744     if( nFin<nOrig ){
52745       rc = saveAllCursors(pBt, 0, 0);
52746     }
52747     for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
52748       rc = incrVacuumStep(pBt, nFin, iFree, 1);
52749     }
52750     if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
52751       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
52752       put4byte(&pBt->pPage1->aData[32], 0);
52753       put4byte(&pBt->pPage1->aData[36], 0);
52754       put4byte(&pBt->pPage1->aData[28], nFin);
52755       pBt->bDoTruncate = 1;
52756       pBt->nPage = nFin;
52757     }
52758     if( rc!=SQLITE_OK ){
52759       sqlite3PagerRollback(pPager);
52760     }
52761   }
52762
52763   assert( nRef>=sqlite3PagerRefcount(pPager) );
52764   return rc;
52765 }
52766
52767 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
52768 # define setChildPtrmaps(x) SQLITE_OK
52769 #endif
52770
52771 /*
52772 ** This routine does the first phase of a two-phase commit.  This routine
52773 ** causes a rollback journal to be created (if it does not already exist)
52774 ** and populated with enough information so that if a power loss occurs
52775 ** the database can be restored to its original state by playing back
52776 ** the journal.  Then the contents of the journal are flushed out to
52777 ** the disk.  After the journal is safely on oxide, the changes to the
52778 ** database are written into the database file and flushed to oxide.
52779 ** At the end of this call, the rollback journal still exists on the
52780 ** disk and we are still holding all locks, so the transaction has not
52781 ** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
52782 ** commit process.
52783 **
52784 ** This call is a no-op if no write-transaction is currently active on pBt.
52785 **
52786 ** Otherwise, sync the database file for the btree pBt. zMaster points to
52787 ** the name of a master journal file that should be written into the
52788 ** individual journal file, or is NULL, indicating no master journal file 
52789 ** (single database transaction).
52790 **
52791 ** When this is called, the master journal should already have been
52792 ** created, populated with this journal pointer and synced to disk.
52793 **
52794 ** Once this is routine has returned, the only thing required to commit
52795 ** the write-transaction for this database file is to delete the journal.
52796 */
52797 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
52798   int rc = SQLITE_OK;
52799   if( p->inTrans==TRANS_WRITE ){
52800     BtShared *pBt = p->pBt;
52801     sqlite3BtreeEnter(p);
52802 #ifndef SQLITE_OMIT_AUTOVACUUM
52803     if( pBt->autoVacuum ){
52804       rc = autoVacuumCommit(pBt);
52805       if( rc!=SQLITE_OK ){
52806         sqlite3BtreeLeave(p);
52807         return rc;
52808       }
52809     }
52810     if( pBt->bDoTruncate ){
52811       sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
52812     }
52813 #endif
52814     rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
52815     sqlite3BtreeLeave(p);
52816   }
52817   return rc;
52818 }
52819
52820 /*
52821 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
52822 ** at the conclusion of a transaction.
52823 */
52824 static void btreeEndTransaction(Btree *p){
52825   BtShared *pBt = p->pBt;
52826   assert( sqlite3BtreeHoldsMutex(p) );
52827
52828 #ifndef SQLITE_OMIT_AUTOVACUUM
52829   pBt->bDoTruncate = 0;
52830 #endif
52831   if( p->inTrans>TRANS_NONE && p->db->activeVdbeCnt>1 ){
52832     /* If there are other active statements that belong to this database
52833     ** handle, downgrade to a read-only transaction. The other statements
52834     ** may still be reading from the database.  */
52835     downgradeAllSharedCacheTableLocks(p);
52836     p->inTrans = TRANS_READ;
52837   }else{
52838     /* If the handle had any kind of transaction open, decrement the 
52839     ** transaction count of the shared btree. If the transaction count 
52840     ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
52841     ** call below will unlock the pager.  */
52842     if( p->inTrans!=TRANS_NONE ){
52843       clearAllSharedCacheTableLocks(p);
52844       pBt->nTransaction--;
52845       if( 0==pBt->nTransaction ){
52846         pBt->inTransaction = TRANS_NONE;
52847       }
52848     }
52849
52850     /* Set the current transaction state to TRANS_NONE and unlock the 
52851     ** pager if this call closed the only read or write transaction.  */
52852     p->inTrans = TRANS_NONE;
52853     unlockBtreeIfUnused(pBt);
52854   }
52855
52856   btreeIntegrity(p);
52857 }
52858
52859 /*
52860 ** Commit the transaction currently in progress.
52861 **
52862 ** This routine implements the second phase of a 2-phase commit.  The
52863 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
52864 ** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
52865 ** routine did all the work of writing information out to disk and flushing the
52866 ** contents so that they are written onto the disk platter.  All this
52867 ** routine has to do is delete or truncate or zero the header in the
52868 ** the rollback journal (which causes the transaction to commit) and
52869 ** drop locks.
52870 **
52871 ** Normally, if an error occurs while the pager layer is attempting to 
52872 ** finalize the underlying journal file, this function returns an error and
52873 ** the upper layer will attempt a rollback. However, if the second argument
52874 ** is non-zero then this b-tree transaction is part of a multi-file 
52875 ** transaction. In this case, the transaction has already been committed 
52876 ** (by deleting a master journal file) and the caller will ignore this 
52877 ** functions return code. So, even if an error occurs in the pager layer,
52878 ** reset the b-tree objects internal state to indicate that the write
52879 ** transaction has been closed. This is quite safe, as the pager will have
52880 ** transitioned to the error state.
52881 **
52882 ** This will release the write lock on the database file.  If there
52883 ** are no active cursors, it also releases the read lock.
52884 */
52885 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
52886
52887   if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
52888   sqlite3BtreeEnter(p);
52889   btreeIntegrity(p);
52890
52891   /* If the handle has a write-transaction open, commit the shared-btrees 
52892   ** transaction and set the shared state to TRANS_READ.
52893   */
52894   if( p->inTrans==TRANS_WRITE ){
52895     int rc;
52896     BtShared *pBt = p->pBt;
52897     assert( pBt->inTransaction==TRANS_WRITE );
52898     assert( pBt->nTransaction>0 );
52899     rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
52900     if( rc!=SQLITE_OK && bCleanup==0 ){
52901       sqlite3BtreeLeave(p);
52902       return rc;
52903     }
52904     pBt->inTransaction = TRANS_READ;
52905     btreeClearHasContent(pBt);
52906   }
52907
52908   btreeEndTransaction(p);
52909   sqlite3BtreeLeave(p);
52910   return SQLITE_OK;
52911 }
52912
52913 /*
52914 ** Do both phases of a commit.
52915 */
52916 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
52917   int rc;
52918   sqlite3BtreeEnter(p);
52919   rc = sqlite3BtreeCommitPhaseOne(p, 0);
52920   if( rc==SQLITE_OK ){
52921     rc = sqlite3BtreeCommitPhaseTwo(p, 0);
52922   }
52923   sqlite3BtreeLeave(p);
52924   return rc;
52925 }
52926
52927 /*
52928 ** This routine sets the state to CURSOR_FAULT and the error
52929 ** code to errCode for every cursor on BtShared that pBtree
52930 ** references.
52931 **
52932 ** Every cursor is tripped, including cursors that belong
52933 ** to other database connections that happen to be sharing
52934 ** the cache with pBtree.
52935 **
52936 ** This routine gets called when a rollback occurs.
52937 ** All cursors using the same cache must be tripped
52938 ** to prevent them from trying to use the btree after
52939 ** the rollback.  The rollback may have deleted tables
52940 ** or moved root pages, so it is not sufficient to
52941 ** save the state of the cursor.  The cursor must be
52942 ** invalidated.
52943 */
52944 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
52945   BtCursor *p;
52946   if( pBtree==0 ) return;
52947   sqlite3BtreeEnter(pBtree);
52948   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
52949     int i;
52950     sqlite3BtreeClearCursor(p);
52951     p->eState = CURSOR_FAULT;
52952     p->skipNext = errCode;
52953     for(i=0; i<=p->iPage; i++){
52954       releasePage(p->apPage[i]);
52955       p->apPage[i] = 0;
52956     }
52957   }
52958   sqlite3BtreeLeave(pBtree);
52959 }
52960
52961 /*
52962 ** Rollback the transaction in progress.  All cursors will be
52963 ** invalided by this operation.  Any attempt to use a cursor
52964 ** that was open at the beginning of this operation will result
52965 ** in an error.
52966 **
52967 ** This will release the write lock on the database file.  If there
52968 ** are no active cursors, it also releases the read lock.
52969 */
52970 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode){
52971   int rc;
52972   BtShared *pBt = p->pBt;
52973   MemPage *pPage1;
52974
52975   sqlite3BtreeEnter(p);
52976   if( tripCode==SQLITE_OK ){
52977     rc = tripCode = saveAllCursors(pBt, 0, 0);
52978   }else{
52979     rc = SQLITE_OK;
52980   }
52981   if( tripCode ){
52982     sqlite3BtreeTripAllCursors(p, tripCode);
52983   }
52984   btreeIntegrity(p);
52985
52986   if( p->inTrans==TRANS_WRITE ){
52987     int rc2;
52988
52989     assert( TRANS_WRITE==pBt->inTransaction );
52990     rc2 = sqlite3PagerRollback(pBt->pPager);
52991     if( rc2!=SQLITE_OK ){
52992       rc = rc2;
52993     }
52994
52995     /* The rollback may have destroyed the pPage1->aData value.  So
52996     ** call btreeGetPage() on page 1 again to make
52997     ** sure pPage1->aData is set correctly. */
52998     if( btreeGetPage(pBt, 1, &pPage1, 0, 0)==SQLITE_OK ){
52999       int nPage = get4byte(28+(u8*)pPage1->aData);
53000       testcase( nPage==0 );
53001       if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
53002       testcase( pBt->nPage!=nPage );
53003       pBt->nPage = nPage;
53004       releasePage(pPage1);
53005     }
53006     assert( countValidCursors(pBt, 1)==0 );
53007     pBt->inTransaction = TRANS_READ;
53008     btreeClearHasContent(pBt);
53009   }
53010
53011   btreeEndTransaction(p);
53012   sqlite3BtreeLeave(p);
53013   return rc;
53014 }
53015
53016 /*
53017 ** Start a statement subtransaction. The subtransaction can can be rolled
53018 ** back independently of the main transaction. You must start a transaction 
53019 ** before starting a subtransaction. The subtransaction is ended automatically 
53020 ** if the main transaction commits or rolls back.
53021 **
53022 ** Statement subtransactions are used around individual SQL statements
53023 ** that are contained within a BEGIN...COMMIT block.  If a constraint
53024 ** error occurs within the statement, the effect of that one statement
53025 ** can be rolled back without having to rollback the entire transaction.
53026 **
53027 ** A statement sub-transaction is implemented as an anonymous savepoint. The
53028 ** value passed as the second parameter is the total number of savepoints,
53029 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
53030 ** are no active savepoints and no other statement-transactions open,
53031 ** iStatement is 1. This anonymous savepoint can be released or rolled back
53032 ** using the sqlite3BtreeSavepoint() function.
53033 */
53034 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
53035   int rc;
53036   BtShared *pBt = p->pBt;
53037   sqlite3BtreeEnter(p);
53038   assert( p->inTrans==TRANS_WRITE );
53039   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
53040   assert( iStatement>0 );
53041   assert( iStatement>p->db->nSavepoint );
53042   assert( pBt->inTransaction==TRANS_WRITE );
53043   /* At the pager level, a statement transaction is a savepoint with
53044   ** an index greater than all savepoints created explicitly using
53045   ** SQL statements. It is illegal to open, release or rollback any
53046   ** such savepoints while the statement transaction savepoint is active.
53047   */
53048   rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
53049   sqlite3BtreeLeave(p);
53050   return rc;
53051 }
53052
53053 /*
53054 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
53055 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
53056 ** savepoint identified by parameter iSavepoint, depending on the value 
53057 ** of op.
53058 **
53059 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
53060 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the 
53061 ** contents of the entire transaction are rolled back. This is different
53062 ** from a normal transaction rollback, as no locks are released and the
53063 ** transaction remains open.
53064 */
53065 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
53066   int rc = SQLITE_OK;
53067   if( p && p->inTrans==TRANS_WRITE ){
53068     BtShared *pBt = p->pBt;
53069     assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
53070     assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
53071     sqlite3BtreeEnter(p);
53072     rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
53073     if( rc==SQLITE_OK ){
53074       if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
53075         pBt->nPage = 0;
53076       }
53077       rc = newDatabase(pBt);
53078       pBt->nPage = get4byte(28 + pBt->pPage1->aData);
53079
53080       /* The database size was written into the offset 28 of the header
53081       ** when the transaction started, so we know that the value at offset
53082       ** 28 is nonzero. */
53083       assert( pBt->nPage>0 );
53084     }
53085     sqlite3BtreeLeave(p);
53086   }
53087   return rc;
53088 }
53089
53090 /*
53091 ** Create a new cursor for the BTree whose root is on the page
53092 ** iTable. If a read-only cursor is requested, it is assumed that
53093 ** the caller already has at least a read-only transaction open
53094 ** on the database already. If a write-cursor is requested, then
53095 ** the caller is assumed to have an open write transaction.
53096 **
53097 ** If wrFlag==0, then the cursor can only be used for reading.
53098 ** If wrFlag==1, then the cursor can be used for reading or for
53099 ** writing if other conditions for writing are also met.  These
53100 ** are the conditions that must be met in order for writing to
53101 ** be allowed:
53102 **
53103 ** 1:  The cursor must have been opened with wrFlag==1
53104 **
53105 ** 2:  Other database connections that share the same pager cache
53106 **     but which are not in the READ_UNCOMMITTED state may not have
53107 **     cursors open with wrFlag==0 on the same table.  Otherwise
53108 **     the changes made by this write cursor would be visible to
53109 **     the read cursors in the other database connection.
53110 **
53111 ** 3:  The database must be writable (not on read-only media)
53112 **
53113 ** 4:  There must be an active transaction.
53114 **
53115 ** No checking is done to make sure that page iTable really is the
53116 ** root page of a b-tree.  If it is not, then the cursor acquired
53117 ** will not work correctly.
53118 **
53119 ** It is assumed that the sqlite3BtreeCursorZero() has been called
53120 ** on pCur to initialize the memory space prior to invoking this routine.
53121 */
53122 static int btreeCursor(
53123   Btree *p,                              /* The btree */
53124   int iTable,                            /* Root page of table to open */
53125   int wrFlag,                            /* 1 to write. 0 read-only */
53126   struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
53127   BtCursor *pCur                         /* Space for new cursor */
53128 ){
53129   BtShared *pBt = p->pBt;                /* Shared b-tree handle */
53130
53131   assert( sqlite3BtreeHoldsMutex(p) );
53132   assert( wrFlag==0 || wrFlag==1 );
53133
53134   /* The following assert statements verify that if this is a sharable 
53135   ** b-tree database, the connection is holding the required table locks, 
53136   ** and that no other connection has any open cursor that conflicts with 
53137   ** this lock.  */
53138   assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
53139   assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
53140
53141   /* Assert that the caller has opened the required transaction. */
53142   assert( p->inTrans>TRANS_NONE );
53143   assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
53144   assert( pBt->pPage1 && pBt->pPage1->aData );
53145
53146   if( NEVER(wrFlag && (pBt->btsFlags & BTS_READ_ONLY)!=0) ){
53147     return SQLITE_READONLY;
53148   }
53149   if( iTable==1 && btreePagecount(pBt)==0 ){
53150     assert( wrFlag==0 );
53151     iTable = 0;
53152   }
53153
53154   /* Now that no other errors can occur, finish filling in the BtCursor
53155   ** variables and link the cursor into the BtShared list.  */
53156   pCur->pgnoRoot = (Pgno)iTable;
53157   pCur->iPage = -1;
53158   pCur->pKeyInfo = pKeyInfo;
53159   pCur->pBtree = p;
53160   pCur->pBt = pBt;
53161   pCur->wrFlag = (u8)wrFlag;
53162   pCur->pNext = pBt->pCursor;
53163   if( pCur->pNext ){
53164     pCur->pNext->pPrev = pCur;
53165   }
53166   pBt->pCursor = pCur;
53167   pCur->eState = CURSOR_INVALID;
53168   pCur->cachedRowid = 0;
53169   return SQLITE_OK;
53170 }
53171 SQLITE_PRIVATE int sqlite3BtreeCursor(
53172   Btree *p,                                   /* The btree */
53173   int iTable,                                 /* Root page of table to open */
53174   int wrFlag,                                 /* 1 to write. 0 read-only */
53175   struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
53176   BtCursor *pCur                              /* Write new cursor here */
53177 ){
53178   int rc;
53179   sqlite3BtreeEnter(p);
53180   rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
53181   sqlite3BtreeLeave(p);
53182   return rc;
53183 }
53184
53185 /*
53186 ** Return the size of a BtCursor object in bytes.
53187 **
53188 ** This interfaces is needed so that users of cursors can preallocate
53189 ** sufficient storage to hold a cursor.  The BtCursor object is opaque
53190 ** to users so they cannot do the sizeof() themselves - they must call
53191 ** this routine.
53192 */
53193 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
53194   return ROUND8(sizeof(BtCursor));
53195 }
53196
53197 /*
53198 ** Initialize memory that will be converted into a BtCursor object.
53199 **
53200 ** The simple approach here would be to memset() the entire object
53201 ** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
53202 ** do not need to be zeroed and they are large, so we can save a lot
53203 ** of run-time by skipping the initialization of those elements.
53204 */
53205 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
53206   memset(p, 0, offsetof(BtCursor, iPage));
53207 }
53208
53209 /*
53210 ** Set the cached rowid value of every cursor in the same database file
53211 ** as pCur and having the same root page number as pCur.  The value is
53212 ** set to iRowid.
53213 **
53214 ** Only positive rowid values are considered valid for this cache.
53215 ** The cache is initialized to zero, indicating an invalid cache.
53216 ** A btree will work fine with zero or negative rowids.  We just cannot
53217 ** cache zero or negative rowids, which means tables that use zero or
53218 ** negative rowids might run a little slower.  But in practice, zero
53219 ** or negative rowids are very uncommon so this should not be a problem.
53220 */
53221 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
53222   BtCursor *p;
53223   for(p=pCur->pBt->pCursor; p; p=p->pNext){
53224     if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
53225   }
53226   assert( pCur->cachedRowid==iRowid );
53227 }
53228
53229 /*
53230 ** Return the cached rowid for the given cursor.  A negative or zero
53231 ** return value indicates that the rowid cache is invalid and should be
53232 ** ignored.  If the rowid cache has never before been set, then a
53233 ** zero is returned.
53234 */
53235 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
53236   return pCur->cachedRowid;
53237 }
53238
53239 /*
53240 ** Close a cursor.  The read lock on the database file is released
53241 ** when the last cursor is closed.
53242 */
53243 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
53244   Btree *pBtree = pCur->pBtree;
53245   if( pBtree ){
53246     int i;
53247     BtShared *pBt = pCur->pBt;
53248     sqlite3BtreeEnter(pBtree);
53249     sqlite3BtreeClearCursor(pCur);
53250     if( pCur->pPrev ){
53251       pCur->pPrev->pNext = pCur->pNext;
53252     }else{
53253       pBt->pCursor = pCur->pNext;
53254     }
53255     if( pCur->pNext ){
53256       pCur->pNext->pPrev = pCur->pPrev;
53257     }
53258     for(i=0; i<=pCur->iPage; i++){
53259       releasePage(pCur->apPage[i]);
53260     }
53261     unlockBtreeIfUnused(pBt);
53262     invalidateOverflowCache(pCur);
53263     /* sqlite3_free(pCur); */
53264     sqlite3BtreeLeave(pBtree);
53265   }
53266   return SQLITE_OK;
53267 }
53268
53269 /*
53270 ** Make sure the BtCursor* given in the argument has a valid
53271 ** BtCursor.info structure.  If it is not already valid, call
53272 ** btreeParseCell() to fill it in.
53273 **
53274 ** BtCursor.info is a cache of the information in the current cell.
53275 ** Using this cache reduces the number of calls to btreeParseCell().
53276 **
53277 ** 2007-06-25:  There is a bug in some versions of MSVC that cause the
53278 ** compiler to crash when getCellInfo() is implemented as a macro.
53279 ** But there is a measureable speed advantage to using the macro on gcc
53280 ** (when less compiler optimizations like -Os or -O0 are used and the
53281 ** compiler is not doing agressive inlining.)  So we use a real function
53282 ** for MSVC and a macro for everything else.  Ticket #2457.
53283 */
53284 #ifndef NDEBUG
53285   static void assertCellInfo(BtCursor *pCur){
53286     CellInfo info;
53287     int iPage = pCur->iPage;
53288     memset(&info, 0, sizeof(info));
53289     btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
53290     assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
53291   }
53292 #else
53293   #define assertCellInfo(x)
53294 #endif
53295 #ifdef _MSC_VER
53296   /* Use a real function in MSVC to work around bugs in that compiler. */
53297   static void getCellInfo(BtCursor *pCur){
53298     if( pCur->info.nSize==0 ){
53299       int iPage = pCur->iPage;
53300       btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
53301       pCur->validNKey = 1;
53302     }else{
53303       assertCellInfo(pCur);
53304     }
53305   }
53306 #else /* if not _MSC_VER */
53307   /* Use a macro in all other compilers so that the function is inlined */
53308 #define getCellInfo(pCur)                                                      \
53309   if( pCur->info.nSize==0 ){                                                   \
53310     int iPage = pCur->iPage;                                                   \
53311     btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
53312     pCur->validNKey = 1;                                                       \
53313   }else{                                                                       \
53314     assertCellInfo(pCur);                                                      \
53315   }
53316 #endif /* _MSC_VER */
53317
53318 #ifndef NDEBUG  /* The next routine used only within assert() statements */
53319 /*
53320 ** Return true if the given BtCursor is valid.  A valid cursor is one
53321 ** that is currently pointing to a row in a (non-empty) table.
53322 ** This is a verification routine is used only within assert() statements.
53323 */
53324 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
53325   return pCur && pCur->eState==CURSOR_VALID;
53326 }
53327 #endif /* NDEBUG */
53328
53329 /*
53330 ** Set *pSize to the size of the buffer needed to hold the value of
53331 ** the key for the current entry.  If the cursor is not pointing
53332 ** to a valid entry, *pSize is set to 0. 
53333 **
53334 ** For a table with the INTKEY flag set, this routine returns the key
53335 ** itself, not the number of bytes in the key.
53336 **
53337 ** The caller must position the cursor prior to invoking this routine.
53338 ** 
53339 ** This routine cannot fail.  It always returns SQLITE_OK.  
53340 */
53341 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
53342   assert( cursorHoldsMutex(pCur) );
53343   assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
53344   if( pCur->eState!=CURSOR_VALID ){
53345     *pSize = 0;
53346   }else{
53347     getCellInfo(pCur);
53348     *pSize = pCur->info.nKey;
53349   }
53350   return SQLITE_OK;
53351 }
53352
53353 /*
53354 ** Set *pSize to the number of bytes of data in the entry the
53355 ** cursor currently points to.
53356 **
53357 ** The caller must guarantee that the cursor is pointing to a non-NULL
53358 ** valid entry.  In other words, the calling procedure must guarantee
53359 ** that the cursor has Cursor.eState==CURSOR_VALID.
53360 **
53361 ** Failure is not possible.  This function always returns SQLITE_OK.
53362 ** It might just as well be a procedure (returning void) but we continue
53363 ** to return an integer result code for historical reasons.
53364 */
53365 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
53366   assert( cursorHoldsMutex(pCur) );
53367   assert( pCur->eState==CURSOR_VALID );
53368   getCellInfo(pCur);
53369   *pSize = pCur->info.nData;
53370   return SQLITE_OK;
53371 }
53372
53373 /*
53374 ** Given the page number of an overflow page in the database (parameter
53375 ** ovfl), this function finds the page number of the next page in the 
53376 ** linked list of overflow pages. If possible, it uses the auto-vacuum
53377 ** pointer-map data instead of reading the content of page ovfl to do so. 
53378 **
53379 ** If an error occurs an SQLite error code is returned. Otherwise:
53380 **
53381 ** The page number of the next overflow page in the linked list is 
53382 ** written to *pPgnoNext. If page ovfl is the last page in its linked 
53383 ** list, *pPgnoNext is set to zero. 
53384 **
53385 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
53386 ** to page number pOvfl was obtained, then *ppPage is set to point to that
53387 ** reference. It is the responsibility of the caller to call releasePage()
53388 ** on *ppPage to free the reference. In no reference was obtained (because
53389 ** the pointer-map was used to obtain the value for *pPgnoNext), then
53390 ** *ppPage is set to zero.
53391 */
53392 static int getOverflowPage(
53393   BtShared *pBt,               /* The database file */
53394   Pgno ovfl,                   /* Current overflow page number */
53395   MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
53396   Pgno *pPgnoNext              /* OUT: Next overflow page number */
53397 ){
53398   Pgno next = 0;
53399   MemPage *pPage = 0;
53400   int rc = SQLITE_OK;
53401
53402   assert( sqlite3_mutex_held(pBt->mutex) );
53403   assert(pPgnoNext);
53404
53405 #ifndef SQLITE_OMIT_AUTOVACUUM
53406   /* Try to find the next page in the overflow list using the
53407   ** autovacuum pointer-map pages. Guess that the next page in 
53408   ** the overflow list is page number (ovfl+1). If that guess turns 
53409   ** out to be wrong, fall back to loading the data of page 
53410   ** number ovfl to determine the next page number.
53411   */
53412   if( pBt->autoVacuum ){
53413     Pgno pgno;
53414     Pgno iGuess = ovfl+1;
53415     u8 eType;
53416
53417     while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
53418       iGuess++;
53419     }
53420
53421     if( iGuess<=btreePagecount(pBt) ){
53422       rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
53423       if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
53424         next = iGuess;
53425         rc = SQLITE_DONE;
53426       }
53427     }
53428   }
53429 #endif
53430
53431   assert( next==0 || rc==SQLITE_DONE );
53432   if( rc==SQLITE_OK ){
53433     rc = btreeGetPage(pBt, ovfl, &pPage, 0, (ppPage==0));
53434     assert( rc==SQLITE_OK || pPage==0 );
53435     if( rc==SQLITE_OK ){
53436       next = get4byte(pPage->aData);
53437     }
53438   }
53439
53440   *pPgnoNext = next;
53441   if( ppPage ){
53442     *ppPage = pPage;
53443   }else{
53444     releasePage(pPage);
53445   }
53446   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
53447 }
53448
53449 /*
53450 ** Copy data from a buffer to a page, or from a page to a buffer.
53451 **
53452 ** pPayload is a pointer to data stored on database page pDbPage.
53453 ** If argument eOp is false, then nByte bytes of data are copied
53454 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
53455 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
53456 ** of data are copied from the buffer pBuf to pPayload.
53457 **
53458 ** SQLITE_OK is returned on success, otherwise an error code.
53459 */
53460 static int copyPayload(
53461   void *pPayload,           /* Pointer to page data */
53462   void *pBuf,               /* Pointer to buffer */
53463   int nByte,                /* Number of bytes to copy */
53464   int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
53465   DbPage *pDbPage           /* Page containing pPayload */
53466 ){
53467   if( eOp ){
53468     /* Copy data from buffer to page (a write operation) */
53469     int rc = sqlite3PagerWrite(pDbPage);
53470     if( rc!=SQLITE_OK ){
53471       return rc;
53472     }
53473     memcpy(pPayload, pBuf, nByte);
53474   }else{
53475     /* Copy data from page to buffer (a read operation) */
53476     memcpy(pBuf, pPayload, nByte);
53477   }
53478   return SQLITE_OK;
53479 }
53480
53481 /*
53482 ** This function is used to read or overwrite payload information
53483 ** for the entry that the pCur cursor is pointing to. If the eOp
53484 ** parameter is 0, this is a read operation (data copied into
53485 ** buffer pBuf). If it is non-zero, a write (data copied from
53486 ** buffer pBuf).
53487 **
53488 ** A total of "amt" bytes are read or written beginning at "offset".
53489 ** Data is read to or from the buffer pBuf.
53490 **
53491 ** The content being read or written might appear on the main page
53492 ** or be scattered out on multiple overflow pages.
53493 **
53494 ** If the BtCursor.isIncrblobHandle flag is set, and the current
53495 ** cursor entry uses one or more overflow pages, this function
53496 ** allocates space for and lazily popluates the overflow page-list 
53497 ** cache array (BtCursor.aOverflow). Subsequent calls use this
53498 ** cache to make seeking to the supplied offset more efficient.
53499 **
53500 ** Once an overflow page-list cache has been allocated, it may be
53501 ** invalidated if some other cursor writes to the same table, or if
53502 ** the cursor is moved to a different row. Additionally, in auto-vacuum
53503 ** mode, the following events may invalidate an overflow page-list cache.
53504 **
53505 **   * An incremental vacuum,
53506 **   * A commit in auto_vacuum="full" mode,
53507 **   * Creating a table (may require moving an overflow page).
53508 */
53509 static int accessPayload(
53510   BtCursor *pCur,      /* Cursor pointing to entry to read from */
53511   u32 offset,          /* Begin reading this far into payload */
53512   u32 amt,             /* Read this many bytes */
53513   unsigned char *pBuf, /* Write the bytes into this buffer */ 
53514   int eOp              /* zero to read. non-zero to write. */
53515 ){
53516   unsigned char *aPayload;
53517   int rc = SQLITE_OK;
53518   u32 nKey;
53519   int iIdx = 0;
53520   MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
53521   BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
53522
53523   assert( pPage );
53524   assert( pCur->eState==CURSOR_VALID );
53525   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
53526   assert( cursorHoldsMutex(pCur) );
53527
53528   getCellInfo(pCur);
53529   aPayload = pCur->info.pCell + pCur->info.nHeader;
53530   nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
53531
53532   if( NEVER(offset+amt > nKey+pCur->info.nData) 
53533    || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
53534   ){
53535     /* Trying to read or write past the end of the data is an error */
53536     return SQLITE_CORRUPT_BKPT;
53537   }
53538
53539   /* Check if data must be read/written to/from the btree page itself. */
53540   if( offset<pCur->info.nLocal ){
53541     int a = amt;
53542     if( a+offset>pCur->info.nLocal ){
53543       a = pCur->info.nLocal - offset;
53544     }
53545     rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
53546     offset = 0;
53547     pBuf += a;
53548     amt -= a;
53549   }else{
53550     offset -= pCur->info.nLocal;
53551   }
53552
53553   if( rc==SQLITE_OK && amt>0 ){
53554     const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
53555     Pgno nextPage;
53556
53557     nextPage = get4byte(&aPayload[pCur->info.nLocal]);
53558
53559 #ifndef SQLITE_OMIT_INCRBLOB
53560     /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
53561     ** has not been allocated, allocate it now. The array is sized at
53562     ** one entry for each overflow page in the overflow chain. The
53563     ** page number of the first overflow page is stored in aOverflow[0],
53564     ** etc. A value of 0 in the aOverflow[] array means "not yet known"
53565     ** (the cache is lazily populated).
53566     */
53567     if( pCur->isIncrblobHandle && !pCur->aOverflow ){
53568       int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
53569       pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
53570       /* nOvfl is always positive.  If it were zero, fetchPayload would have
53571       ** been used instead of this routine. */
53572       if( ALWAYS(nOvfl) && !pCur->aOverflow ){
53573         rc = SQLITE_NOMEM;
53574       }
53575     }
53576
53577     /* If the overflow page-list cache has been allocated and the
53578     ** entry for the first required overflow page is valid, skip
53579     ** directly to it.
53580     */
53581     if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
53582       iIdx = (offset/ovflSize);
53583       nextPage = pCur->aOverflow[iIdx];
53584       offset = (offset%ovflSize);
53585     }
53586 #endif
53587
53588     for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
53589
53590 #ifndef SQLITE_OMIT_INCRBLOB
53591       /* If required, populate the overflow page-list cache. */
53592       if( pCur->aOverflow ){
53593         assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
53594         pCur->aOverflow[iIdx] = nextPage;
53595       }
53596 #endif
53597
53598       if( offset>=ovflSize ){
53599         /* The only reason to read this page is to obtain the page
53600         ** number for the next page in the overflow chain. The page
53601         ** data is not required. So first try to lookup the overflow
53602         ** page-list cache, if any, then fall back to the getOverflowPage()
53603         ** function.
53604         */
53605 #ifndef SQLITE_OMIT_INCRBLOB
53606         if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
53607           nextPage = pCur->aOverflow[iIdx+1];
53608         } else 
53609 #endif
53610           rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
53611         offset -= ovflSize;
53612       }else{
53613         /* Need to read this page properly. It contains some of the
53614         ** range of data that is being read (eOp==0) or written (eOp!=0).
53615         */
53616 #ifdef SQLITE_DIRECT_OVERFLOW_READ
53617         sqlite3_file *fd;
53618 #endif
53619         int a = amt;
53620         if( a + offset > ovflSize ){
53621           a = ovflSize - offset;
53622         }
53623
53624 #ifdef SQLITE_DIRECT_OVERFLOW_READ
53625         /* If all the following are true:
53626         **
53627         **   1) this is a read operation, and 
53628         **   2) data is required from the start of this overflow page, and
53629         **   3) the database is file-backed, and
53630         **   4) there is no open write-transaction, and
53631         **   5) the database is not a WAL database,
53632         **
53633         ** then data can be read directly from the database file into the
53634         ** output buffer, bypassing the page-cache altogether. This speeds
53635         ** up loading large records that span many overflow pages.
53636         */
53637         if( eOp==0                                             /* (1) */
53638          && offset==0                                          /* (2) */
53639          && pBt->inTransaction==TRANS_READ                     /* (4) */
53640          && (fd = sqlite3PagerFile(pBt->pPager))->pMethods     /* (3) */
53641          && pBt->pPage1->aData[19]==0x01                       /* (5) */
53642         ){
53643           u8 aSave[4];
53644           u8 *aWrite = &pBuf[-4];
53645           memcpy(aSave, aWrite, 4);
53646           rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
53647           nextPage = get4byte(aWrite);
53648           memcpy(aWrite, aSave, 4);
53649         }else
53650 #endif
53651
53652         {
53653           DbPage *pDbPage;
53654           rc = sqlite3PagerAcquire(pBt->pPager, nextPage, &pDbPage,
53655               (eOp==0 ? PAGER_ACQUIRE_READONLY : 0)
53656           );
53657           if( rc==SQLITE_OK ){
53658             aPayload = sqlite3PagerGetData(pDbPage);
53659             nextPage = get4byte(aPayload);
53660             rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
53661             sqlite3PagerUnref(pDbPage);
53662             offset = 0;
53663           }
53664         }
53665         amt -= a;
53666         pBuf += a;
53667       }
53668     }
53669   }
53670
53671   if( rc==SQLITE_OK && amt>0 ){
53672     return SQLITE_CORRUPT_BKPT;
53673   }
53674   return rc;
53675 }
53676
53677 /*
53678 ** Read part of the key associated with cursor pCur.  Exactly
53679 ** "amt" bytes will be transfered into pBuf[].  The transfer
53680 ** begins at "offset".
53681 **
53682 ** The caller must ensure that pCur is pointing to a valid row
53683 ** in the table.
53684 **
53685 ** Return SQLITE_OK on success or an error code if anything goes
53686 ** wrong.  An error is returned if "offset+amt" is larger than
53687 ** the available payload.
53688 */
53689 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
53690   assert( cursorHoldsMutex(pCur) );
53691   assert( pCur->eState==CURSOR_VALID );
53692   assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
53693   assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
53694   return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
53695 }
53696
53697 /*
53698 ** Read part of the data associated with cursor pCur.  Exactly
53699 ** "amt" bytes will be transfered into pBuf[].  The transfer
53700 ** begins at "offset".
53701 **
53702 ** Return SQLITE_OK on success or an error code if anything goes
53703 ** wrong.  An error is returned if "offset+amt" is larger than
53704 ** the available payload.
53705 */
53706 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
53707   int rc;
53708
53709 #ifndef SQLITE_OMIT_INCRBLOB
53710   if ( pCur->eState==CURSOR_INVALID ){
53711     return SQLITE_ABORT;
53712   }
53713 #endif
53714
53715   assert( cursorHoldsMutex(pCur) );
53716   rc = restoreCursorPosition(pCur);
53717   if( rc==SQLITE_OK ){
53718     assert( pCur->eState==CURSOR_VALID );
53719     assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
53720     assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
53721     rc = accessPayload(pCur, offset, amt, pBuf, 0);
53722   }
53723   return rc;
53724 }
53725
53726 /*
53727 ** Return a pointer to payload information from the entry that the 
53728 ** pCur cursor is pointing to.  The pointer is to the beginning of
53729 ** the key if skipKey==0 and it points to the beginning of data if
53730 ** skipKey==1.  The number of bytes of available key/data is written
53731 ** into *pAmt.  If *pAmt==0, then the value returned will not be
53732 ** a valid pointer.
53733 **
53734 ** This routine is an optimization.  It is common for the entire key
53735 ** and data to fit on the local page and for there to be no overflow
53736 ** pages.  When that is so, this routine can be used to access the
53737 ** key and data without making a copy.  If the key and/or data spills
53738 ** onto overflow pages, then accessPayload() must be used to reassemble
53739 ** the key/data and copy it into a preallocated buffer.
53740 **
53741 ** The pointer returned by this routine looks directly into the cached
53742 ** page of the database.  The data might change or move the next time
53743 ** any btree routine is called.
53744 */
53745 static const unsigned char *fetchPayload(
53746   BtCursor *pCur,      /* Cursor pointing to entry to read from */
53747   int *pAmt,           /* Write the number of available bytes here */
53748   int skipKey          /* read beginning at data if this is true */
53749 ){
53750   unsigned char *aPayload;
53751   MemPage *pPage;
53752   u32 nKey;
53753   u32 nLocal;
53754
53755   assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
53756   assert( pCur->eState==CURSOR_VALID );
53757   assert( cursorHoldsMutex(pCur) );
53758   pPage = pCur->apPage[pCur->iPage];
53759   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
53760   if( NEVER(pCur->info.nSize==0) ){
53761     btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],
53762                    &pCur->info);
53763   }
53764   aPayload = pCur->info.pCell;
53765   aPayload += pCur->info.nHeader;
53766   if( pPage->intKey ){
53767     nKey = 0;
53768   }else{
53769     nKey = (int)pCur->info.nKey;
53770   }
53771   if( skipKey ){
53772     aPayload += nKey;
53773     nLocal = pCur->info.nLocal - nKey;
53774   }else{
53775     nLocal = pCur->info.nLocal;
53776     assert( nLocal<=nKey );
53777   }
53778   *pAmt = nLocal;
53779   return aPayload;
53780 }
53781
53782
53783 /*
53784 ** For the entry that cursor pCur is point to, return as
53785 ** many bytes of the key or data as are available on the local
53786 ** b-tree page.  Write the number of available bytes into *pAmt.
53787 **
53788 ** The pointer returned is ephemeral.  The key/data may move
53789 ** or be destroyed on the next call to any Btree routine,
53790 ** including calls from other threads against the same cache.
53791 ** Hence, a mutex on the BtShared should be held prior to calling
53792 ** this routine.
53793 **
53794 ** These routines is used to get quick access to key and data
53795 ** in the common case where no overflow pages are used.
53796 */
53797 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
53798   const void *p = 0;
53799   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
53800   assert( cursorHoldsMutex(pCur) );
53801   if( ALWAYS(pCur->eState==CURSOR_VALID) ){
53802     p = (const void*)fetchPayload(pCur, pAmt, 0);
53803   }
53804   return p;
53805 }
53806 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
53807   const void *p = 0;
53808   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
53809   assert( cursorHoldsMutex(pCur) );
53810   if( ALWAYS(pCur->eState==CURSOR_VALID) ){
53811     p = (const void*)fetchPayload(pCur, pAmt, 1);
53812   }
53813   return p;
53814 }
53815
53816
53817 /*
53818 ** Move the cursor down to a new child page.  The newPgno argument is the
53819 ** page number of the child page to move to.
53820 **
53821 ** This function returns SQLITE_CORRUPT if the page-header flags field of
53822 ** the new child page does not match the flags field of the parent (i.e.
53823 ** if an intkey page appears to be the parent of a non-intkey page, or
53824 ** vice-versa).
53825 */
53826 static int moveToChild(BtCursor *pCur, u32 newPgno){
53827   int rc;
53828   int i = pCur->iPage;
53829   MemPage *pNewPage;
53830   BtShared *pBt = pCur->pBt;
53831
53832   assert( cursorHoldsMutex(pCur) );
53833   assert( pCur->eState==CURSOR_VALID );
53834   assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
53835   assert( pCur->iPage>=0 );
53836   if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
53837     return SQLITE_CORRUPT_BKPT;
53838   }
53839   rc = getAndInitPage(pBt, newPgno, &pNewPage, (pCur->wrFlag==0));
53840   if( rc ) return rc;
53841   pCur->apPage[i+1] = pNewPage;
53842   pCur->aiIdx[i+1] = 0;
53843   pCur->iPage++;
53844
53845   pCur->info.nSize = 0;
53846   pCur->validNKey = 0;
53847   if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
53848     return SQLITE_CORRUPT_BKPT;
53849   }
53850   return SQLITE_OK;
53851 }
53852
53853 #if 0
53854 /*
53855 ** Page pParent is an internal (non-leaf) tree page. This function 
53856 ** asserts that page number iChild is the left-child if the iIdx'th
53857 ** cell in page pParent. Or, if iIdx is equal to the total number of
53858 ** cells in pParent, that page number iChild is the right-child of
53859 ** the page.
53860 */
53861 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
53862   assert( iIdx<=pParent->nCell );
53863   if( iIdx==pParent->nCell ){
53864     assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
53865   }else{
53866     assert( get4byte(findCell(pParent, iIdx))==iChild );
53867   }
53868 }
53869 #else
53870 #  define assertParentIndex(x,y,z) 
53871 #endif
53872
53873 /*
53874 ** Move the cursor up to the parent page.
53875 **
53876 ** pCur->idx is set to the cell index that contains the pointer
53877 ** to the page we are coming from.  If we are coming from the
53878 ** right-most child page then pCur->idx is set to one more than
53879 ** the largest cell index.
53880 */
53881 static void moveToParent(BtCursor *pCur){
53882   assert( cursorHoldsMutex(pCur) );
53883   assert( pCur->eState==CURSOR_VALID );
53884   assert( pCur->iPage>0 );
53885   assert( pCur->apPage[pCur->iPage] );
53886
53887   /* UPDATE: It is actually possible for the condition tested by the assert
53888   ** below to be untrue if the database file is corrupt. This can occur if
53889   ** one cursor has modified page pParent while a reference to it is held 
53890   ** by a second cursor. Which can only happen if a single page is linked
53891   ** into more than one b-tree structure in a corrupt database.  */
53892 #if 0
53893   assertParentIndex(
53894     pCur->apPage[pCur->iPage-1], 
53895     pCur->aiIdx[pCur->iPage-1], 
53896     pCur->apPage[pCur->iPage]->pgno
53897   );
53898 #endif
53899   testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
53900
53901   releasePage(pCur->apPage[pCur->iPage]);
53902   pCur->iPage--;
53903   pCur->info.nSize = 0;
53904   pCur->validNKey = 0;
53905 }
53906
53907 /*
53908 ** Move the cursor to point to the root page of its b-tree structure.
53909 **
53910 ** If the table has a virtual root page, then the cursor is moved to point
53911 ** to the virtual root page instead of the actual root page. A table has a
53912 ** virtual root page when the actual root page contains no cells and a 
53913 ** single child page. This can only happen with the table rooted at page 1.
53914 **
53915 ** If the b-tree structure is empty, the cursor state is set to 
53916 ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
53917 ** cell located on the root (or virtual root) page and the cursor state
53918 ** is set to CURSOR_VALID.
53919 **
53920 ** If this function returns successfully, it may be assumed that the
53921 ** page-header flags indicate that the [virtual] root-page is the expected 
53922 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
53923 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
53924 ** indicating a table b-tree, or if the caller did specify a KeyInfo 
53925 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
53926 ** b-tree).
53927 */
53928 static int moveToRoot(BtCursor *pCur){
53929   MemPage *pRoot;
53930   int rc = SQLITE_OK;
53931   Btree *p = pCur->pBtree;
53932   BtShared *pBt = p->pBt;
53933
53934   assert( cursorHoldsMutex(pCur) );
53935   assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
53936   assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
53937   assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
53938   if( pCur->eState>=CURSOR_REQUIRESEEK ){
53939     if( pCur->eState==CURSOR_FAULT ){
53940       assert( pCur->skipNext!=SQLITE_OK );
53941       return pCur->skipNext;
53942     }
53943     sqlite3BtreeClearCursor(pCur);
53944   }
53945
53946   if( pCur->iPage>=0 ){
53947     int i;
53948     for(i=1; i<=pCur->iPage; i++){
53949       releasePage(pCur->apPage[i]);
53950     }
53951     pCur->iPage = 0;
53952   }else if( pCur->pgnoRoot==0 ){
53953     pCur->eState = CURSOR_INVALID;
53954     return SQLITE_OK;
53955   }else{
53956     rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0], pCur->wrFlag==0);
53957     if( rc!=SQLITE_OK ){
53958       pCur->eState = CURSOR_INVALID;
53959       return rc;
53960     }
53961     pCur->iPage = 0;
53962
53963     /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
53964     ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
53965     ** NULL, the caller expects a table b-tree. If this is not the case,
53966     ** return an SQLITE_CORRUPT error.  */
53967     assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 );
53968     if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){
53969       return SQLITE_CORRUPT_BKPT;
53970     }
53971   }
53972
53973   /* Assert that the root page is of the correct type. This must be the
53974   ** case as the call to this function that loaded the root-page (either
53975   ** this call or a previous invocation) would have detected corruption 
53976   ** if the assumption were not true, and it is not possible for the flags 
53977   ** byte to have been modified while this cursor is holding a reference
53978   ** to the page.  */
53979   pRoot = pCur->apPage[0];
53980   assert( pRoot->pgno==pCur->pgnoRoot );
53981   assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey );
53982
53983   pCur->aiIdx[0] = 0;
53984   pCur->info.nSize = 0;
53985   pCur->atLast = 0;
53986   pCur->validNKey = 0;
53987
53988   if( pRoot->nCell==0 && !pRoot->leaf ){
53989     Pgno subpage;
53990     if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
53991     subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
53992     pCur->eState = CURSOR_VALID;
53993     rc = moveToChild(pCur, subpage);
53994   }else{
53995     pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
53996   }
53997   return rc;
53998 }
53999
54000 /*
54001 ** Move the cursor down to the left-most leaf entry beneath the
54002 ** entry to which it is currently pointing.
54003 **
54004 ** The left-most leaf is the one with the smallest key - the first
54005 ** in ascending order.
54006 */
54007 static int moveToLeftmost(BtCursor *pCur){
54008   Pgno pgno;
54009   int rc = SQLITE_OK;
54010   MemPage *pPage;
54011
54012   assert( cursorHoldsMutex(pCur) );
54013   assert( pCur->eState==CURSOR_VALID );
54014   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
54015     assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
54016     pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
54017     rc = moveToChild(pCur, pgno);
54018   }
54019   return rc;
54020 }
54021
54022 /*
54023 ** Move the cursor down to the right-most leaf entry beneath the
54024 ** page to which it is currently pointing.  Notice the difference
54025 ** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
54026 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
54027 ** finds the right-most entry beneath the *page*.
54028 **
54029 ** The right-most entry is the one with the largest key - the last
54030 ** key in ascending order.
54031 */
54032 static int moveToRightmost(BtCursor *pCur){
54033   Pgno pgno;
54034   int rc = SQLITE_OK;
54035   MemPage *pPage = 0;
54036
54037   assert( cursorHoldsMutex(pCur) );
54038   assert( pCur->eState==CURSOR_VALID );
54039   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
54040     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
54041     pCur->aiIdx[pCur->iPage] = pPage->nCell;
54042     rc = moveToChild(pCur, pgno);
54043   }
54044   if( rc==SQLITE_OK ){
54045     pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
54046     pCur->info.nSize = 0;
54047     pCur->validNKey = 0;
54048   }
54049   return rc;
54050 }
54051
54052 /* Move the cursor to the first entry in the table.  Return SQLITE_OK
54053 ** on success.  Set *pRes to 0 if the cursor actually points to something
54054 ** or set *pRes to 1 if the table is empty.
54055 */
54056 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
54057   int rc;
54058
54059   assert( cursorHoldsMutex(pCur) );
54060   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
54061   rc = moveToRoot(pCur);
54062   if( rc==SQLITE_OK ){
54063     if( pCur->eState==CURSOR_INVALID ){
54064       assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
54065       *pRes = 1;
54066     }else{
54067       assert( pCur->apPage[pCur->iPage]->nCell>0 );
54068       *pRes = 0;
54069       rc = moveToLeftmost(pCur);
54070     }
54071   }
54072   return rc;
54073 }
54074
54075 /* Move the cursor to the last entry in the table.  Return SQLITE_OK
54076 ** on success.  Set *pRes to 0 if the cursor actually points to something
54077 ** or set *pRes to 1 if the table is empty.
54078 */
54079 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
54080   int rc;
54081  
54082   assert( cursorHoldsMutex(pCur) );
54083   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
54084
54085   /* If the cursor already points to the last entry, this is a no-op. */
54086   if( CURSOR_VALID==pCur->eState && pCur->atLast ){
54087 #ifdef SQLITE_DEBUG
54088     /* This block serves to assert() that the cursor really does point 
54089     ** to the last entry in the b-tree. */
54090     int ii;
54091     for(ii=0; ii<pCur->iPage; ii++){
54092       assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
54093     }
54094     assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
54095     assert( pCur->apPage[pCur->iPage]->leaf );
54096 #endif
54097     return SQLITE_OK;
54098   }
54099
54100   rc = moveToRoot(pCur);
54101   if( rc==SQLITE_OK ){
54102     if( CURSOR_INVALID==pCur->eState ){
54103       assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
54104       *pRes = 1;
54105     }else{
54106       assert( pCur->eState==CURSOR_VALID );
54107       *pRes = 0;
54108       rc = moveToRightmost(pCur);
54109       pCur->atLast = rc==SQLITE_OK ?1:0;
54110     }
54111   }
54112   return rc;
54113 }
54114
54115 /* Move the cursor so that it points to an entry near the key 
54116 ** specified by pIdxKey or intKey.   Return a success code.
54117 **
54118 ** For INTKEY tables, the intKey parameter is used.  pIdxKey 
54119 ** must be NULL.  For index tables, pIdxKey is used and intKey
54120 ** is ignored.
54121 **
54122 ** If an exact match is not found, then the cursor is always
54123 ** left pointing at a leaf page which would hold the entry if it
54124 ** were present.  The cursor might point to an entry that comes
54125 ** before or after the key.
54126 **
54127 ** An integer is written into *pRes which is the result of
54128 ** comparing the key with the entry to which the cursor is 
54129 ** pointing.  The meaning of the integer written into
54130 ** *pRes is as follows:
54131 **
54132 **     *pRes<0      The cursor is left pointing at an entry that
54133 **                  is smaller than intKey/pIdxKey or if the table is empty
54134 **                  and the cursor is therefore left point to nothing.
54135 **
54136 **     *pRes==0     The cursor is left pointing at an entry that
54137 **                  exactly matches intKey/pIdxKey.
54138 **
54139 **     *pRes>0      The cursor is left pointing at an entry that
54140 **                  is larger than intKey/pIdxKey.
54141 **
54142 */
54143 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
54144   BtCursor *pCur,          /* The cursor to be moved */
54145   UnpackedRecord *pIdxKey, /* Unpacked index key */
54146   i64 intKey,              /* The table key */
54147   int biasRight,           /* If true, bias the search to the high end */
54148   int *pRes                /* Write search results here */
54149 ){
54150   int rc;
54151
54152   assert( cursorHoldsMutex(pCur) );
54153   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
54154   assert( pRes );
54155   assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
54156
54157   /* If the cursor is already positioned at the point we are trying
54158   ** to move to, then just return without doing any work */
54159   if( pCur->eState==CURSOR_VALID && pCur->validNKey 
54160    && pCur->apPage[0]->intKey 
54161   ){
54162     if( pCur->info.nKey==intKey ){
54163       *pRes = 0;
54164       return SQLITE_OK;
54165     }
54166     if( pCur->atLast && pCur->info.nKey<intKey ){
54167       *pRes = -1;
54168       return SQLITE_OK;
54169     }
54170   }
54171
54172   rc = moveToRoot(pCur);
54173   if( rc ){
54174     return rc;
54175   }
54176   assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
54177   assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
54178   assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
54179   if( pCur->eState==CURSOR_INVALID ){
54180     *pRes = -1;
54181     assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
54182     return SQLITE_OK;
54183   }
54184   assert( pCur->apPage[0]->intKey || pIdxKey );
54185   for(;;){
54186     int lwr, upr, idx;
54187     Pgno chldPg;
54188     MemPage *pPage = pCur->apPage[pCur->iPage];
54189     int c;
54190
54191     /* pPage->nCell must be greater than zero. If this is the root-page
54192     ** the cursor would have been INVALID above and this for(;;) loop
54193     ** not run. If this is not the root-page, then the moveToChild() routine
54194     ** would have already detected db corruption. Similarly, pPage must
54195     ** be the right kind (index or table) of b-tree page. Otherwise
54196     ** a moveToChild() or moveToRoot() call would have detected corruption.  */
54197     assert( pPage->nCell>0 );
54198     assert( pPage->intKey==(pIdxKey==0) );
54199     lwr = 0;
54200     upr = pPage->nCell-1;
54201     if( biasRight ){
54202       pCur->aiIdx[pCur->iPage] = (u16)(idx = upr);
54203     }else{
54204       pCur->aiIdx[pCur->iPage] = (u16)(idx = (upr+lwr)/2);
54205     }
54206     for(;;){
54207       u8 *pCell;                          /* Pointer to current cell in pPage */
54208
54209       assert( idx==pCur->aiIdx[pCur->iPage] );
54210       pCur->info.nSize = 0;
54211       pCell = findCell(pPage, idx) + pPage->childPtrSize;
54212       if( pPage->intKey ){
54213         i64 nCellKey;
54214         if( pPage->hasData ){
54215           u32 dummy;
54216           pCell += getVarint32(pCell, dummy);
54217         }
54218         getVarint(pCell, (u64*)&nCellKey);
54219         if( nCellKey==intKey ){
54220           c = 0;
54221         }else if( nCellKey<intKey ){
54222           c = -1;
54223         }else{
54224           assert( nCellKey>intKey );
54225           c = +1;
54226         }
54227         pCur->validNKey = 1;
54228         pCur->info.nKey = nCellKey;
54229       }else{
54230         /* The maximum supported page-size is 65536 bytes. This means that
54231         ** the maximum number of record bytes stored on an index B-Tree
54232         ** page is less than 16384 bytes and may be stored as a 2-byte
54233         ** varint. This information is used to attempt to avoid parsing 
54234         ** the entire cell by checking for the cases where the record is 
54235         ** stored entirely within the b-tree page by inspecting the first 
54236         ** 2 bytes of the cell.
54237         */
54238         int nCell = pCell[0];
54239         if( nCell<=pPage->max1bytePayload
54240          /* && (pCell+nCell)<pPage->aDataEnd */
54241         ){
54242           /* This branch runs if the record-size field of the cell is a
54243           ** single byte varint and the record fits entirely on the main
54244           ** b-tree page.  */
54245           testcase( pCell+nCell+1==pPage->aDataEnd );
54246           c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
54247         }else if( !(pCell[1] & 0x80) 
54248           && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
54249           /* && (pCell+nCell+2)<=pPage->aDataEnd */
54250         ){
54251           /* The record-size field is a 2 byte varint and the record 
54252           ** fits entirely on the main b-tree page.  */
54253           testcase( pCell+nCell+2==pPage->aDataEnd );
54254           c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
54255         }else{
54256           /* The record flows over onto one or more overflow pages. In
54257           ** this case the whole cell needs to be parsed, a buffer allocated
54258           ** and accessPayload() used to retrieve the record into the
54259           ** buffer before VdbeRecordCompare() can be called. */
54260           void *pCellKey;
54261           u8 * const pCellBody = pCell - pPage->childPtrSize;
54262           btreeParseCellPtr(pPage, pCellBody, &pCur->info);
54263           nCell = (int)pCur->info.nKey;
54264           pCellKey = sqlite3Malloc( nCell );
54265           if( pCellKey==0 ){
54266             rc = SQLITE_NOMEM;
54267             goto moveto_finish;
54268           }
54269           rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
54270           if( rc ){
54271             sqlite3_free(pCellKey);
54272             goto moveto_finish;
54273           }
54274           c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
54275           sqlite3_free(pCellKey);
54276         }
54277       }
54278       if( c==0 ){
54279         if( pPage->intKey && !pPage->leaf ){
54280           lwr = idx;
54281           break;
54282         }else{
54283           *pRes = 0;
54284           rc = SQLITE_OK;
54285           goto moveto_finish;
54286         }
54287       }
54288       if( c<0 ){
54289         lwr = idx+1;
54290       }else{
54291         upr = idx-1;
54292       }
54293       if( lwr>upr ){
54294         break;
54295       }
54296       pCur->aiIdx[pCur->iPage] = (u16)(idx = (lwr+upr)/2);
54297     }
54298     assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
54299     assert( pPage->isInit );
54300     if( pPage->leaf ){
54301       chldPg = 0;
54302     }else if( lwr>=pPage->nCell ){
54303       chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
54304     }else{
54305       chldPg = get4byte(findCell(pPage, lwr));
54306     }
54307     if( chldPg==0 ){
54308       assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
54309       *pRes = c;
54310       rc = SQLITE_OK;
54311       goto moveto_finish;
54312     }
54313     pCur->aiIdx[pCur->iPage] = (u16)lwr;
54314     pCur->info.nSize = 0;
54315     pCur->validNKey = 0;
54316     rc = moveToChild(pCur, chldPg);
54317     if( rc ) goto moveto_finish;
54318   }
54319 moveto_finish:
54320   return rc;
54321 }
54322
54323
54324 /*
54325 ** Return TRUE if the cursor is not pointing at an entry of the table.
54326 **
54327 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
54328 ** past the last entry in the table or sqlite3BtreePrev() moves past
54329 ** the first entry.  TRUE is also returned if the table is empty.
54330 */
54331 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
54332   /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
54333   ** have been deleted? This API will need to change to return an error code
54334   ** as well as the boolean result value.
54335   */
54336   return (CURSOR_VALID!=pCur->eState);
54337 }
54338
54339 /*
54340 ** Advance the cursor to the next entry in the database.  If
54341 ** successful then set *pRes=0.  If the cursor
54342 ** was already pointing to the last entry in the database before
54343 ** this routine was called, then set *pRes=1.
54344 */
54345 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
54346   int rc;
54347   int idx;
54348   MemPage *pPage;
54349
54350   assert( cursorHoldsMutex(pCur) );
54351   rc = restoreCursorPosition(pCur);
54352   if( rc!=SQLITE_OK ){
54353     return rc;
54354   }
54355   assert( pRes!=0 );
54356   if( CURSOR_INVALID==pCur->eState ){
54357     *pRes = 1;
54358     return SQLITE_OK;
54359   }
54360   if( pCur->skipNext>0 ){
54361     pCur->skipNext = 0;
54362     *pRes = 0;
54363     return SQLITE_OK;
54364   }
54365   pCur->skipNext = 0;
54366
54367   pPage = pCur->apPage[pCur->iPage];
54368   idx = ++pCur->aiIdx[pCur->iPage];
54369   assert( pPage->isInit );
54370
54371   /* If the database file is corrupt, it is possible for the value of idx 
54372   ** to be invalid here. This can only occur if a second cursor modifies
54373   ** the page while cursor pCur is holding a reference to it. Which can
54374   ** only happen if the database is corrupt in such a way as to link the
54375   ** page into more than one b-tree structure. */
54376   testcase( idx>pPage->nCell );
54377
54378   pCur->info.nSize = 0;
54379   pCur->validNKey = 0;
54380   if( idx>=pPage->nCell ){
54381     if( !pPage->leaf ){
54382       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
54383       if( rc ) return rc;
54384       rc = moveToLeftmost(pCur);
54385       *pRes = 0;
54386       return rc;
54387     }
54388     do{
54389       if( pCur->iPage==0 ){
54390         *pRes = 1;
54391         pCur->eState = CURSOR_INVALID;
54392         return SQLITE_OK;
54393       }
54394       moveToParent(pCur);
54395       pPage = pCur->apPage[pCur->iPage];
54396     }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
54397     *pRes = 0;
54398     if( pPage->intKey ){
54399       rc = sqlite3BtreeNext(pCur, pRes);
54400     }else{
54401       rc = SQLITE_OK;
54402     }
54403     return rc;
54404   }
54405   *pRes = 0;
54406   if( pPage->leaf ){
54407     return SQLITE_OK;
54408   }
54409   rc = moveToLeftmost(pCur);
54410   return rc;
54411 }
54412
54413
54414 /*
54415 ** Step the cursor to the back to the previous entry in the database.  If
54416 ** successful then set *pRes=0.  If the cursor
54417 ** was already pointing to the first entry in the database before
54418 ** this routine was called, then set *pRes=1.
54419 */
54420 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
54421   int rc;
54422   MemPage *pPage;
54423
54424   assert( cursorHoldsMutex(pCur) );
54425   rc = restoreCursorPosition(pCur);
54426   if( rc!=SQLITE_OK ){
54427     return rc;
54428   }
54429   pCur->atLast = 0;
54430   if( CURSOR_INVALID==pCur->eState ){
54431     *pRes = 1;
54432     return SQLITE_OK;
54433   }
54434   if( pCur->skipNext<0 ){
54435     pCur->skipNext = 0;
54436     *pRes = 0;
54437     return SQLITE_OK;
54438   }
54439   pCur->skipNext = 0;
54440
54441   pPage = pCur->apPage[pCur->iPage];
54442   assert( pPage->isInit );
54443   if( !pPage->leaf ){
54444     int idx = pCur->aiIdx[pCur->iPage];
54445     rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
54446     if( rc ){
54447       return rc;
54448     }
54449     rc = moveToRightmost(pCur);
54450   }else{
54451     while( pCur->aiIdx[pCur->iPage]==0 ){
54452       if( pCur->iPage==0 ){
54453         pCur->eState = CURSOR_INVALID;
54454         *pRes = 1;
54455         return SQLITE_OK;
54456       }
54457       moveToParent(pCur);
54458     }
54459     pCur->info.nSize = 0;
54460     pCur->validNKey = 0;
54461
54462     pCur->aiIdx[pCur->iPage]--;
54463     pPage = pCur->apPage[pCur->iPage];
54464     if( pPage->intKey && !pPage->leaf ){
54465       rc = sqlite3BtreePrevious(pCur, pRes);
54466     }else{
54467       rc = SQLITE_OK;
54468     }
54469   }
54470   *pRes = 0;
54471   return rc;
54472 }
54473
54474 /*
54475 ** Allocate a new page from the database file.
54476 **
54477 ** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
54478 ** has already been called on the new page.)  The new page has also
54479 ** been referenced and the calling routine is responsible for calling
54480 ** sqlite3PagerUnref() on the new page when it is done.
54481 **
54482 ** SQLITE_OK is returned on success.  Any other return value indicates
54483 ** an error.  *ppPage and *pPgno are undefined in the event of an error.
54484 ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
54485 **
54486 ** If the "nearby" parameter is not 0, then an effort is made to 
54487 ** locate a page close to the page number "nearby".  This can be used in an
54488 ** attempt to keep related pages close to each other in the database file,
54489 ** which in turn can make database access faster.
54490 **
54491 ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
54492 ** anywhere on the free-list, then it is guaranteed to be returned.  If
54493 ** eMode is BTALLOC_LT then the page returned will be less than or equal
54494 ** to nearby if any such page exists.  If eMode is BTALLOC_ANY then there
54495 ** are no restrictions on which page is returned.
54496 */
54497 static int allocateBtreePage(
54498   BtShared *pBt,         /* The btree */
54499   MemPage **ppPage,      /* Store pointer to the allocated page here */
54500   Pgno *pPgno,           /* Store the page number here */
54501   Pgno nearby,           /* Search for a page near this one */
54502   u8 eMode               /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
54503 ){
54504   MemPage *pPage1;
54505   int rc;
54506   u32 n;     /* Number of pages on the freelist */
54507   u32 k;     /* Number of leaves on the trunk of the freelist */
54508   MemPage *pTrunk = 0;
54509   MemPage *pPrevTrunk = 0;
54510   Pgno mxPage;     /* Total size of the database file */
54511
54512   assert( sqlite3_mutex_held(pBt->mutex) );
54513   assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
54514   pPage1 = pBt->pPage1;
54515   mxPage = btreePagecount(pBt);
54516   n = get4byte(&pPage1->aData[36]);
54517   testcase( n==mxPage-1 );
54518   if( n>=mxPage ){
54519     return SQLITE_CORRUPT_BKPT;
54520   }
54521   if( n>0 ){
54522     /* There are pages on the freelist.  Reuse one of those pages. */
54523     Pgno iTrunk;
54524     u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
54525     
54526     /* If eMode==BTALLOC_EXACT and a query of the pointer-map
54527     ** shows that the page 'nearby' is somewhere on the free-list, then
54528     ** the entire-list will be searched for that page.
54529     */
54530 #ifndef SQLITE_OMIT_AUTOVACUUM
54531     if( eMode==BTALLOC_EXACT ){
54532       if( nearby<=mxPage ){
54533         u8 eType;
54534         assert( nearby>0 );
54535         assert( pBt->autoVacuum );
54536         rc = ptrmapGet(pBt, nearby, &eType, 0);
54537         if( rc ) return rc;
54538         if( eType==PTRMAP_FREEPAGE ){
54539           searchList = 1;
54540         }
54541       }
54542     }else if( eMode==BTALLOC_LE ){
54543       searchList = 1;
54544     }
54545 #endif
54546
54547     /* Decrement the free-list count by 1. Set iTrunk to the index of the
54548     ** first free-list trunk page. iPrevTrunk is initially 1.
54549     */
54550     rc = sqlite3PagerWrite(pPage1->pDbPage);
54551     if( rc ) return rc;
54552     put4byte(&pPage1->aData[36], n-1);
54553
54554     /* The code within this loop is run only once if the 'searchList' variable
54555     ** is not true. Otherwise, it runs once for each trunk-page on the
54556     ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
54557     ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
54558     */
54559     do {
54560       pPrevTrunk = pTrunk;
54561       if( pPrevTrunk ){
54562         iTrunk = get4byte(&pPrevTrunk->aData[0]);
54563       }else{
54564         iTrunk = get4byte(&pPage1->aData[32]);
54565       }
54566       testcase( iTrunk==mxPage );
54567       if( iTrunk>mxPage ){
54568         rc = SQLITE_CORRUPT_BKPT;
54569       }else{
54570         rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0, 0);
54571       }
54572       if( rc ){
54573         pTrunk = 0;
54574         goto end_allocate_page;
54575       }
54576       assert( pTrunk!=0 );
54577       assert( pTrunk->aData!=0 );
54578
54579       k = get4byte(&pTrunk->aData[4]); /* # of leaves on this trunk page */
54580       if( k==0 && !searchList ){
54581         /* The trunk has no leaves and the list is not being searched. 
54582         ** So extract the trunk page itself and use it as the newly 
54583         ** allocated page */
54584         assert( pPrevTrunk==0 );
54585         rc = sqlite3PagerWrite(pTrunk->pDbPage);
54586         if( rc ){
54587           goto end_allocate_page;
54588         }
54589         *pPgno = iTrunk;
54590         memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
54591         *ppPage = pTrunk;
54592         pTrunk = 0;
54593         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
54594       }else if( k>(u32)(pBt->usableSize/4 - 2) ){
54595         /* Value of k is out of range.  Database corruption */
54596         rc = SQLITE_CORRUPT_BKPT;
54597         goto end_allocate_page;
54598 #ifndef SQLITE_OMIT_AUTOVACUUM
54599       }else if( searchList 
54600             && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE)) 
54601       ){
54602         /* The list is being searched and this trunk page is the page
54603         ** to allocate, regardless of whether it has leaves.
54604         */
54605         *pPgno = iTrunk;
54606         *ppPage = pTrunk;
54607         searchList = 0;
54608         rc = sqlite3PagerWrite(pTrunk->pDbPage);
54609         if( rc ){
54610           goto end_allocate_page;
54611         }
54612         if( k==0 ){
54613           if( !pPrevTrunk ){
54614             memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
54615           }else{
54616             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
54617             if( rc!=SQLITE_OK ){
54618               goto end_allocate_page;
54619             }
54620             memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
54621           }
54622         }else{
54623           /* The trunk page is required by the caller but it contains 
54624           ** pointers to free-list leaves. The first leaf becomes a trunk
54625           ** page in this case.
54626           */
54627           MemPage *pNewTrunk;
54628           Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
54629           if( iNewTrunk>mxPage ){ 
54630             rc = SQLITE_CORRUPT_BKPT;
54631             goto end_allocate_page;
54632           }
54633           testcase( iNewTrunk==mxPage );
54634           rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0, 0);
54635           if( rc!=SQLITE_OK ){
54636             goto end_allocate_page;
54637           }
54638           rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
54639           if( rc!=SQLITE_OK ){
54640             releasePage(pNewTrunk);
54641             goto end_allocate_page;
54642           }
54643           memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
54644           put4byte(&pNewTrunk->aData[4], k-1);
54645           memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
54646           releasePage(pNewTrunk);
54647           if( !pPrevTrunk ){
54648             assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
54649             put4byte(&pPage1->aData[32], iNewTrunk);
54650           }else{
54651             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
54652             if( rc ){
54653               goto end_allocate_page;
54654             }
54655             put4byte(&pPrevTrunk->aData[0], iNewTrunk);
54656           }
54657         }
54658         pTrunk = 0;
54659         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
54660 #endif
54661       }else if( k>0 ){
54662         /* Extract a leaf from the trunk */
54663         u32 closest;
54664         Pgno iPage;
54665         unsigned char *aData = pTrunk->aData;
54666         if( nearby>0 ){
54667           u32 i;
54668           closest = 0;
54669           if( eMode==BTALLOC_LE ){
54670             for(i=0; i<k; i++){
54671               iPage = get4byte(&aData[8+i*4]);
54672               if( iPage<=nearby ){
54673                 closest = i;
54674                 break;
54675               }
54676             }
54677           }else{
54678             int dist;
54679             dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
54680             for(i=1; i<k; i++){
54681               int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
54682               if( d2<dist ){
54683                 closest = i;
54684                 dist = d2;
54685               }
54686             }
54687           }
54688         }else{
54689           closest = 0;
54690         }
54691
54692         iPage = get4byte(&aData[8+closest*4]);
54693         testcase( iPage==mxPage );
54694         if( iPage>mxPage ){
54695           rc = SQLITE_CORRUPT_BKPT;
54696           goto end_allocate_page;
54697         }
54698         testcase( iPage==mxPage );
54699         if( !searchList 
54700          || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE)) 
54701         ){
54702           int noContent;
54703           *pPgno = iPage;
54704           TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
54705                  ": %d more free pages\n",
54706                  *pPgno, closest+1, k, pTrunk->pgno, n-1));
54707           rc = sqlite3PagerWrite(pTrunk->pDbPage);
54708           if( rc ) goto end_allocate_page;
54709           if( closest<k-1 ){
54710             memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
54711           }
54712           put4byte(&aData[4], k-1);
54713           noContent = !btreeGetHasContent(pBt, *pPgno);
54714           rc = btreeGetPage(pBt, *pPgno, ppPage, noContent, 0);
54715           if( rc==SQLITE_OK ){
54716             rc = sqlite3PagerWrite((*ppPage)->pDbPage);
54717             if( rc!=SQLITE_OK ){
54718               releasePage(*ppPage);
54719             }
54720           }
54721           searchList = 0;
54722         }
54723       }
54724       releasePage(pPrevTrunk);
54725       pPrevTrunk = 0;
54726     }while( searchList );
54727   }else{
54728     /* There are no pages on the freelist, so append a new page to the
54729     ** database image.
54730     **
54731     ** Normally, new pages allocated by this block can be requested from the
54732     ** pager layer with the 'no-content' flag set. This prevents the pager
54733     ** from trying to read the pages content from disk. However, if the
54734     ** current transaction has already run one or more incremental-vacuum
54735     ** steps, then the page we are about to allocate may contain content
54736     ** that is required in the event of a rollback. In this case, do
54737     ** not set the no-content flag. This causes the pager to load and journal
54738     ** the current page content before overwriting it.
54739     **
54740     ** Note that the pager will not actually attempt to load or journal 
54741     ** content for any page that really does lie past the end of the database
54742     ** file on disk. So the effects of disabling the no-content optimization
54743     ** here are confined to those pages that lie between the end of the
54744     ** database image and the end of the database file.
54745     */
54746     int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate));
54747
54748     rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
54749     if( rc ) return rc;
54750     pBt->nPage++;
54751     if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
54752
54753 #ifndef SQLITE_OMIT_AUTOVACUUM
54754     if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
54755       /* If *pPgno refers to a pointer-map page, allocate two new pages
54756       ** at the end of the file instead of one. The first allocated page
54757       ** becomes a new pointer-map page, the second is used by the caller.
54758       */
54759       MemPage *pPg = 0;
54760       TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
54761       assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
54762       rc = btreeGetPage(pBt, pBt->nPage, &pPg, bNoContent, 0);
54763       if( rc==SQLITE_OK ){
54764         rc = sqlite3PagerWrite(pPg->pDbPage);
54765         releasePage(pPg);
54766       }
54767       if( rc ) return rc;
54768       pBt->nPage++;
54769       if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
54770     }
54771 #endif
54772     put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
54773     *pPgno = pBt->nPage;
54774
54775     assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
54776     rc = btreeGetPage(pBt, *pPgno, ppPage, bNoContent, 0);
54777     if( rc ) return rc;
54778     rc = sqlite3PagerWrite((*ppPage)->pDbPage);
54779     if( rc!=SQLITE_OK ){
54780       releasePage(*ppPage);
54781     }
54782     TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
54783   }
54784
54785   assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
54786
54787 end_allocate_page:
54788   releasePage(pTrunk);
54789   releasePage(pPrevTrunk);
54790   if( rc==SQLITE_OK ){
54791     if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
54792       releasePage(*ppPage);
54793       return SQLITE_CORRUPT_BKPT;
54794     }
54795     (*ppPage)->isInit = 0;
54796   }else{
54797     *ppPage = 0;
54798   }
54799   assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) );
54800   return rc;
54801 }
54802
54803 /*
54804 ** This function is used to add page iPage to the database file free-list. 
54805 ** It is assumed that the page is not already a part of the free-list.
54806 **
54807 ** The value passed as the second argument to this function is optional.
54808 ** If the caller happens to have a pointer to the MemPage object 
54809 ** corresponding to page iPage handy, it may pass it as the second value. 
54810 ** Otherwise, it may pass NULL.
54811 **
54812 ** If a pointer to a MemPage object is passed as the second argument,
54813 ** its reference count is not altered by this function.
54814 */
54815 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
54816   MemPage *pTrunk = 0;                /* Free-list trunk page */
54817   Pgno iTrunk = 0;                    /* Page number of free-list trunk page */ 
54818   MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
54819   MemPage *pPage;                     /* Page being freed. May be NULL. */
54820   int rc;                             /* Return Code */
54821   int nFree;                          /* Initial number of pages on free-list */
54822
54823   assert( sqlite3_mutex_held(pBt->mutex) );
54824   assert( iPage>1 );
54825   assert( !pMemPage || pMemPage->pgno==iPage );
54826
54827   if( pMemPage ){
54828     pPage = pMemPage;
54829     sqlite3PagerRef(pPage->pDbPage);
54830   }else{
54831     pPage = btreePageLookup(pBt, iPage);
54832   }
54833
54834   /* Increment the free page count on pPage1 */
54835   rc = sqlite3PagerWrite(pPage1->pDbPage);
54836   if( rc ) goto freepage_out;
54837   nFree = get4byte(&pPage1->aData[36]);
54838   put4byte(&pPage1->aData[36], nFree+1);
54839
54840   if( pBt->btsFlags & BTS_SECURE_DELETE ){
54841     /* If the secure_delete option is enabled, then
54842     ** always fully overwrite deleted information with zeros.
54843     */
54844     if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0, 0))!=0) )
54845      ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
54846     ){
54847       goto freepage_out;
54848     }
54849     memset(pPage->aData, 0, pPage->pBt->pageSize);
54850   }
54851
54852   /* If the database supports auto-vacuum, write an entry in the pointer-map
54853   ** to indicate that the page is free.
54854   */
54855   if( ISAUTOVACUUM ){
54856     ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
54857     if( rc ) goto freepage_out;
54858   }
54859
54860   /* Now manipulate the actual database free-list structure. There are two
54861   ** possibilities. If the free-list is currently empty, or if the first
54862   ** trunk page in the free-list is full, then this page will become a
54863   ** new free-list trunk page. Otherwise, it will become a leaf of the
54864   ** first trunk page in the current free-list. This block tests if it
54865   ** is possible to add the page as a new free-list leaf.
54866   */
54867   if( nFree!=0 ){
54868     u32 nLeaf;                /* Initial number of leaf cells on trunk page */
54869
54870     iTrunk = get4byte(&pPage1->aData[32]);
54871     rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0, 0);
54872     if( rc!=SQLITE_OK ){
54873       goto freepage_out;
54874     }
54875
54876     nLeaf = get4byte(&pTrunk->aData[4]);
54877     assert( pBt->usableSize>32 );
54878     if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
54879       rc = SQLITE_CORRUPT_BKPT;
54880       goto freepage_out;
54881     }
54882     if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
54883       /* In this case there is room on the trunk page to insert the page
54884       ** being freed as a new leaf.
54885       **
54886       ** Note that the trunk page is not really full until it contains
54887       ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
54888       ** coded.  But due to a coding error in versions of SQLite prior to
54889       ** 3.6.0, databases with freelist trunk pages holding more than
54890       ** usableSize/4 - 8 entries will be reported as corrupt.  In order
54891       ** to maintain backwards compatibility with older versions of SQLite,
54892       ** we will continue to restrict the number of entries to usableSize/4 - 8
54893       ** for now.  At some point in the future (once everyone has upgraded
54894       ** to 3.6.0 or later) we should consider fixing the conditional above
54895       ** to read "usableSize/4-2" instead of "usableSize/4-8".
54896       */
54897       rc = sqlite3PagerWrite(pTrunk->pDbPage);
54898       if( rc==SQLITE_OK ){
54899         put4byte(&pTrunk->aData[4], nLeaf+1);
54900         put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
54901         if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
54902           sqlite3PagerDontWrite(pPage->pDbPage);
54903         }
54904         rc = btreeSetHasContent(pBt, iPage);
54905       }
54906       TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
54907       goto freepage_out;
54908     }
54909   }
54910
54911   /* If control flows to this point, then it was not possible to add the
54912   ** the page being freed as a leaf page of the first trunk in the free-list.
54913   ** Possibly because the free-list is empty, or possibly because the 
54914   ** first trunk in the free-list is full. Either way, the page being freed
54915   ** will become the new first trunk page in the free-list.
54916   */
54917   if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0, 0)) ){
54918     goto freepage_out;
54919   }
54920   rc = sqlite3PagerWrite(pPage->pDbPage);
54921   if( rc!=SQLITE_OK ){
54922     goto freepage_out;
54923   }
54924   put4byte(pPage->aData, iTrunk);
54925   put4byte(&pPage->aData[4], 0);
54926   put4byte(&pPage1->aData[32], iPage);
54927   TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
54928
54929 freepage_out:
54930   if( pPage ){
54931     pPage->isInit = 0;
54932   }
54933   releasePage(pPage);
54934   releasePage(pTrunk);
54935   return rc;
54936 }
54937 static void freePage(MemPage *pPage, int *pRC){
54938   if( (*pRC)==SQLITE_OK ){
54939     *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
54940   }
54941 }
54942
54943 /*
54944 ** Free any overflow pages associated with the given Cell.
54945 */
54946 static int clearCell(MemPage *pPage, unsigned char *pCell){
54947   BtShared *pBt = pPage->pBt;
54948   CellInfo info;
54949   Pgno ovflPgno;
54950   int rc;
54951   int nOvfl;
54952   u32 ovflPageSize;
54953
54954   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
54955   btreeParseCellPtr(pPage, pCell, &info);
54956   if( info.iOverflow==0 ){
54957     return SQLITE_OK;  /* No overflow pages. Return without doing anything */
54958   }
54959   if( pCell+info.iOverflow+3 > pPage->aData+pPage->maskPage ){
54960     return SQLITE_CORRUPT_BKPT;  /* Cell extends past end of page */
54961   }
54962   ovflPgno = get4byte(&pCell[info.iOverflow]);
54963   assert( pBt->usableSize > 4 );
54964   ovflPageSize = pBt->usableSize - 4;
54965   nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
54966   assert( ovflPgno==0 || nOvfl>0 );
54967   while( nOvfl-- ){
54968     Pgno iNext = 0;
54969     MemPage *pOvfl = 0;
54970     if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
54971       /* 0 is not a legal page number and page 1 cannot be an 
54972       ** overflow page. Therefore if ovflPgno<2 or past the end of the 
54973       ** file the database must be corrupt. */
54974       return SQLITE_CORRUPT_BKPT;
54975     }
54976     if( nOvfl ){
54977       rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
54978       if( rc ) return rc;
54979     }
54980
54981     if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
54982      && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
54983     ){
54984       /* There is no reason any cursor should have an outstanding reference 
54985       ** to an overflow page belonging to a cell that is being deleted/updated.
54986       ** So if there exists more than one reference to this page, then it 
54987       ** must not really be an overflow page and the database must be corrupt. 
54988       ** It is helpful to detect this before calling freePage2(), as 
54989       ** freePage2() may zero the page contents if secure-delete mode is
54990       ** enabled. If this 'overflow' page happens to be a page that the
54991       ** caller is iterating through or using in some other way, this
54992       ** can be problematic.
54993       */
54994       rc = SQLITE_CORRUPT_BKPT;
54995     }else{
54996       rc = freePage2(pBt, pOvfl, ovflPgno);
54997     }
54998
54999     if( pOvfl ){
55000       sqlite3PagerUnref(pOvfl->pDbPage);
55001     }
55002     if( rc ) return rc;
55003     ovflPgno = iNext;
55004   }
55005   return SQLITE_OK;
55006 }
55007
55008 /*
55009 ** Create the byte sequence used to represent a cell on page pPage
55010 ** and write that byte sequence into pCell[].  Overflow pages are
55011 ** allocated and filled in as necessary.  The calling procedure
55012 ** is responsible for making sure sufficient space has been allocated
55013 ** for pCell[].
55014 **
55015 ** Note that pCell does not necessary need to point to the pPage->aData
55016 ** area.  pCell might point to some temporary storage.  The cell will
55017 ** be constructed in this temporary area then copied into pPage->aData
55018 ** later.
55019 */
55020 static int fillInCell(
55021   MemPage *pPage,                /* The page that contains the cell */
55022   unsigned char *pCell,          /* Complete text of the cell */
55023   const void *pKey, i64 nKey,    /* The key */
55024   const void *pData,int nData,   /* The data */
55025   int nZero,                     /* Extra zero bytes to append to pData */
55026   int *pnSize                    /* Write cell size here */
55027 ){
55028   int nPayload;
55029   const u8 *pSrc;
55030   int nSrc, n, rc;
55031   int spaceLeft;
55032   MemPage *pOvfl = 0;
55033   MemPage *pToRelease = 0;
55034   unsigned char *pPrior;
55035   unsigned char *pPayload;
55036   BtShared *pBt = pPage->pBt;
55037   Pgno pgnoOvfl = 0;
55038   int nHeader;
55039   CellInfo info;
55040
55041   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
55042
55043   /* pPage is not necessarily writeable since pCell might be auxiliary
55044   ** buffer space that is separate from the pPage buffer area */
55045   assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
55046             || sqlite3PagerIswriteable(pPage->pDbPage) );
55047
55048   /* Fill in the header. */
55049   nHeader = 0;
55050   if( !pPage->leaf ){
55051     nHeader += 4;
55052   }
55053   if( pPage->hasData ){
55054     nHeader += putVarint(&pCell[nHeader], nData+nZero);
55055   }else{
55056     nData = nZero = 0;
55057   }
55058   nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
55059   btreeParseCellPtr(pPage, pCell, &info);
55060   assert( info.nHeader==nHeader );
55061   assert( info.nKey==nKey );
55062   assert( info.nData==(u32)(nData+nZero) );
55063   
55064   /* Fill in the payload */
55065   nPayload = nData + nZero;
55066   if( pPage->intKey ){
55067     pSrc = pData;
55068     nSrc = nData;
55069     nData = 0;
55070   }else{ 
55071     if( NEVER(nKey>0x7fffffff || pKey==0) ){
55072       return SQLITE_CORRUPT_BKPT;
55073     }
55074     nPayload += (int)nKey;
55075     pSrc = pKey;
55076     nSrc = (int)nKey;
55077   }
55078   *pnSize = info.nSize;
55079   spaceLeft = info.nLocal;
55080   pPayload = &pCell[nHeader];
55081   pPrior = &pCell[info.iOverflow];
55082
55083   while( nPayload>0 ){
55084     if( spaceLeft==0 ){
55085 #ifndef SQLITE_OMIT_AUTOVACUUM
55086       Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
55087       if( pBt->autoVacuum ){
55088         do{
55089           pgnoOvfl++;
55090         } while( 
55091           PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt) 
55092         );
55093       }
55094 #endif
55095       rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
55096 #ifndef SQLITE_OMIT_AUTOVACUUM
55097       /* If the database supports auto-vacuum, and the second or subsequent
55098       ** overflow page is being allocated, add an entry to the pointer-map
55099       ** for that page now. 
55100       **
55101       ** If this is the first overflow page, then write a partial entry 
55102       ** to the pointer-map. If we write nothing to this pointer-map slot,
55103       ** then the optimistic overflow chain processing in clearCell()
55104       ** may misinterpret the uninitialized values and delete the
55105       ** wrong pages from the database.
55106       */
55107       if( pBt->autoVacuum && rc==SQLITE_OK ){
55108         u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
55109         ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
55110         if( rc ){
55111           releasePage(pOvfl);
55112         }
55113       }
55114 #endif
55115       if( rc ){
55116         releasePage(pToRelease);
55117         return rc;
55118       }
55119
55120       /* If pToRelease is not zero than pPrior points into the data area
55121       ** of pToRelease.  Make sure pToRelease is still writeable. */
55122       assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
55123
55124       /* If pPrior is part of the data area of pPage, then make sure pPage
55125       ** is still writeable */
55126       assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
55127             || sqlite3PagerIswriteable(pPage->pDbPage) );
55128
55129       put4byte(pPrior, pgnoOvfl);
55130       releasePage(pToRelease);
55131       pToRelease = pOvfl;
55132       pPrior = pOvfl->aData;
55133       put4byte(pPrior, 0);
55134       pPayload = &pOvfl->aData[4];
55135       spaceLeft = pBt->usableSize - 4;
55136     }
55137     n = nPayload;
55138     if( n>spaceLeft ) n = spaceLeft;
55139
55140     /* If pToRelease is not zero than pPayload points into the data area
55141     ** of pToRelease.  Make sure pToRelease is still writeable. */
55142     assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
55143
55144     /* If pPayload is part of the data area of pPage, then make sure pPage
55145     ** is still writeable */
55146     assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
55147             || sqlite3PagerIswriteable(pPage->pDbPage) );
55148
55149     if( nSrc>0 ){
55150       if( n>nSrc ) n = nSrc;
55151       assert( pSrc );
55152       memcpy(pPayload, pSrc, n);
55153     }else{
55154       memset(pPayload, 0, n);
55155     }
55156     nPayload -= n;
55157     pPayload += n;
55158     pSrc += n;
55159     nSrc -= n;
55160     spaceLeft -= n;
55161     if( nSrc==0 ){
55162       nSrc = nData;
55163       pSrc = pData;
55164     }
55165   }
55166   releasePage(pToRelease);
55167   return SQLITE_OK;
55168 }
55169
55170 /*
55171 ** Remove the i-th cell from pPage.  This routine effects pPage only.
55172 ** The cell content is not freed or deallocated.  It is assumed that
55173 ** the cell content has been copied someplace else.  This routine just
55174 ** removes the reference to the cell from pPage.
55175 **
55176 ** "sz" must be the number of bytes in the cell.
55177 */
55178 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
55179   u32 pc;         /* Offset to cell content of cell being deleted */
55180   u8 *data;       /* pPage->aData */
55181   u8 *ptr;        /* Used to move bytes around within data[] */
55182   u8 *endPtr;     /* End of loop */
55183   int rc;         /* The return code */
55184   int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
55185
55186   if( *pRC ) return;
55187
55188   assert( idx>=0 && idx<pPage->nCell );
55189   assert( sz==cellSize(pPage, idx) );
55190   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
55191   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
55192   data = pPage->aData;
55193   ptr = &pPage->aCellIdx[2*idx];
55194   pc = get2byte(ptr);
55195   hdr = pPage->hdrOffset;
55196   testcase( pc==get2byte(&data[hdr+5]) );
55197   testcase( pc+sz==pPage->pBt->usableSize );
55198   if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
55199     *pRC = SQLITE_CORRUPT_BKPT;
55200     return;
55201   }
55202   rc = freeSpace(pPage, pc, sz);
55203   if( rc ){
55204     *pRC = rc;
55205     return;
55206   }
55207   endPtr = &pPage->aCellIdx[2*pPage->nCell - 2];
55208   assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 );  /* ptr is always 2-byte aligned */
55209   while( ptr<endPtr ){
55210     *(u16*)ptr = *(u16*)&ptr[2];
55211     ptr += 2;
55212   }
55213   pPage->nCell--;
55214   put2byte(&data[hdr+3], pPage->nCell);
55215   pPage->nFree += 2;
55216 }
55217
55218 /*
55219 ** Insert a new cell on pPage at cell index "i".  pCell points to the
55220 ** content of the cell.
55221 **
55222 ** If the cell content will fit on the page, then put it there.  If it
55223 ** will not fit, then make a copy of the cell content into pTemp if
55224 ** pTemp is not null.  Regardless of pTemp, allocate a new entry
55225 ** in pPage->apOvfl[] and make it point to the cell content (either
55226 ** in pTemp or the original pCell) and also record its index. 
55227 ** Allocating a new entry in pPage->aCell[] implies that 
55228 ** pPage->nOverflow is incremented.
55229 **
55230 ** If nSkip is non-zero, then do not copy the first nSkip bytes of the
55231 ** cell. The caller will overwrite them after this function returns. If
55232 ** nSkip is non-zero, then pCell may not point to an invalid memory location 
55233 ** (but pCell+nSkip is always valid).
55234 */
55235 static void insertCell(
55236   MemPage *pPage,   /* Page into which we are copying */
55237   int i,            /* New cell becomes the i-th cell of the page */
55238   u8 *pCell,        /* Content of the new cell */
55239   int sz,           /* Bytes of content in pCell */
55240   u8 *pTemp,        /* Temp storage space for pCell, if needed */
55241   Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
55242   int *pRC          /* Read and write return code from here */
55243 ){
55244   int idx = 0;      /* Where to write new cell content in data[] */
55245   int j;            /* Loop counter */
55246   int end;          /* First byte past the last cell pointer in data[] */
55247   int ins;          /* Index in data[] where new cell pointer is inserted */
55248   int cellOffset;   /* Address of first cell pointer in data[] */
55249   u8 *data;         /* The content of the whole page */
55250   u8 *ptr;          /* Used for moving information around in data[] */
55251   u8 *endPtr;       /* End of the loop */
55252
55253   int nSkip = (iChild ? 4 : 0);
55254
55255   if( *pRC ) return;
55256
55257   assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
55258   assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921 );
55259   assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
55260   assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
55261   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
55262   /* The cell should normally be sized correctly.  However, when moving a
55263   ** malformed cell from a leaf page to an interior page, if the cell size
55264   ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
55265   ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
55266   ** the term after the || in the following assert(). */
55267   assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
55268   if( pPage->nOverflow || sz+2>pPage->nFree ){
55269     if( pTemp ){
55270       memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
55271       pCell = pTemp;
55272     }
55273     if( iChild ){
55274       put4byte(pCell, iChild);
55275     }
55276     j = pPage->nOverflow++;
55277     assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) );
55278     pPage->apOvfl[j] = pCell;
55279     pPage->aiOvfl[j] = (u16)i;
55280   }else{
55281     int rc = sqlite3PagerWrite(pPage->pDbPage);
55282     if( rc!=SQLITE_OK ){
55283       *pRC = rc;
55284       return;
55285     }
55286     assert( sqlite3PagerIswriteable(pPage->pDbPage) );
55287     data = pPage->aData;
55288     cellOffset = pPage->cellOffset;
55289     end = cellOffset + 2*pPage->nCell;
55290     ins = cellOffset + 2*i;
55291     rc = allocateSpace(pPage, sz, &idx);
55292     if( rc ){ *pRC = rc; return; }
55293     /* The allocateSpace() routine guarantees the following two properties
55294     ** if it returns success */
55295     assert( idx >= end+2 );
55296     assert( idx+sz <= (int)pPage->pBt->usableSize );
55297     pPage->nCell++;
55298     pPage->nFree -= (u16)(2 + sz);
55299     memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
55300     if( iChild ){
55301       put4byte(&data[idx], iChild);
55302     }
55303     ptr = &data[end];
55304     endPtr = &data[ins];
55305     assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 );  /* ptr is always 2-byte aligned */
55306     while( ptr>endPtr ){
55307       *(u16*)ptr = *(u16*)&ptr[-2];
55308       ptr -= 2;
55309     }
55310     put2byte(&data[ins], idx);
55311     put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
55312 #ifndef SQLITE_OMIT_AUTOVACUUM
55313     if( pPage->pBt->autoVacuum ){
55314       /* The cell may contain a pointer to an overflow page. If so, write
55315       ** the entry for the overflow page into the pointer map.
55316       */
55317       ptrmapPutOvflPtr(pPage, pCell, pRC);
55318     }
55319 #endif
55320   }
55321 }
55322
55323 /*
55324 ** Add a list of cells to a page.  The page should be initially empty.
55325 ** The cells are guaranteed to fit on the page.
55326 */
55327 static void assemblePage(
55328   MemPage *pPage,   /* The page to be assemblied */
55329   int nCell,        /* The number of cells to add to this page */
55330   u8 **apCell,      /* Pointers to cell bodies */
55331   u16 *aSize        /* Sizes of the cells */
55332 ){
55333   int i;            /* Loop counter */
55334   u8 *pCellptr;     /* Address of next cell pointer */
55335   int cellbody;     /* Address of next cell body */
55336   u8 * const data = pPage->aData;             /* Pointer to data for pPage */
55337   const int hdr = pPage->hdrOffset;           /* Offset of header on pPage */
55338   const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
55339
55340   assert( pPage->nOverflow==0 );
55341   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
55342   assert( nCell>=0 && nCell<=(int)MX_CELL(pPage->pBt)
55343             && (int)MX_CELL(pPage->pBt)<=10921);
55344   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
55345
55346   /* Check that the page has just been zeroed by zeroPage() */
55347   assert( pPage->nCell==0 );
55348   assert( get2byteNotZero(&data[hdr+5])==nUsable );
55349
55350   pCellptr = &pPage->aCellIdx[nCell*2];
55351   cellbody = nUsable;
55352   for(i=nCell-1; i>=0; i--){
55353     u16 sz = aSize[i];
55354     pCellptr -= 2;
55355     cellbody -= sz;
55356     put2byte(pCellptr, cellbody);
55357     memcpy(&data[cellbody], apCell[i], sz);
55358   }
55359   put2byte(&data[hdr+3], nCell);
55360   put2byte(&data[hdr+5], cellbody);
55361   pPage->nFree -= (nCell*2 + nUsable - cellbody);
55362   pPage->nCell = (u16)nCell;
55363 }
55364
55365 /*
55366 ** The following parameters determine how many adjacent pages get involved
55367 ** in a balancing operation.  NN is the number of neighbors on either side
55368 ** of the page that participate in the balancing operation.  NB is the
55369 ** total number of pages that participate, including the target page and
55370 ** NN neighbors on either side.
55371 **
55372 ** The minimum value of NN is 1 (of course).  Increasing NN above 1
55373 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
55374 ** in exchange for a larger degradation in INSERT and UPDATE performance.
55375 ** The value of NN appears to give the best results overall.
55376 */
55377 #define NN 1             /* Number of neighbors on either side of pPage */
55378 #define NB (NN*2+1)      /* Total pages involved in the balance */
55379
55380
55381 #ifndef SQLITE_OMIT_QUICKBALANCE
55382 /*
55383 ** This version of balance() handles the common special case where
55384 ** a new entry is being inserted on the extreme right-end of the
55385 ** tree, in other words, when the new entry will become the largest
55386 ** entry in the tree.
55387 **
55388 ** Instead of trying to balance the 3 right-most leaf pages, just add
55389 ** a new page to the right-hand side and put the one new entry in
55390 ** that page.  This leaves the right side of the tree somewhat
55391 ** unbalanced.  But odds are that we will be inserting new entries
55392 ** at the end soon afterwards so the nearly empty page will quickly
55393 ** fill up.  On average.
55394 **
55395 ** pPage is the leaf page which is the right-most page in the tree.
55396 ** pParent is its parent.  pPage must have a single overflow entry
55397 ** which is also the right-most entry on the page.
55398 **
55399 ** The pSpace buffer is used to store a temporary copy of the divider
55400 ** cell that will be inserted into pParent. Such a cell consists of a 4
55401 ** byte page number followed by a variable length integer. In other
55402 ** words, at most 13 bytes. Hence the pSpace buffer must be at
55403 ** least 13 bytes in size.
55404 */
55405 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
55406   BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
55407   MemPage *pNew;                       /* Newly allocated page */
55408   int rc;                              /* Return Code */
55409   Pgno pgnoNew;                        /* Page number of pNew */
55410
55411   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
55412   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
55413   assert( pPage->nOverflow==1 );
55414
55415   /* This error condition is now caught prior to reaching this function */
55416   if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT;
55417
55418   /* Allocate a new page. This page will become the right-sibling of 
55419   ** pPage. Make the parent page writable, so that the new divider cell
55420   ** may be inserted. If both these operations are successful, proceed.
55421   */
55422   rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
55423
55424   if( rc==SQLITE_OK ){
55425
55426     u8 *pOut = &pSpace[4];
55427     u8 *pCell = pPage->apOvfl[0];
55428     u16 szCell = cellSizePtr(pPage, pCell);
55429     u8 *pStop;
55430
55431     assert( sqlite3PagerIswriteable(pNew->pDbPage) );
55432     assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
55433     zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
55434     assemblePage(pNew, 1, &pCell, &szCell);
55435
55436     /* If this is an auto-vacuum database, update the pointer map
55437     ** with entries for the new page, and any pointer from the 
55438     ** cell on the page to an overflow page. If either of these
55439     ** operations fails, the return code is set, but the contents
55440     ** of the parent page are still manipulated by thh code below.
55441     ** That is Ok, at this point the parent page is guaranteed to
55442     ** be marked as dirty. Returning an error code will cause a
55443     ** rollback, undoing any changes made to the parent page.
55444     */
55445     if( ISAUTOVACUUM ){
55446       ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
55447       if( szCell>pNew->minLocal ){
55448         ptrmapPutOvflPtr(pNew, pCell, &rc);
55449       }
55450     }
55451   
55452     /* Create a divider cell to insert into pParent. The divider cell
55453     ** consists of a 4-byte page number (the page number of pPage) and
55454     ** a variable length key value (which must be the same value as the
55455     ** largest key on pPage).
55456     **
55457     ** To find the largest key value on pPage, first find the right-most 
55458     ** cell on pPage. The first two fields of this cell are the 
55459     ** record-length (a variable length integer at most 32-bits in size)
55460     ** and the key value (a variable length integer, may have any value).
55461     ** The first of the while(...) loops below skips over the record-length
55462     ** field. The second while(...) loop copies the key value from the
55463     ** cell on pPage into the pSpace buffer.
55464     */
55465     pCell = findCell(pPage, pPage->nCell-1);
55466     pStop = &pCell[9];
55467     while( (*(pCell++)&0x80) && pCell<pStop );
55468     pStop = &pCell[9];
55469     while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
55470
55471     /* Insert the new divider cell into pParent. */
55472     insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
55473                0, pPage->pgno, &rc);
55474
55475     /* Set the right-child pointer of pParent to point to the new page. */
55476     put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
55477   
55478     /* Release the reference to the new page. */
55479     releasePage(pNew);
55480   }
55481
55482   return rc;
55483 }
55484 #endif /* SQLITE_OMIT_QUICKBALANCE */
55485
55486 #if 0
55487 /*
55488 ** This function does not contribute anything to the operation of SQLite.
55489 ** it is sometimes activated temporarily while debugging code responsible 
55490 ** for setting pointer-map entries.
55491 */
55492 static int ptrmapCheckPages(MemPage **apPage, int nPage){
55493   int i, j;
55494   for(i=0; i<nPage; i++){
55495     Pgno n;
55496     u8 e;
55497     MemPage *pPage = apPage[i];
55498     BtShared *pBt = pPage->pBt;
55499     assert( pPage->isInit );
55500
55501     for(j=0; j<pPage->nCell; j++){
55502       CellInfo info;
55503       u8 *z;
55504      
55505       z = findCell(pPage, j);
55506       btreeParseCellPtr(pPage, z, &info);
55507       if( info.iOverflow ){
55508         Pgno ovfl = get4byte(&z[info.iOverflow]);
55509         ptrmapGet(pBt, ovfl, &e, &n);
55510         assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
55511       }
55512       if( !pPage->leaf ){
55513         Pgno child = get4byte(z);
55514         ptrmapGet(pBt, child, &e, &n);
55515         assert( n==pPage->pgno && e==PTRMAP_BTREE );
55516       }
55517     }
55518     if( !pPage->leaf ){
55519       Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
55520       ptrmapGet(pBt, child, &e, &n);
55521       assert( n==pPage->pgno && e==PTRMAP_BTREE );
55522     }
55523   }
55524   return 1;
55525 }
55526 #endif
55527
55528 /*
55529 ** This function is used to copy the contents of the b-tree node stored 
55530 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
55531 ** the pointer-map entries for each child page are updated so that the
55532 ** parent page stored in the pointer map is page pTo. If pFrom contained
55533 ** any cells with overflow page pointers, then the corresponding pointer
55534 ** map entries are also updated so that the parent page is page pTo.
55535 **
55536 ** If pFrom is currently carrying any overflow cells (entries in the
55537 ** MemPage.apOvfl[] array), they are not copied to pTo. 
55538 **
55539 ** Before returning, page pTo is reinitialized using btreeInitPage().
55540 **
55541 ** The performance of this function is not critical. It is only used by 
55542 ** the balance_shallower() and balance_deeper() procedures, neither of
55543 ** which are called often under normal circumstances.
55544 */
55545 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
55546   if( (*pRC)==SQLITE_OK ){
55547     BtShared * const pBt = pFrom->pBt;
55548     u8 * const aFrom = pFrom->aData;
55549     u8 * const aTo = pTo->aData;
55550     int const iFromHdr = pFrom->hdrOffset;
55551     int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
55552     int rc;
55553     int iData;
55554   
55555   
55556     assert( pFrom->isInit );
55557     assert( pFrom->nFree>=iToHdr );
55558     assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
55559   
55560     /* Copy the b-tree node content from page pFrom to page pTo. */
55561     iData = get2byte(&aFrom[iFromHdr+5]);
55562     memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
55563     memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
55564   
55565     /* Reinitialize page pTo so that the contents of the MemPage structure
55566     ** match the new data. The initialization of pTo can actually fail under
55567     ** fairly obscure circumstances, even though it is a copy of initialized 
55568     ** page pFrom.
55569     */
55570     pTo->isInit = 0;
55571     rc = btreeInitPage(pTo);
55572     if( rc!=SQLITE_OK ){
55573       *pRC = rc;
55574       return;
55575     }
55576   
55577     /* If this is an auto-vacuum database, update the pointer-map entries
55578     ** for any b-tree or overflow pages that pTo now contains the pointers to.
55579     */
55580     if( ISAUTOVACUUM ){
55581       *pRC = setChildPtrmaps(pTo);
55582     }
55583   }
55584 }
55585
55586 /*
55587 ** This routine redistributes cells on the iParentIdx'th child of pParent
55588 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
55589 ** same amount of free space. Usually a single sibling on either side of the
55590 ** page are used in the balancing, though both siblings might come from one
55591 ** side if the page is the first or last child of its parent. If the page 
55592 ** has fewer than 2 siblings (something which can only happen if the page
55593 ** is a root page or a child of a root page) then all available siblings
55594 ** participate in the balancing.
55595 **
55596 ** The number of siblings of the page might be increased or decreased by 
55597 ** one or two in an effort to keep pages nearly full but not over full. 
55598 **
55599 ** Note that when this routine is called, some of the cells on the page
55600 ** might not actually be stored in MemPage.aData[]. This can happen
55601 ** if the page is overfull. This routine ensures that all cells allocated
55602 ** to the page and its siblings fit into MemPage.aData[] before returning.
55603 **
55604 ** In the course of balancing the page and its siblings, cells may be
55605 ** inserted into or removed from the parent page (pParent). Doing so
55606 ** may cause the parent page to become overfull or underfull. If this
55607 ** happens, it is the responsibility of the caller to invoke the correct
55608 ** balancing routine to fix this problem (see the balance() routine). 
55609 **
55610 ** If this routine fails for any reason, it might leave the database
55611 ** in a corrupted state. So if this routine fails, the database should
55612 ** be rolled back.
55613 **
55614 ** The third argument to this function, aOvflSpace, is a pointer to a
55615 ** buffer big enough to hold one page. If while inserting cells into the parent
55616 ** page (pParent) the parent page becomes overfull, this buffer is
55617 ** used to store the parent's overflow cells. Because this function inserts
55618 ** a maximum of four divider cells into the parent page, and the maximum
55619 ** size of a cell stored within an internal node is always less than 1/4
55620 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
55621 ** enough for all overflow cells.
55622 **
55623 ** If aOvflSpace is set to a null pointer, this function returns 
55624 ** SQLITE_NOMEM.
55625 */
55626 #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
55627 #pragma optimize("", off)
55628 #endif
55629 static int balance_nonroot(
55630   MemPage *pParent,               /* Parent page of siblings being balanced */
55631   int iParentIdx,                 /* Index of "the page" in pParent */
55632   u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
55633   int isRoot,                     /* True if pParent is a root-page */
55634   int bBulk                       /* True if this call is part of a bulk load */
55635 ){
55636   BtShared *pBt;               /* The whole database */
55637   int nCell = 0;               /* Number of cells in apCell[] */
55638   int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
55639   int nNew = 0;                /* Number of pages in apNew[] */
55640   int nOld;                    /* Number of pages in apOld[] */
55641   int i, j, k;                 /* Loop counters */
55642   int nxDiv;                   /* Next divider slot in pParent->aCell[] */
55643   int rc = SQLITE_OK;          /* The return code */
55644   u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
55645   int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
55646   int usableSpace;             /* Bytes in pPage beyond the header */
55647   int pageFlags;               /* Value of pPage->aData[0] */
55648   int subtotal;                /* Subtotal of bytes in cells on one page */
55649   int iSpace1 = 0;             /* First unused byte of aSpace1[] */
55650   int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
55651   int szScratch;               /* Size of scratch memory requested */
55652   MemPage *apOld[NB];          /* pPage and up to two siblings */
55653   MemPage *apCopy[NB];         /* Private copies of apOld[] pages */
55654   MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
55655   u8 *pRight;                  /* Location in parent of right-sibling pointer */
55656   u8 *apDiv[NB-1];             /* Divider cells in pParent */
55657   int cntNew[NB+2];            /* Index in aCell[] of cell after i-th page */
55658   int szNew[NB+2];             /* Combined size of cells place on i-th page */
55659   u8 **apCell = 0;             /* All cells begin balanced */
55660   u16 *szCell;                 /* Local size of all cells in apCell[] */
55661   u8 *aSpace1;                 /* Space for copies of dividers cells */
55662   Pgno pgno;                   /* Temp var to store a page number in */
55663
55664   pBt = pParent->pBt;
55665   assert( sqlite3_mutex_held(pBt->mutex) );
55666   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
55667
55668 #if 0
55669   TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
55670 #endif
55671
55672   /* At this point pParent may have at most one overflow cell. And if
55673   ** this overflow cell is present, it must be the cell with 
55674   ** index iParentIdx. This scenario comes about when this function
55675   ** is called (indirectly) from sqlite3BtreeDelete().
55676   */
55677   assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
55678   assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
55679
55680   if( !aOvflSpace ){
55681     return SQLITE_NOMEM;
55682   }
55683
55684   /* Find the sibling pages to balance. Also locate the cells in pParent 
55685   ** that divide the siblings. An attempt is made to find NN siblings on 
55686   ** either side of pPage. More siblings are taken from one side, however, 
55687   ** if there are fewer than NN siblings on the other side. If pParent
55688   ** has NB or fewer children then all children of pParent are taken.  
55689   **
55690   ** This loop also drops the divider cells from the parent page. This
55691   ** way, the remainder of the function does not have to deal with any
55692   ** overflow cells in the parent page, since if any existed they will
55693   ** have already been removed.
55694   */
55695   i = pParent->nOverflow + pParent->nCell;
55696   if( i<2 ){
55697     nxDiv = 0;
55698   }else{
55699     assert( bBulk==0 || bBulk==1 );
55700     if( iParentIdx==0 ){                 
55701       nxDiv = 0;
55702     }else if( iParentIdx==i ){
55703       nxDiv = i-2+bBulk;
55704     }else{
55705       assert( bBulk==0 );
55706       nxDiv = iParentIdx-1;
55707     }
55708     i = 2-bBulk;
55709   }
55710   nOld = i+1;
55711   if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
55712     pRight = &pParent->aData[pParent->hdrOffset+8];
55713   }else{
55714     pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
55715   }
55716   pgno = get4byte(pRight);
55717   while( 1 ){
55718     rc = getAndInitPage(pBt, pgno, &apOld[i], 0);
55719     if( rc ){
55720       memset(apOld, 0, (i+1)*sizeof(MemPage*));
55721       goto balance_cleanup;
55722     }
55723     nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
55724     if( (i--)==0 ) break;
55725
55726     if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){
55727       apDiv[i] = pParent->apOvfl[0];
55728       pgno = get4byte(apDiv[i]);
55729       szNew[i] = cellSizePtr(pParent, apDiv[i]);
55730       pParent->nOverflow = 0;
55731     }else{
55732       apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
55733       pgno = get4byte(apDiv[i]);
55734       szNew[i] = cellSizePtr(pParent, apDiv[i]);
55735
55736       /* Drop the cell from the parent page. apDiv[i] still points to
55737       ** the cell within the parent, even though it has been dropped.
55738       ** This is safe because dropping a cell only overwrites the first
55739       ** four bytes of it, and this function does not need the first
55740       ** four bytes of the divider cell. So the pointer is safe to use
55741       ** later on.  
55742       **
55743       ** But not if we are in secure-delete mode. In secure-delete mode,
55744       ** the dropCell() routine will overwrite the entire cell with zeroes.
55745       ** In this case, temporarily copy the cell into the aOvflSpace[]
55746       ** buffer. It will be copied out again as soon as the aSpace[] buffer
55747       ** is allocated.  */
55748       if( pBt->btsFlags & BTS_SECURE_DELETE ){
55749         int iOff;
55750
55751         iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
55752         if( (iOff+szNew[i])>(int)pBt->usableSize ){
55753           rc = SQLITE_CORRUPT_BKPT;
55754           memset(apOld, 0, (i+1)*sizeof(MemPage*));
55755           goto balance_cleanup;
55756         }else{
55757           memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
55758           apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
55759         }
55760       }
55761       dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
55762     }
55763   }
55764
55765   /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
55766   ** alignment */
55767   nMaxCells = (nMaxCells + 3)&~3;
55768
55769   /*
55770   ** Allocate space for memory structures
55771   */
55772   k = pBt->pageSize + ROUND8(sizeof(MemPage));
55773   szScratch =
55774        nMaxCells*sizeof(u8*)                       /* apCell */
55775      + nMaxCells*sizeof(u16)                       /* szCell */
55776      + pBt->pageSize                               /* aSpace1 */
55777      + k*nOld;                                     /* Page copies (apCopy) */
55778   apCell = sqlite3ScratchMalloc( szScratch ); 
55779   if( apCell==0 ){
55780     rc = SQLITE_NOMEM;
55781     goto balance_cleanup;
55782   }
55783   szCell = (u16*)&apCell[nMaxCells];
55784   aSpace1 = (u8*)&szCell[nMaxCells];
55785   assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
55786
55787   /*
55788   ** Load pointers to all cells on sibling pages and the divider cells
55789   ** into the local apCell[] array.  Make copies of the divider cells
55790   ** into space obtained from aSpace1[] and remove the divider cells
55791   ** from pParent.
55792   **
55793   ** If the siblings are on leaf pages, then the child pointers of the
55794   ** divider cells are stripped from the cells before they are copied
55795   ** into aSpace1[].  In this way, all cells in apCell[] are without
55796   ** child pointers.  If siblings are not leaves, then all cell in
55797   ** apCell[] include child pointers.  Either way, all cells in apCell[]
55798   ** are alike.
55799   **
55800   ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
55801   **       leafData:  1 if pPage holds key+data and pParent holds only keys.
55802   */
55803   leafCorrection = apOld[0]->leaf*4;
55804   leafData = apOld[0]->hasData;
55805   for(i=0; i<nOld; i++){
55806     int limit;
55807     
55808     /* Before doing anything else, take a copy of the i'th original sibling
55809     ** The rest of this function will use data from the copies rather
55810     ** that the original pages since the original pages will be in the
55811     ** process of being overwritten.  */
55812     MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
55813     memcpy(pOld, apOld[i], sizeof(MemPage));
55814     pOld->aData = (void*)&pOld[1];
55815     memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
55816
55817     limit = pOld->nCell+pOld->nOverflow;
55818     if( pOld->nOverflow>0 ){
55819       for(j=0; j<limit; j++){
55820         assert( nCell<nMaxCells );
55821         apCell[nCell] = findOverflowCell(pOld, j);
55822         szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
55823         nCell++;
55824       }
55825     }else{
55826       u8 *aData = pOld->aData;
55827       u16 maskPage = pOld->maskPage;
55828       u16 cellOffset = pOld->cellOffset;
55829       for(j=0; j<limit; j++){
55830         assert( nCell<nMaxCells );
55831         apCell[nCell] = findCellv2(aData, maskPage, cellOffset, j);
55832         szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
55833         nCell++;
55834       }
55835     }       
55836     if( i<nOld-1 && !leafData){
55837       u16 sz = (u16)szNew[i];
55838       u8 *pTemp;
55839       assert( nCell<nMaxCells );
55840       szCell[nCell] = sz;
55841       pTemp = &aSpace1[iSpace1];
55842       iSpace1 += sz;
55843       assert( sz<=pBt->maxLocal+23 );
55844       assert( iSpace1 <= (int)pBt->pageSize );
55845       memcpy(pTemp, apDiv[i], sz);
55846       apCell[nCell] = pTemp+leafCorrection;
55847       assert( leafCorrection==0 || leafCorrection==4 );
55848       szCell[nCell] = szCell[nCell] - leafCorrection;
55849       if( !pOld->leaf ){
55850         assert( leafCorrection==0 );
55851         assert( pOld->hdrOffset==0 );
55852         /* The right pointer of the child page pOld becomes the left
55853         ** pointer of the divider cell */
55854         memcpy(apCell[nCell], &pOld->aData[8], 4);
55855       }else{
55856         assert( leafCorrection==4 );
55857         if( szCell[nCell]<4 ){
55858           /* Do not allow any cells smaller than 4 bytes. */
55859           szCell[nCell] = 4;
55860         }
55861       }
55862       nCell++;
55863     }
55864   }
55865
55866   /*
55867   ** Figure out the number of pages needed to hold all nCell cells.
55868   ** Store this number in "k".  Also compute szNew[] which is the total
55869   ** size of all cells on the i-th page and cntNew[] which is the index
55870   ** in apCell[] of the cell that divides page i from page i+1.  
55871   ** cntNew[k] should equal nCell.
55872   **
55873   ** Values computed by this block:
55874   **
55875   **           k: The total number of sibling pages
55876   **    szNew[i]: Spaced used on the i-th sibling page.
55877   **   cntNew[i]: Index in apCell[] and szCell[] for the first cell to
55878   **              the right of the i-th sibling page.
55879   ** usableSpace: Number of bytes of space available on each sibling.
55880   ** 
55881   */
55882   usableSpace = pBt->usableSize - 12 + leafCorrection;
55883   for(subtotal=k=i=0; i<nCell; i++){
55884     assert( i<nMaxCells );
55885     subtotal += szCell[i] + 2;
55886     if( subtotal > usableSpace ){
55887       szNew[k] = subtotal - szCell[i];
55888       cntNew[k] = i;
55889       if( leafData ){ i--; }
55890       subtotal = 0;
55891       k++;
55892       if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
55893     }
55894   }
55895   szNew[k] = subtotal;
55896   cntNew[k] = nCell;
55897   k++;
55898
55899   /*
55900   ** The packing computed by the previous block is biased toward the siblings
55901   ** on the left side.  The left siblings are always nearly full, while the
55902   ** right-most sibling might be nearly empty.  This block of code attempts
55903   ** to adjust the packing of siblings to get a better balance.
55904   **
55905   ** This adjustment is more than an optimization.  The packing above might
55906   ** be so out of balance as to be illegal.  For example, the right-most
55907   ** sibling might be completely empty.  This adjustment is not optional.
55908   */
55909   for(i=k-1; i>0; i--){
55910     int szRight = szNew[i];  /* Size of sibling on the right */
55911     int szLeft = szNew[i-1]; /* Size of sibling on the left */
55912     int r;              /* Index of right-most cell in left sibling */
55913     int d;              /* Index of first cell to the left of right sibling */
55914
55915     r = cntNew[i-1] - 1;
55916     d = r + 1 - leafData;
55917     assert( d<nMaxCells );
55918     assert( r<nMaxCells );
55919     while( szRight==0 
55920        || (!bBulk && szRight+szCell[d]+2<=szLeft-(szCell[r]+2)) 
55921     ){
55922       szRight += szCell[d] + 2;
55923       szLeft -= szCell[r] + 2;
55924       cntNew[i-1]--;
55925       r = cntNew[i-1] - 1;
55926       d = r + 1 - leafData;
55927     }
55928     szNew[i] = szRight;
55929     szNew[i-1] = szLeft;
55930   }
55931
55932   /* Either we found one or more cells (cntnew[0])>0) or pPage is
55933   ** a virtual root page.  A virtual root page is when the real root
55934   ** page is page 1 and we are the only child of that page.
55935   **
55936   ** UPDATE:  The assert() below is not necessarily true if the database
55937   ** file is corrupt.  The corruption will be detected and reported later
55938   ** in this procedure so there is no need to act upon it now.
55939   */
55940 #if 0
55941   assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
55942 #endif
55943
55944   TRACE(("BALANCE: old: %d %d %d  ",
55945     apOld[0]->pgno, 
55946     nOld>=2 ? apOld[1]->pgno : 0,
55947     nOld>=3 ? apOld[2]->pgno : 0
55948   ));
55949
55950   /*
55951   ** Allocate k new pages.  Reuse old pages where possible.
55952   */
55953   if( apOld[0]->pgno<=1 ){
55954     rc = SQLITE_CORRUPT_BKPT;
55955     goto balance_cleanup;
55956   }
55957   pageFlags = apOld[0]->aData[0];
55958   for(i=0; i<k; i++){
55959     MemPage *pNew;
55960     if( i<nOld ){
55961       pNew = apNew[i] = apOld[i];
55962       apOld[i] = 0;
55963       rc = sqlite3PagerWrite(pNew->pDbPage);
55964       nNew++;
55965       if( rc ) goto balance_cleanup;
55966     }else{
55967       assert( i>0 );
55968       rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
55969       if( rc ) goto balance_cleanup;
55970       apNew[i] = pNew;
55971       nNew++;
55972
55973       /* Set the pointer-map entry for the new sibling page. */
55974       if( ISAUTOVACUUM ){
55975         ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
55976         if( rc!=SQLITE_OK ){
55977           goto balance_cleanup;
55978         }
55979       }
55980     }
55981   }
55982
55983   /* Free any old pages that were not reused as new pages.
55984   */
55985   while( i<nOld ){
55986     freePage(apOld[i], &rc);
55987     if( rc ) goto balance_cleanup;
55988     releasePage(apOld[i]);
55989     apOld[i] = 0;
55990     i++;
55991   }
55992
55993   /*
55994   ** Put the new pages in accending order.  This helps to
55995   ** keep entries in the disk file in order so that a scan
55996   ** of the table is a linear scan through the file.  That
55997   ** in turn helps the operating system to deliver pages
55998   ** from the disk more rapidly.
55999   **
56000   ** An O(n^2) insertion sort algorithm is used, but since
56001   ** n is never more than NB (a small constant), that should
56002   ** not be a problem.
56003   **
56004   ** When NB==3, this one optimization makes the database
56005   ** about 25% faster for large insertions and deletions.
56006   */
56007   for(i=0; i<k-1; i++){
56008     int minV = apNew[i]->pgno;
56009     int minI = i;
56010     for(j=i+1; j<k; j++){
56011       if( apNew[j]->pgno<(unsigned)minV ){
56012         minI = j;
56013         minV = apNew[j]->pgno;
56014       }
56015     }
56016     if( minI>i ){
56017       MemPage *pT;
56018       pT = apNew[i];
56019       apNew[i] = apNew[minI];
56020       apNew[minI] = pT;
56021     }
56022   }
56023   TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
56024     apNew[0]->pgno, szNew[0],
56025     nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
56026     nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
56027     nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
56028     nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
56029
56030   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
56031   put4byte(pRight, apNew[nNew-1]->pgno);
56032
56033   /*
56034   ** Evenly distribute the data in apCell[] across the new pages.
56035   ** Insert divider cells into pParent as necessary.
56036   */
56037   j = 0;
56038   for(i=0; i<nNew; i++){
56039     /* Assemble the new sibling page. */
56040     MemPage *pNew = apNew[i];
56041     assert( j<nMaxCells );
56042     zeroPage(pNew, pageFlags);
56043     assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
56044     assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
56045     assert( pNew->nOverflow==0 );
56046
56047     j = cntNew[i];
56048
56049     /* If the sibling page assembled above was not the right-most sibling,
56050     ** insert a divider cell into the parent page.
56051     */
56052     assert( i<nNew-1 || j==nCell );
56053     if( j<nCell ){
56054       u8 *pCell;
56055       u8 *pTemp;
56056       int sz;
56057
56058       assert( j<nMaxCells );
56059       pCell = apCell[j];
56060       sz = szCell[j] + leafCorrection;
56061       pTemp = &aOvflSpace[iOvflSpace];
56062       if( !pNew->leaf ){
56063         memcpy(&pNew->aData[8], pCell, 4);
56064       }else if( leafData ){
56065         /* If the tree is a leaf-data tree, and the siblings are leaves, 
56066         ** then there is no divider cell in apCell[]. Instead, the divider 
56067         ** cell consists of the integer key for the right-most cell of 
56068         ** the sibling-page assembled above only.
56069         */
56070         CellInfo info;
56071         j--;
56072         btreeParseCellPtr(pNew, apCell[j], &info);
56073         pCell = pTemp;
56074         sz = 4 + putVarint(&pCell[4], info.nKey);
56075         pTemp = 0;
56076       }else{
56077         pCell -= 4;
56078         /* Obscure case for non-leaf-data trees: If the cell at pCell was
56079         ** previously stored on a leaf node, and its reported size was 4
56080         ** bytes, then it may actually be smaller than this 
56081         ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
56082         ** any cell). But it is important to pass the correct size to 
56083         ** insertCell(), so reparse the cell now.
56084         **
56085         ** Note that this can never happen in an SQLite data file, as all
56086         ** cells are at least 4 bytes. It only happens in b-trees used
56087         ** to evaluate "IN (SELECT ...)" and similar clauses.
56088         */
56089         if( szCell[j]==4 ){
56090           assert(leafCorrection==4);
56091           sz = cellSizePtr(pParent, pCell);
56092         }
56093       }
56094       iOvflSpace += sz;
56095       assert( sz<=pBt->maxLocal+23 );
56096       assert( iOvflSpace <= (int)pBt->pageSize );
56097       insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
56098       if( rc!=SQLITE_OK ) goto balance_cleanup;
56099       assert( sqlite3PagerIswriteable(pParent->pDbPage) );
56100
56101       j++;
56102       nxDiv++;
56103     }
56104   }
56105   assert( j==nCell );
56106   assert( nOld>0 );
56107   assert( nNew>0 );
56108   if( (pageFlags & PTF_LEAF)==0 ){
56109     u8 *zChild = &apCopy[nOld-1]->aData[8];
56110     memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
56111   }
56112
56113   if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
56114     /* The root page of the b-tree now contains no cells. The only sibling
56115     ** page is the right-child of the parent. Copy the contents of the
56116     ** child page into the parent, decreasing the overall height of the
56117     ** b-tree structure by one. This is described as the "balance-shallower"
56118     ** sub-algorithm in some documentation.
56119     **
56120     ** If this is an auto-vacuum database, the call to copyNodeContent() 
56121     ** sets all pointer-map entries corresponding to database image pages 
56122     ** for which the pointer is stored within the content being copied.
56123     **
56124     ** The second assert below verifies that the child page is defragmented
56125     ** (it must be, as it was just reconstructed using assemblePage()). This
56126     ** is important if the parent page happens to be page 1 of the database
56127     ** image.  */
56128     assert( nNew==1 );
56129     assert( apNew[0]->nFree == 
56130         (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2) 
56131     );
56132     copyNodeContent(apNew[0], pParent, &rc);
56133     freePage(apNew[0], &rc);
56134   }else if( ISAUTOVACUUM ){
56135     /* Fix the pointer-map entries for all the cells that were shifted around. 
56136     ** There are several different types of pointer-map entries that need to
56137     ** be dealt with by this routine. Some of these have been set already, but
56138     ** many have not. The following is a summary:
56139     **
56140     **   1) The entries associated with new sibling pages that were not
56141     **      siblings when this function was called. These have already
56142     **      been set. We don't need to worry about old siblings that were
56143     **      moved to the free-list - the freePage() code has taken care
56144     **      of those.
56145     **
56146     **   2) The pointer-map entries associated with the first overflow
56147     **      page in any overflow chains used by new divider cells. These 
56148     **      have also already been taken care of by the insertCell() code.
56149     **
56150     **   3) If the sibling pages are not leaves, then the child pages of
56151     **      cells stored on the sibling pages may need to be updated.
56152     **
56153     **   4) If the sibling pages are not internal intkey nodes, then any
56154     **      overflow pages used by these cells may need to be updated
56155     **      (internal intkey nodes never contain pointers to overflow pages).
56156     **
56157     **   5) If the sibling pages are not leaves, then the pointer-map
56158     **      entries for the right-child pages of each sibling may need
56159     **      to be updated.
56160     **
56161     ** Cases 1 and 2 are dealt with above by other code. The next
56162     ** block deals with cases 3 and 4 and the one after that, case 5. Since
56163     ** setting a pointer map entry is a relatively expensive operation, this
56164     ** code only sets pointer map entries for child or overflow pages that have
56165     ** actually moved between pages.  */
56166     MemPage *pNew = apNew[0];
56167     MemPage *pOld = apCopy[0];
56168     int nOverflow = pOld->nOverflow;
56169     int iNextOld = pOld->nCell + nOverflow;
56170     int iOverflow = (nOverflow ? pOld->aiOvfl[0] : -1);
56171     j = 0;                             /* Current 'old' sibling page */
56172     k = 0;                             /* Current 'new' sibling page */
56173     for(i=0; i<nCell; i++){
56174       int isDivider = 0;
56175       while( i==iNextOld ){
56176         /* Cell i is the cell immediately following the last cell on old
56177         ** sibling page j. If the siblings are not leaf pages of an
56178         ** intkey b-tree, then cell i was a divider cell. */
56179         assert( j+1 < ArraySize(apCopy) );
56180         assert( j+1 < nOld );
56181         pOld = apCopy[++j];
56182         iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
56183         if( pOld->nOverflow ){
56184           nOverflow = pOld->nOverflow;
56185           iOverflow = i + !leafData + pOld->aiOvfl[0];
56186         }
56187         isDivider = !leafData;  
56188       }
56189
56190       assert(nOverflow>0 || iOverflow<i );
56191       assert(nOverflow<2 || pOld->aiOvfl[0]==pOld->aiOvfl[1]-1);
56192       assert(nOverflow<3 || pOld->aiOvfl[1]==pOld->aiOvfl[2]-1);
56193       if( i==iOverflow ){
56194         isDivider = 1;
56195         if( (--nOverflow)>0 ){
56196           iOverflow++;
56197         }
56198       }
56199
56200       if( i==cntNew[k] ){
56201         /* Cell i is the cell immediately following the last cell on new
56202         ** sibling page k. If the siblings are not leaf pages of an
56203         ** intkey b-tree, then cell i is a divider cell.  */
56204         pNew = apNew[++k];
56205         if( !leafData ) continue;
56206       }
56207       assert( j<nOld );
56208       assert( k<nNew );
56209
56210       /* If the cell was originally divider cell (and is not now) or
56211       ** an overflow cell, or if the cell was located on a different sibling
56212       ** page before the balancing, then the pointer map entries associated
56213       ** with any child or overflow pages need to be updated.  */
56214       if( isDivider || pOld->pgno!=pNew->pgno ){
56215         if( !leafCorrection ){
56216           ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
56217         }
56218         if( szCell[i]>pNew->minLocal ){
56219           ptrmapPutOvflPtr(pNew, apCell[i], &rc);
56220         }
56221       }
56222     }
56223
56224     if( !leafCorrection ){
56225       for(i=0; i<nNew; i++){
56226         u32 key = get4byte(&apNew[i]->aData[8]);
56227         ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
56228       }
56229     }
56230
56231 #if 0
56232     /* The ptrmapCheckPages() contains assert() statements that verify that
56233     ** all pointer map pages are set correctly. This is helpful while 
56234     ** debugging. This is usually disabled because a corrupt database may
56235     ** cause an assert() statement to fail.  */
56236     ptrmapCheckPages(apNew, nNew);
56237     ptrmapCheckPages(&pParent, 1);
56238 #endif
56239   }
56240
56241   assert( pParent->isInit );
56242   TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
56243           nOld, nNew, nCell));
56244
56245   /*
56246   ** Cleanup before returning.
56247   */
56248 balance_cleanup:
56249   sqlite3ScratchFree(apCell);
56250   for(i=0; i<nOld; i++){
56251     releasePage(apOld[i]);
56252   }
56253   for(i=0; i<nNew; i++){
56254     releasePage(apNew[i]);
56255   }
56256
56257   return rc;
56258 }
56259 #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
56260 #pragma optimize("", on)
56261 #endif
56262
56263
56264 /*
56265 ** This function is called when the root page of a b-tree structure is
56266 ** overfull (has one or more overflow pages).
56267 **
56268 ** A new child page is allocated and the contents of the current root
56269 ** page, including overflow cells, are copied into the child. The root
56270 ** page is then overwritten to make it an empty page with the right-child 
56271 ** pointer pointing to the new page.
56272 **
56273 ** Before returning, all pointer-map entries corresponding to pages 
56274 ** that the new child-page now contains pointers to are updated. The
56275 ** entry corresponding to the new right-child pointer of the root
56276 ** page is also updated.
56277 **
56278 ** If successful, *ppChild is set to contain a reference to the child 
56279 ** page and SQLITE_OK is returned. In this case the caller is required
56280 ** to call releasePage() on *ppChild exactly once. If an error occurs,
56281 ** an error code is returned and *ppChild is set to 0.
56282 */
56283 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
56284   int rc;                        /* Return value from subprocedures */
56285   MemPage *pChild = 0;           /* Pointer to a new child page */
56286   Pgno pgnoChild = 0;            /* Page number of the new child page */
56287   BtShared *pBt = pRoot->pBt;    /* The BTree */
56288
56289   assert( pRoot->nOverflow>0 );
56290   assert( sqlite3_mutex_held(pBt->mutex) );
56291
56292   /* Make pRoot, the root page of the b-tree, writable. Allocate a new 
56293   ** page that will become the new right-child of pPage. Copy the contents
56294   ** of the node stored on pRoot into the new child page.
56295   */
56296   rc = sqlite3PagerWrite(pRoot->pDbPage);
56297   if( rc==SQLITE_OK ){
56298     rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
56299     copyNodeContent(pRoot, pChild, &rc);
56300     if( ISAUTOVACUUM ){
56301       ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
56302     }
56303   }
56304   if( rc ){
56305     *ppChild = 0;
56306     releasePage(pChild);
56307     return rc;
56308   }
56309   assert( sqlite3PagerIswriteable(pChild->pDbPage) );
56310   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
56311   assert( pChild->nCell==pRoot->nCell );
56312
56313   TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
56314
56315   /* Copy the overflow cells from pRoot to pChild */
56316   memcpy(pChild->aiOvfl, pRoot->aiOvfl,
56317          pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
56318   memcpy(pChild->apOvfl, pRoot->apOvfl,
56319          pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
56320   pChild->nOverflow = pRoot->nOverflow;
56321
56322   /* Zero the contents of pRoot. Then install pChild as the right-child. */
56323   zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
56324   put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
56325
56326   *ppChild = pChild;
56327   return SQLITE_OK;
56328 }
56329
56330 /*
56331 ** The page that pCur currently points to has just been modified in
56332 ** some way. This function figures out if this modification means the
56333 ** tree needs to be balanced, and if so calls the appropriate balancing 
56334 ** routine. Balancing routines are:
56335 **
56336 **   balance_quick()
56337 **   balance_deeper()
56338 **   balance_nonroot()
56339 */
56340 static int balance(BtCursor *pCur){
56341   int rc = SQLITE_OK;
56342   const int nMin = pCur->pBt->usableSize * 2 / 3;
56343   u8 aBalanceQuickSpace[13];
56344   u8 *pFree = 0;
56345
56346   TESTONLY( int balance_quick_called = 0 );
56347   TESTONLY( int balance_deeper_called = 0 );
56348
56349   do {
56350     int iPage = pCur->iPage;
56351     MemPage *pPage = pCur->apPage[iPage];
56352
56353     if( iPage==0 ){
56354       if( pPage->nOverflow ){
56355         /* The root page of the b-tree is overfull. In this case call the
56356         ** balance_deeper() function to create a new child for the root-page
56357         ** and copy the current contents of the root-page to it. The
56358         ** next iteration of the do-loop will balance the child page.
56359         */ 
56360         assert( (balance_deeper_called++)==0 );
56361         rc = balance_deeper(pPage, &pCur->apPage[1]);
56362         if( rc==SQLITE_OK ){
56363           pCur->iPage = 1;
56364           pCur->aiIdx[0] = 0;
56365           pCur->aiIdx[1] = 0;
56366           assert( pCur->apPage[1]->nOverflow );
56367         }
56368       }else{
56369         break;
56370       }
56371     }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
56372       break;
56373     }else{
56374       MemPage * const pParent = pCur->apPage[iPage-1];
56375       int const iIdx = pCur->aiIdx[iPage-1];
56376
56377       rc = sqlite3PagerWrite(pParent->pDbPage);
56378       if( rc==SQLITE_OK ){
56379 #ifndef SQLITE_OMIT_QUICKBALANCE
56380         if( pPage->hasData
56381          && pPage->nOverflow==1
56382          && pPage->aiOvfl[0]==pPage->nCell
56383          && pParent->pgno!=1
56384          && pParent->nCell==iIdx
56385         ){
56386           /* Call balance_quick() to create a new sibling of pPage on which
56387           ** to store the overflow cell. balance_quick() inserts a new cell
56388           ** into pParent, which may cause pParent overflow. If this
56389           ** happens, the next interation of the do-loop will balance pParent 
56390           ** use either balance_nonroot() or balance_deeper(). Until this
56391           ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
56392           ** buffer. 
56393           **
56394           ** The purpose of the following assert() is to check that only a
56395           ** single call to balance_quick() is made for each call to this
56396           ** function. If this were not verified, a subtle bug involving reuse
56397           ** of the aBalanceQuickSpace[] might sneak in.
56398           */
56399           assert( (balance_quick_called++)==0 );
56400           rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
56401         }else
56402 #endif
56403         {
56404           /* In this case, call balance_nonroot() to redistribute cells
56405           ** between pPage and up to 2 of its sibling pages. This involves
56406           ** modifying the contents of pParent, which may cause pParent to
56407           ** become overfull or underfull. The next iteration of the do-loop
56408           ** will balance the parent page to correct this.
56409           ** 
56410           ** If the parent page becomes overfull, the overflow cell or cells
56411           ** are stored in the pSpace buffer allocated immediately below. 
56412           ** A subsequent iteration of the do-loop will deal with this by
56413           ** calling balance_nonroot() (balance_deeper() may be called first,
56414           ** but it doesn't deal with overflow cells - just moves them to a
56415           ** different page). Once this subsequent call to balance_nonroot() 
56416           ** has completed, it is safe to release the pSpace buffer used by
56417           ** the previous call, as the overflow cell data will have been 
56418           ** copied either into the body of a database page or into the new
56419           ** pSpace buffer passed to the latter call to balance_nonroot().
56420           */
56421           u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
56422           rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1, pCur->hints);
56423           if( pFree ){
56424             /* If pFree is not NULL, it points to the pSpace buffer used 
56425             ** by a previous call to balance_nonroot(). Its contents are
56426             ** now stored either on real database pages or within the 
56427             ** new pSpace buffer, so it may be safely freed here. */
56428             sqlite3PageFree(pFree);
56429           }
56430
56431           /* The pSpace buffer will be freed after the next call to
56432           ** balance_nonroot(), or just before this function returns, whichever
56433           ** comes first. */
56434           pFree = pSpace;
56435         }
56436       }
56437
56438       pPage->nOverflow = 0;
56439
56440       /* The next iteration of the do-loop balances the parent page. */
56441       releasePage(pPage);
56442       pCur->iPage--;
56443     }
56444   }while( rc==SQLITE_OK );
56445
56446   if( pFree ){
56447     sqlite3PageFree(pFree);
56448   }
56449   return rc;
56450 }
56451
56452
56453 /*
56454 ** Insert a new record into the BTree.  The key is given by (pKey,nKey)
56455 ** and the data is given by (pData,nData).  The cursor is used only to
56456 ** define what table the record should be inserted into.  The cursor
56457 ** is left pointing at a random location.
56458 **
56459 ** For an INTKEY table, only the nKey value of the key is used.  pKey is
56460 ** ignored.  For a ZERODATA table, the pData and nData are both ignored.
56461 **
56462 ** If the seekResult parameter is non-zero, then a successful call to
56463 ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
56464 ** been performed. seekResult is the search result returned (a negative
56465 ** number if pCur points at an entry that is smaller than (pKey, nKey), or
56466 ** a positive value if pCur points at an etry that is larger than 
56467 ** (pKey, nKey)). 
56468 **
56469 ** If the seekResult parameter is non-zero, then the caller guarantees that
56470 ** cursor pCur is pointing at the existing copy of a row that is to be
56471 ** overwritten.  If the seekResult parameter is 0, then cursor pCur may
56472 ** point to any entry or to no entry at all and so this function has to seek
56473 ** the cursor before the new key can be inserted.
56474 */
56475 SQLITE_PRIVATE int sqlite3BtreeInsert(
56476   BtCursor *pCur,                /* Insert data into the table of this cursor */
56477   const void *pKey, i64 nKey,    /* The key of the new record */
56478   const void *pData, int nData,  /* The data of the new record */
56479   int nZero,                     /* Number of extra 0 bytes to append to data */
56480   int appendBias,                /* True if this is likely an append */
56481   int seekResult                 /* Result of prior MovetoUnpacked() call */
56482 ){
56483   int rc;
56484   int loc = seekResult;          /* -1: before desired location  +1: after */
56485   int szNew = 0;
56486   int idx;
56487   MemPage *pPage;
56488   Btree *p = pCur->pBtree;
56489   BtShared *pBt = p->pBt;
56490   unsigned char *oldCell;
56491   unsigned char *newCell = 0;
56492
56493   if( pCur->eState==CURSOR_FAULT ){
56494     assert( pCur->skipNext!=SQLITE_OK );
56495     return pCur->skipNext;
56496   }
56497
56498   assert( cursorHoldsMutex(pCur) );
56499   assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE
56500               && (pBt->btsFlags & BTS_READ_ONLY)==0 );
56501   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
56502
56503   /* Assert that the caller has been consistent. If this cursor was opened
56504   ** expecting an index b-tree, then the caller should be inserting blob
56505   ** keys with no associated data. If the cursor was opened expecting an
56506   ** intkey table, the caller should be inserting integer keys with a
56507   ** blob of associated data.  */
56508   assert( (pKey==0)==(pCur->pKeyInfo==0) );
56509
56510   /* Save the positions of any other cursors open on this table.
56511   **
56512   ** In some cases, the call to btreeMoveto() below is a no-op. For
56513   ** example, when inserting data into a table with auto-generated integer
56514   ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the 
56515   ** integer key to use. It then calls this function to actually insert the 
56516   ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
56517   ** that the cursor is already where it needs to be and returns without
56518   ** doing any work. To avoid thwarting these optimizations, it is important
56519   ** not to clear the cursor here.
56520   */
56521   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
56522   if( rc ) return rc;
56523
56524   /* If this is an insert into a table b-tree, invalidate any incrblob 
56525   ** cursors open on the row being replaced (assuming this is a replace
56526   ** operation - if it is not, the following is a no-op).  */
56527   if( pCur->pKeyInfo==0 ){
56528     invalidateIncrblobCursors(p, nKey, 0);
56529   }
56530
56531   if( !loc ){
56532     rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
56533     if( rc ) return rc;
56534   }
56535   assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
56536
56537   pPage = pCur->apPage[pCur->iPage];
56538   assert( pPage->intKey || nKey>=0 );
56539   assert( pPage->leaf || !pPage->intKey );
56540
56541   TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
56542           pCur->pgnoRoot, nKey, nData, pPage->pgno,
56543           loc==0 ? "overwrite" : "new entry"));
56544   assert( pPage->isInit );
56545   allocateTempSpace(pBt);
56546   newCell = pBt->pTmpSpace;
56547   if( newCell==0 ) return SQLITE_NOMEM;
56548   rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
56549   if( rc ) goto end_insert;
56550   assert( szNew==cellSizePtr(pPage, newCell) );
56551   assert( szNew <= MX_CELL_SIZE(pBt) );
56552   idx = pCur->aiIdx[pCur->iPage];
56553   if( loc==0 ){
56554     u16 szOld;
56555     assert( idx<pPage->nCell );
56556     rc = sqlite3PagerWrite(pPage->pDbPage);
56557     if( rc ){
56558       goto end_insert;
56559     }
56560     oldCell = findCell(pPage, idx);
56561     if( !pPage->leaf ){
56562       memcpy(newCell, oldCell, 4);
56563     }
56564     szOld = cellSizePtr(pPage, oldCell);
56565     rc = clearCell(pPage, oldCell);
56566     dropCell(pPage, idx, szOld, &rc);
56567     if( rc ) goto end_insert;
56568   }else if( loc<0 && pPage->nCell>0 ){
56569     assert( pPage->leaf );
56570     idx = ++pCur->aiIdx[pCur->iPage];
56571   }else{
56572     assert( pPage->leaf );
56573   }
56574   insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
56575   assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
56576
56577   /* If no error has occurred and pPage has an overflow cell, call balance() 
56578   ** to redistribute the cells within the tree. Since balance() may move
56579   ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
56580   ** variables.
56581   **
56582   ** Previous versions of SQLite called moveToRoot() to move the cursor
56583   ** back to the root page as balance() used to invalidate the contents
56584   ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
56585   ** set the cursor state to "invalid". This makes common insert operations
56586   ** slightly faster.
56587   **
56588   ** There is a subtle but important optimization here too. When inserting
56589   ** multiple records into an intkey b-tree using a single cursor (as can
56590   ** happen while processing an "INSERT INTO ... SELECT" statement), it
56591   ** is advantageous to leave the cursor pointing to the last entry in
56592   ** the b-tree if possible. If the cursor is left pointing to the last
56593   ** entry in the table, and the next row inserted has an integer key
56594   ** larger than the largest existing key, it is possible to insert the
56595   ** row without seeking the cursor. This can be a big performance boost.
56596   */
56597   pCur->info.nSize = 0;
56598   pCur->validNKey = 0;
56599   if( rc==SQLITE_OK && pPage->nOverflow ){
56600     rc = balance(pCur);
56601
56602     /* Must make sure nOverflow is reset to zero even if the balance()
56603     ** fails. Internal data structure corruption will result otherwise. 
56604     ** Also, set the cursor state to invalid. This stops saveCursorPosition()
56605     ** from trying to save the current position of the cursor.  */
56606     pCur->apPage[pCur->iPage]->nOverflow = 0;
56607     pCur->eState = CURSOR_INVALID;
56608   }
56609   assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
56610
56611 end_insert:
56612   return rc;
56613 }
56614
56615 /*
56616 ** Delete the entry that the cursor is pointing to.  The cursor
56617 ** is left pointing at a arbitrary location.
56618 */
56619 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
56620   Btree *p = pCur->pBtree;
56621   BtShared *pBt = p->pBt;              
56622   int rc;                              /* Return code */
56623   MemPage *pPage;                      /* Page to delete cell from */
56624   unsigned char *pCell;                /* Pointer to cell to delete */
56625   int iCellIdx;                        /* Index of cell to delete */
56626   int iCellDepth;                      /* Depth of node containing pCell */ 
56627
56628   assert( cursorHoldsMutex(pCur) );
56629   assert( pBt->inTransaction==TRANS_WRITE );
56630   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
56631   assert( pCur->wrFlag );
56632   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
56633   assert( !hasReadConflicts(p, pCur->pgnoRoot) );
56634
56635   if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell) 
56636    || NEVER(pCur->eState!=CURSOR_VALID)
56637   ){
56638     return SQLITE_ERROR;  /* Something has gone awry. */
56639   }
56640
56641   iCellDepth = pCur->iPage;
56642   iCellIdx = pCur->aiIdx[iCellDepth];
56643   pPage = pCur->apPage[iCellDepth];
56644   pCell = findCell(pPage, iCellIdx);
56645
56646   /* If the page containing the entry to delete is not a leaf page, move
56647   ** the cursor to the largest entry in the tree that is smaller than
56648   ** the entry being deleted. This cell will replace the cell being deleted
56649   ** from the internal node. The 'previous' entry is used for this instead
56650   ** of the 'next' entry, as the previous entry is always a part of the
56651   ** sub-tree headed by the child page of the cell being deleted. This makes
56652   ** balancing the tree following the delete operation easier.  */
56653   if( !pPage->leaf ){
56654     int notUsed;
56655     rc = sqlite3BtreePrevious(pCur, &notUsed);
56656     if( rc ) return rc;
56657   }
56658
56659   /* Save the positions of any other cursors open on this table before
56660   ** making any modifications. Make the page containing the entry to be 
56661   ** deleted writable. Then free any overflow pages associated with the 
56662   ** entry and finally remove the cell itself from within the page.  
56663   */
56664   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
56665   if( rc ) return rc;
56666
56667   /* If this is a delete operation to remove a row from a table b-tree,
56668   ** invalidate any incrblob cursors open on the row being deleted.  */
56669   if( pCur->pKeyInfo==0 ){
56670     invalidateIncrblobCursors(p, pCur->info.nKey, 0);
56671   }
56672
56673   rc = sqlite3PagerWrite(pPage->pDbPage);
56674   if( rc ) return rc;
56675   rc = clearCell(pPage, pCell);
56676   dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
56677   if( rc ) return rc;
56678
56679   /* If the cell deleted was not located on a leaf page, then the cursor
56680   ** is currently pointing to the largest entry in the sub-tree headed
56681   ** by the child-page of the cell that was just deleted from an internal
56682   ** node. The cell from the leaf node needs to be moved to the internal
56683   ** node to replace the deleted cell.  */
56684   if( !pPage->leaf ){
56685     MemPage *pLeaf = pCur->apPage[pCur->iPage];
56686     int nCell;
56687     Pgno n = pCur->apPage[iCellDepth+1]->pgno;
56688     unsigned char *pTmp;
56689
56690     pCell = findCell(pLeaf, pLeaf->nCell-1);
56691     nCell = cellSizePtr(pLeaf, pCell);
56692     assert( MX_CELL_SIZE(pBt) >= nCell );
56693
56694     allocateTempSpace(pBt);
56695     pTmp = pBt->pTmpSpace;
56696
56697     rc = sqlite3PagerWrite(pLeaf->pDbPage);
56698     insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
56699     dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
56700     if( rc ) return rc;
56701   }
56702
56703   /* Balance the tree. If the entry deleted was located on a leaf page,
56704   ** then the cursor still points to that page. In this case the first
56705   ** call to balance() repairs the tree, and the if(...) condition is
56706   ** never true.
56707   **
56708   ** Otherwise, if the entry deleted was on an internal node page, then
56709   ** pCur is pointing to the leaf page from which a cell was removed to
56710   ** replace the cell deleted from the internal node. This is slightly
56711   ** tricky as the leaf node may be underfull, and the internal node may
56712   ** be either under or overfull. In this case run the balancing algorithm
56713   ** on the leaf node first. If the balance proceeds far enough up the
56714   ** tree that we can be sure that any problem in the internal node has
56715   ** been corrected, so be it. Otherwise, after balancing the leaf node,
56716   ** walk the cursor up the tree to the internal node and balance it as 
56717   ** well.  */
56718   rc = balance(pCur);
56719   if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
56720     while( pCur->iPage>iCellDepth ){
56721       releasePage(pCur->apPage[pCur->iPage--]);
56722     }
56723     rc = balance(pCur);
56724   }
56725
56726   if( rc==SQLITE_OK ){
56727     moveToRoot(pCur);
56728   }
56729   return rc;
56730 }
56731
56732 /*
56733 ** Create a new BTree table.  Write into *piTable the page
56734 ** number for the root page of the new table.
56735 **
56736 ** The type of type is determined by the flags parameter.  Only the
56737 ** following values of flags are currently in use.  Other values for
56738 ** flags might not work:
56739 **
56740 **     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
56741 **     BTREE_ZERODATA                  Used for SQL indices
56742 */
56743 static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
56744   BtShared *pBt = p->pBt;
56745   MemPage *pRoot;
56746   Pgno pgnoRoot;
56747   int rc;
56748   int ptfFlags;          /* Page-type flage for the root page of new table */
56749
56750   assert( sqlite3BtreeHoldsMutex(p) );
56751   assert( pBt->inTransaction==TRANS_WRITE );
56752   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
56753
56754 #ifdef SQLITE_OMIT_AUTOVACUUM
56755   rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
56756   if( rc ){
56757     return rc;
56758   }
56759 #else
56760   if( pBt->autoVacuum ){
56761     Pgno pgnoMove;      /* Move a page here to make room for the root-page */
56762     MemPage *pPageMove; /* The page to move to. */
56763
56764     /* Creating a new table may probably require moving an existing database
56765     ** to make room for the new tables root page. In case this page turns
56766     ** out to be an overflow page, delete all overflow page-map caches
56767     ** held by open cursors.
56768     */
56769     invalidateAllOverflowCache(pBt);
56770
56771     /* Read the value of meta[3] from the database to determine where the
56772     ** root page of the new table should go. meta[3] is the largest root-page
56773     ** created so far, so the new root-page is (meta[3]+1).
56774     */
56775     sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
56776     pgnoRoot++;
56777
56778     /* The new root-page may not be allocated on a pointer-map page, or the
56779     ** PENDING_BYTE page.
56780     */
56781     while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
56782         pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
56783       pgnoRoot++;
56784     }
56785     assert( pgnoRoot>=3 );
56786
56787     /* Allocate a page. The page that currently resides at pgnoRoot will
56788     ** be moved to the allocated page (unless the allocated page happens
56789     ** to reside at pgnoRoot).
56790     */
56791     rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
56792     if( rc!=SQLITE_OK ){
56793       return rc;
56794     }
56795
56796     if( pgnoMove!=pgnoRoot ){
56797       /* pgnoRoot is the page that will be used for the root-page of
56798       ** the new table (assuming an error did not occur). But we were
56799       ** allocated pgnoMove. If required (i.e. if it was not allocated
56800       ** by extending the file), the current page at position pgnoMove
56801       ** is already journaled.
56802       */
56803       u8 eType = 0;
56804       Pgno iPtrPage = 0;
56805
56806       /* Save the positions of any open cursors. This is required in
56807       ** case they are holding a reference to an xFetch reference
56808       ** corresponding to page pgnoRoot.  */
56809       rc = saveAllCursors(pBt, 0, 0);
56810       releasePage(pPageMove);
56811       if( rc!=SQLITE_OK ){
56812         return rc;
56813       }
56814
56815       /* Move the page currently at pgnoRoot to pgnoMove. */
56816       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0, 0);
56817       if( rc!=SQLITE_OK ){
56818         return rc;
56819       }
56820       rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
56821       if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
56822         rc = SQLITE_CORRUPT_BKPT;
56823       }
56824       if( rc!=SQLITE_OK ){
56825         releasePage(pRoot);
56826         return rc;
56827       }
56828       assert( eType!=PTRMAP_ROOTPAGE );
56829       assert( eType!=PTRMAP_FREEPAGE );
56830       rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
56831       releasePage(pRoot);
56832
56833       /* Obtain the page at pgnoRoot */
56834       if( rc!=SQLITE_OK ){
56835         return rc;
56836       }
56837       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0, 0);
56838       if( rc!=SQLITE_OK ){
56839         return rc;
56840       }
56841       rc = sqlite3PagerWrite(pRoot->pDbPage);
56842       if( rc!=SQLITE_OK ){
56843         releasePage(pRoot);
56844         return rc;
56845       }
56846     }else{
56847       pRoot = pPageMove;
56848     } 
56849
56850     /* Update the pointer-map and meta-data with the new root-page number. */
56851     ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
56852     if( rc ){
56853       releasePage(pRoot);
56854       return rc;
56855     }
56856
56857     /* When the new root page was allocated, page 1 was made writable in
56858     ** order either to increase the database filesize, or to decrement the
56859     ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
56860     */
56861     assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
56862     rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
56863     if( NEVER(rc) ){
56864       releasePage(pRoot);
56865       return rc;
56866     }
56867
56868   }else{
56869     rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
56870     if( rc ) return rc;
56871   }
56872 #endif
56873   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
56874   if( createTabFlags & BTREE_INTKEY ){
56875     ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
56876   }else{
56877     ptfFlags = PTF_ZERODATA | PTF_LEAF;
56878   }
56879   zeroPage(pRoot, ptfFlags);
56880   sqlite3PagerUnref(pRoot->pDbPage);
56881   assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
56882   *piTable = (int)pgnoRoot;
56883   return SQLITE_OK;
56884 }
56885 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
56886   int rc;
56887   sqlite3BtreeEnter(p);
56888   rc = btreeCreateTable(p, piTable, flags);
56889   sqlite3BtreeLeave(p);
56890   return rc;
56891 }
56892
56893 /*
56894 ** Erase the given database page and all its children.  Return
56895 ** the page to the freelist.
56896 */
56897 static int clearDatabasePage(
56898   BtShared *pBt,           /* The BTree that contains the table */
56899   Pgno pgno,               /* Page number to clear */
56900   int freePageFlag,        /* Deallocate page if true */
56901   int *pnChange            /* Add number of Cells freed to this counter */
56902 ){
56903   MemPage *pPage;
56904   int rc;
56905   unsigned char *pCell;
56906   int i;
56907
56908   assert( sqlite3_mutex_held(pBt->mutex) );
56909   if( pgno>btreePagecount(pBt) ){
56910     return SQLITE_CORRUPT_BKPT;
56911   }
56912
56913   rc = getAndInitPage(pBt, pgno, &pPage, 0);
56914   if( rc ) return rc;
56915   for(i=0; i<pPage->nCell; i++){
56916     pCell = findCell(pPage, i);
56917     if( !pPage->leaf ){
56918       rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
56919       if( rc ) goto cleardatabasepage_out;
56920     }
56921     rc = clearCell(pPage, pCell);
56922     if( rc ) goto cleardatabasepage_out;
56923   }
56924   if( !pPage->leaf ){
56925     rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
56926     if( rc ) goto cleardatabasepage_out;
56927   }else if( pnChange ){
56928     assert( pPage->intKey );
56929     *pnChange += pPage->nCell;
56930   }
56931   if( freePageFlag ){
56932     freePage(pPage, &rc);
56933   }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
56934     zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
56935   }
56936
56937 cleardatabasepage_out:
56938   releasePage(pPage);
56939   return rc;
56940 }
56941
56942 /*
56943 ** Delete all information from a single table in the database.  iTable is
56944 ** the page number of the root of the table.  After this routine returns,
56945 ** the root page is empty, but still exists.
56946 **
56947 ** This routine will fail with SQLITE_LOCKED if there are any open
56948 ** read cursors on the table.  Open write cursors are moved to the
56949 ** root of the table.
56950 **
56951 ** If pnChange is not NULL, then table iTable must be an intkey table. The
56952 ** integer value pointed to by pnChange is incremented by the number of
56953 ** entries in the table.
56954 */
56955 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
56956   int rc;
56957   BtShared *pBt = p->pBt;
56958   sqlite3BtreeEnter(p);
56959   assert( p->inTrans==TRANS_WRITE );
56960
56961   rc = saveAllCursors(pBt, (Pgno)iTable, 0);
56962
56963   if( SQLITE_OK==rc ){
56964     /* Invalidate all incrblob cursors open on table iTable (assuming iTable
56965     ** is the root of a table b-tree - if it is not, the following call is
56966     ** a no-op).  */
56967     invalidateIncrblobCursors(p, 0, 1);
56968     rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
56969   }
56970   sqlite3BtreeLeave(p);
56971   return rc;
56972 }
56973
56974 /*
56975 ** Erase all information in a table and add the root of the table to
56976 ** the freelist.  Except, the root of the principle table (the one on
56977 ** page 1) is never added to the freelist.
56978 **
56979 ** This routine will fail with SQLITE_LOCKED if there are any open
56980 ** cursors on the table.
56981 **
56982 ** If AUTOVACUUM is enabled and the page at iTable is not the last
56983 ** root page in the database file, then the last root page 
56984 ** in the database file is moved into the slot formerly occupied by
56985 ** iTable and that last slot formerly occupied by the last root page
56986 ** is added to the freelist instead of iTable.  In this say, all
56987 ** root pages are kept at the beginning of the database file, which
56988 ** is necessary for AUTOVACUUM to work right.  *piMoved is set to the 
56989 ** page number that used to be the last root page in the file before
56990 ** the move.  If no page gets moved, *piMoved is set to 0.
56991 ** The last root page is recorded in meta[3] and the value of
56992 ** meta[3] is updated by this procedure.
56993 */
56994 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
56995   int rc;
56996   MemPage *pPage = 0;
56997   BtShared *pBt = p->pBt;
56998
56999   assert( sqlite3BtreeHoldsMutex(p) );
57000   assert( p->inTrans==TRANS_WRITE );
57001
57002   /* It is illegal to drop a table if any cursors are open on the
57003   ** database. This is because in auto-vacuum mode the backend may
57004   ** need to move another root-page to fill a gap left by the deleted
57005   ** root page. If an open cursor was using this page a problem would 
57006   ** occur.
57007   **
57008   ** This error is caught long before control reaches this point.
57009   */
57010   if( NEVER(pBt->pCursor) ){
57011     sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
57012     return SQLITE_LOCKED_SHAREDCACHE;
57013   }
57014
57015   rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0, 0);
57016   if( rc ) return rc;
57017   rc = sqlite3BtreeClearTable(p, iTable, 0);
57018   if( rc ){
57019     releasePage(pPage);
57020     return rc;
57021   }
57022
57023   *piMoved = 0;
57024
57025   if( iTable>1 ){
57026 #ifdef SQLITE_OMIT_AUTOVACUUM
57027     freePage(pPage, &rc);
57028     releasePage(pPage);
57029 #else
57030     if( pBt->autoVacuum ){
57031       Pgno maxRootPgno;
57032       sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
57033
57034       if( iTable==maxRootPgno ){
57035         /* If the table being dropped is the table with the largest root-page
57036         ** number in the database, put the root page on the free list. 
57037         */
57038         freePage(pPage, &rc);
57039         releasePage(pPage);
57040         if( rc!=SQLITE_OK ){
57041           return rc;
57042         }
57043       }else{
57044         /* The table being dropped does not have the largest root-page
57045         ** number in the database. So move the page that does into the 
57046         ** gap left by the deleted root-page.
57047         */
57048         MemPage *pMove;
57049         releasePage(pPage);
57050         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0, 0);
57051         if( rc!=SQLITE_OK ){
57052           return rc;
57053         }
57054         rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
57055         releasePage(pMove);
57056         if( rc!=SQLITE_OK ){
57057           return rc;
57058         }
57059         pMove = 0;
57060         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0, 0);
57061         freePage(pMove, &rc);
57062         releasePage(pMove);
57063         if( rc!=SQLITE_OK ){
57064           return rc;
57065         }
57066         *piMoved = maxRootPgno;
57067       }
57068
57069       /* Set the new 'max-root-page' value in the database header. This
57070       ** is the old value less one, less one more if that happens to
57071       ** be a root-page number, less one again if that is the
57072       ** PENDING_BYTE_PAGE.
57073       */
57074       maxRootPgno--;
57075       while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
57076              || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
57077         maxRootPgno--;
57078       }
57079       assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
57080
57081       rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
57082     }else{
57083       freePage(pPage, &rc);
57084       releasePage(pPage);
57085     }
57086 #endif
57087   }else{
57088     /* If sqlite3BtreeDropTable was called on page 1.
57089     ** This really never should happen except in a corrupt
57090     ** database. 
57091     */
57092     zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
57093     releasePage(pPage);
57094   }
57095   return rc;  
57096 }
57097 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
57098   int rc;
57099   sqlite3BtreeEnter(p);
57100   rc = btreeDropTable(p, iTable, piMoved);
57101   sqlite3BtreeLeave(p);
57102   return rc;
57103 }
57104
57105
57106 /*
57107 ** This function may only be called if the b-tree connection already
57108 ** has a read or write transaction open on the database.
57109 **
57110 ** Read the meta-information out of a database file.  Meta[0]
57111 ** is the number of free pages currently in the database.  Meta[1]
57112 ** through meta[15] are available for use by higher layers.  Meta[0]
57113 ** is read-only, the others are read/write.
57114 ** 
57115 ** The schema layer numbers meta values differently.  At the schema
57116 ** layer (and the SetCookie and ReadCookie opcodes) the number of
57117 ** free pages is not visible.  So Cookie[0] is the same as Meta[1].
57118 */
57119 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
57120   BtShared *pBt = p->pBt;
57121
57122   sqlite3BtreeEnter(p);
57123   assert( p->inTrans>TRANS_NONE );
57124   assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
57125   assert( pBt->pPage1 );
57126   assert( idx>=0 && idx<=15 );
57127
57128   *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
57129
57130   /* If auto-vacuum is disabled in this build and this is an auto-vacuum
57131   ** database, mark the database as read-only.  */
57132 #ifdef SQLITE_OMIT_AUTOVACUUM
57133   if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
57134     pBt->btsFlags |= BTS_READ_ONLY;
57135   }
57136 #endif
57137
57138   sqlite3BtreeLeave(p);
57139 }
57140
57141 /*
57142 ** Write meta-information back into the database.  Meta[0] is
57143 ** read-only and may not be written.
57144 */
57145 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
57146   BtShared *pBt = p->pBt;
57147   unsigned char *pP1;
57148   int rc;
57149   assert( idx>=1 && idx<=15 );
57150   sqlite3BtreeEnter(p);
57151   assert( p->inTrans==TRANS_WRITE );
57152   assert( pBt->pPage1!=0 );
57153   pP1 = pBt->pPage1->aData;
57154   rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
57155   if( rc==SQLITE_OK ){
57156     put4byte(&pP1[36 + idx*4], iMeta);
57157 #ifndef SQLITE_OMIT_AUTOVACUUM
57158     if( idx==BTREE_INCR_VACUUM ){
57159       assert( pBt->autoVacuum || iMeta==0 );
57160       assert( iMeta==0 || iMeta==1 );
57161       pBt->incrVacuum = (u8)iMeta;
57162     }
57163 #endif
57164   }
57165   sqlite3BtreeLeave(p);
57166   return rc;
57167 }
57168
57169 #ifndef SQLITE_OMIT_BTREECOUNT
57170 /*
57171 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
57172 ** number of entries in the b-tree and write the result to *pnEntry.
57173 **
57174 ** SQLITE_OK is returned if the operation is successfully executed. 
57175 ** Otherwise, if an error is encountered (i.e. an IO error or database
57176 ** corruption) an SQLite error code is returned.
57177 */
57178 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
57179   i64 nEntry = 0;                      /* Value to return in *pnEntry */
57180   int rc;                              /* Return code */
57181
57182   if( pCur->pgnoRoot==0 ){
57183     *pnEntry = 0;
57184     return SQLITE_OK;
57185   }
57186   rc = moveToRoot(pCur);
57187
57188   /* Unless an error occurs, the following loop runs one iteration for each
57189   ** page in the B-Tree structure (not including overflow pages). 
57190   */
57191   while( rc==SQLITE_OK ){
57192     int iIdx;                          /* Index of child node in parent */
57193     MemPage *pPage;                    /* Current page of the b-tree */
57194
57195     /* If this is a leaf page or the tree is not an int-key tree, then 
57196     ** this page contains countable entries. Increment the entry counter
57197     ** accordingly.
57198     */
57199     pPage = pCur->apPage[pCur->iPage];
57200     if( pPage->leaf || !pPage->intKey ){
57201       nEntry += pPage->nCell;
57202     }
57203
57204     /* pPage is a leaf node. This loop navigates the cursor so that it 
57205     ** points to the first interior cell that it points to the parent of
57206     ** the next page in the tree that has not yet been visited. The
57207     ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
57208     ** of the page, or to the number of cells in the page if the next page
57209     ** to visit is the right-child of its parent.
57210     **
57211     ** If all pages in the tree have been visited, return SQLITE_OK to the
57212     ** caller.
57213     */
57214     if( pPage->leaf ){
57215       do {
57216         if( pCur->iPage==0 ){
57217           /* All pages of the b-tree have been visited. Return successfully. */
57218           *pnEntry = nEntry;
57219           return SQLITE_OK;
57220         }
57221         moveToParent(pCur);
57222       }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
57223
57224       pCur->aiIdx[pCur->iPage]++;
57225       pPage = pCur->apPage[pCur->iPage];
57226     }
57227
57228     /* Descend to the child node of the cell that the cursor currently 
57229     ** points at. This is the right-child if (iIdx==pPage->nCell).
57230     */
57231     iIdx = pCur->aiIdx[pCur->iPage];
57232     if( iIdx==pPage->nCell ){
57233       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
57234     }else{
57235       rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
57236     }
57237   }
57238
57239   /* An error has occurred. Return an error code. */
57240   return rc;
57241 }
57242 #endif
57243
57244 /*
57245 ** Return the pager associated with a BTree.  This routine is used for
57246 ** testing and debugging only.
57247 */
57248 SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
57249   return p->pBt->pPager;
57250 }
57251
57252 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
57253 /*
57254 ** Append a message to the error message string.
57255 */
57256 static void checkAppendMsg(
57257   IntegrityCk *pCheck,
57258   char *zMsg1,
57259   const char *zFormat,
57260   ...
57261 ){
57262   va_list ap;
57263   if( !pCheck->mxErr ) return;
57264   pCheck->mxErr--;
57265   pCheck->nErr++;
57266   va_start(ap, zFormat);
57267   if( pCheck->errMsg.nChar ){
57268     sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
57269   }
57270   if( zMsg1 ){
57271     sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
57272   }
57273   sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
57274   va_end(ap);
57275   if( pCheck->errMsg.mallocFailed ){
57276     pCheck->mallocFailed = 1;
57277   }
57278 }
57279 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
57280
57281 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
57282
57283 /*
57284 ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
57285 ** corresponds to page iPg is already set.
57286 */
57287 static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
57288   assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
57289   return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
57290 }
57291
57292 /*
57293 ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
57294 */
57295 static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
57296   assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
57297   pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
57298 }
57299
57300
57301 /*
57302 ** Add 1 to the reference count for page iPage.  If this is the second
57303 ** reference to the page, add an error message to pCheck->zErrMsg.
57304 ** Return 1 if there are 2 ore more references to the page and 0 if
57305 ** if this is the first reference to the page.
57306 **
57307 ** Also check that the page number is in bounds.
57308 */
57309 static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
57310   if( iPage==0 ) return 1;
57311   if( iPage>pCheck->nPage ){
57312     checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
57313     return 1;
57314   }
57315   if( getPageReferenced(pCheck, iPage) ){
57316     checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
57317     return 1;
57318   }
57319   setPageReferenced(pCheck, iPage);
57320   return 0;
57321 }
57322
57323 #ifndef SQLITE_OMIT_AUTOVACUUM
57324 /*
57325 ** Check that the entry in the pointer-map for page iChild maps to 
57326 ** page iParent, pointer type ptrType. If not, append an error message
57327 ** to pCheck.
57328 */
57329 static void checkPtrmap(
57330   IntegrityCk *pCheck,   /* Integrity check context */
57331   Pgno iChild,           /* Child page number */
57332   u8 eType,              /* Expected pointer map type */
57333   Pgno iParent,          /* Expected pointer map parent page number */
57334   char *zContext         /* Context description (used for error msg) */
57335 ){
57336   int rc;
57337   u8 ePtrmapType;
57338   Pgno iPtrmapParent;
57339
57340   rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
57341   if( rc!=SQLITE_OK ){
57342     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
57343     checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
57344     return;
57345   }
57346
57347   if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
57348     checkAppendMsg(pCheck, zContext, 
57349       "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)", 
57350       iChild, eType, iParent, ePtrmapType, iPtrmapParent);
57351   }
57352 }
57353 #endif
57354
57355 /*
57356 ** Check the integrity of the freelist or of an overflow page list.
57357 ** Verify that the number of pages on the list is N.
57358 */
57359 static void checkList(
57360   IntegrityCk *pCheck,  /* Integrity checking context */
57361   int isFreeList,       /* True for a freelist.  False for overflow page list */
57362   int iPage,            /* Page number for first page in the list */
57363   int N,                /* Expected number of pages in the list */
57364   char *zContext        /* Context for error messages */
57365 ){
57366   int i;
57367   int expected = N;
57368   int iFirst = iPage;
57369   while( N-- > 0 && pCheck->mxErr ){
57370     DbPage *pOvflPage;
57371     unsigned char *pOvflData;
57372     if( iPage<1 ){
57373       checkAppendMsg(pCheck, zContext,
57374          "%d of %d pages missing from overflow list starting at %d",
57375           N+1, expected, iFirst);
57376       break;
57377     }
57378     if( checkRef(pCheck, iPage, zContext) ) break;
57379     if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
57380       checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
57381       break;
57382     }
57383     pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
57384     if( isFreeList ){
57385       int n = get4byte(&pOvflData[4]);
57386 #ifndef SQLITE_OMIT_AUTOVACUUM
57387       if( pCheck->pBt->autoVacuum ){
57388         checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
57389       }
57390 #endif
57391       if( n>(int)pCheck->pBt->usableSize/4-2 ){
57392         checkAppendMsg(pCheck, zContext,
57393            "freelist leaf count too big on page %d", iPage);
57394         N--;
57395       }else{
57396         for(i=0; i<n; i++){
57397           Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
57398 #ifndef SQLITE_OMIT_AUTOVACUUM
57399           if( pCheck->pBt->autoVacuum ){
57400             checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
57401           }
57402 #endif
57403           checkRef(pCheck, iFreePage, zContext);
57404         }
57405         N -= n;
57406       }
57407     }
57408 #ifndef SQLITE_OMIT_AUTOVACUUM
57409     else{
57410       /* If this database supports auto-vacuum and iPage is not the last
57411       ** page in this overflow list, check that the pointer-map entry for
57412       ** the following page matches iPage.
57413       */
57414       if( pCheck->pBt->autoVacuum && N>0 ){
57415         i = get4byte(pOvflData);
57416         checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
57417       }
57418     }
57419 #endif
57420     iPage = get4byte(pOvflData);
57421     sqlite3PagerUnref(pOvflPage);
57422   }
57423 }
57424 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
57425
57426 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
57427 /*
57428 ** Do various sanity checks on a single page of a tree.  Return
57429 ** the tree depth.  Root pages return 0.  Parents of root pages
57430 ** return 1, and so forth.
57431 ** 
57432 ** These checks are done:
57433 **
57434 **      1.  Make sure that cells and freeblocks do not overlap
57435 **          but combine to completely cover the page.
57436 **  NO  2.  Make sure cell keys are in order.
57437 **  NO  3.  Make sure no key is less than or equal to zLowerBound.
57438 **  NO  4.  Make sure no key is greater than or equal to zUpperBound.
57439 **      5.  Check the integrity of overflow pages.
57440 **      6.  Recursively call checkTreePage on all children.
57441 **      7.  Verify that the depth of all children is the same.
57442 **      8.  Make sure this page is at least 33% full or else it is
57443 **          the root of the tree.
57444 */
57445 static int checkTreePage(
57446   IntegrityCk *pCheck,  /* Context for the sanity check */
57447   int iPage,            /* Page number of the page to check */
57448   char *zParentContext, /* Parent context */
57449   i64 *pnParentMinKey, 
57450   i64 *pnParentMaxKey
57451 ){
57452   MemPage *pPage;
57453   int i, rc, depth, d2, pgno, cnt;
57454   int hdr, cellStart;
57455   int nCell;
57456   u8 *data;
57457   BtShared *pBt;
57458   int usableSize;
57459   char zContext[100];
57460   char *hit = 0;
57461   i64 nMinKey = 0;
57462   i64 nMaxKey = 0;
57463
57464   sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
57465
57466   /* Check that the page exists
57467   */
57468   pBt = pCheck->pBt;
57469   usableSize = pBt->usableSize;
57470   if( iPage==0 ) return 0;
57471   if( checkRef(pCheck, iPage, zParentContext) ) return 0;
57472   if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0, 0))!=0 ){
57473     checkAppendMsg(pCheck, zContext,
57474        "unable to get the page. error code=%d", rc);
57475     return 0;
57476   }
57477
57478   /* Clear MemPage.isInit to make sure the corruption detection code in
57479   ** btreeInitPage() is executed.  */
57480   pPage->isInit = 0;
57481   if( (rc = btreeInitPage(pPage))!=0 ){
57482     assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
57483     checkAppendMsg(pCheck, zContext, 
57484                    "btreeInitPage() returns error code %d", rc);
57485     releasePage(pPage);
57486     return 0;
57487   }
57488
57489   /* Check out all the cells.
57490   */
57491   depth = 0;
57492   for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
57493     u8 *pCell;
57494     u32 sz;
57495     CellInfo info;
57496
57497     /* Check payload overflow pages
57498     */
57499     sqlite3_snprintf(sizeof(zContext), zContext,
57500              "On tree page %d cell %d: ", iPage, i);
57501     pCell = findCell(pPage,i);
57502     btreeParseCellPtr(pPage, pCell, &info);
57503     sz = info.nData;
57504     if( !pPage->intKey ) sz += (int)info.nKey;
57505     /* For intKey pages, check that the keys are in order.
57506     */
57507     else if( i==0 ) nMinKey = nMaxKey = info.nKey;
57508     else{
57509       if( info.nKey <= nMaxKey ){
57510         checkAppendMsg(pCheck, zContext, 
57511             "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
57512       }
57513       nMaxKey = info.nKey;
57514     }
57515     assert( sz==info.nPayload );
57516     if( (sz>info.nLocal) 
57517      && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
57518     ){
57519       int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
57520       Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
57521 #ifndef SQLITE_OMIT_AUTOVACUUM
57522       if( pBt->autoVacuum ){
57523         checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
57524       }
57525 #endif
57526       checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
57527     }
57528
57529     /* Check sanity of left child page.
57530     */
57531     if( !pPage->leaf ){
57532       pgno = get4byte(pCell);
57533 #ifndef SQLITE_OMIT_AUTOVACUUM
57534       if( pBt->autoVacuum ){
57535         checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
57536       }
57537 #endif
57538       d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
57539       if( i>0 && d2!=depth ){
57540         checkAppendMsg(pCheck, zContext, "Child page depth differs");
57541       }
57542       depth = d2;
57543     }
57544   }
57545
57546   if( !pPage->leaf ){
57547     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
57548     sqlite3_snprintf(sizeof(zContext), zContext, 
57549                      "On page %d at right child: ", iPage);
57550 #ifndef SQLITE_OMIT_AUTOVACUUM
57551     if( pBt->autoVacuum ){
57552       checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
57553     }
57554 #endif
57555     checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
57556   }
57557  
57558   /* For intKey leaf pages, check that the min/max keys are in order
57559   ** with any left/parent/right pages.
57560   */
57561   if( pPage->leaf && pPage->intKey ){
57562     /* if we are a left child page */
57563     if( pnParentMinKey ){
57564       /* if we are the left most child page */
57565       if( !pnParentMaxKey ){
57566         if( nMaxKey > *pnParentMinKey ){
57567           checkAppendMsg(pCheck, zContext, 
57568               "Rowid %lld out of order (max larger than parent min of %lld)",
57569               nMaxKey, *pnParentMinKey);
57570         }
57571       }else{
57572         if( nMinKey <= *pnParentMinKey ){
57573           checkAppendMsg(pCheck, zContext, 
57574               "Rowid %lld out of order (min less than parent min of %lld)",
57575               nMinKey, *pnParentMinKey);
57576         }
57577         if( nMaxKey > *pnParentMaxKey ){
57578           checkAppendMsg(pCheck, zContext, 
57579               "Rowid %lld out of order (max larger than parent max of %lld)",
57580               nMaxKey, *pnParentMaxKey);
57581         }
57582         *pnParentMinKey = nMaxKey;
57583       }
57584     /* else if we're a right child page */
57585     } else if( pnParentMaxKey ){
57586       if( nMinKey <= *pnParentMaxKey ){
57587         checkAppendMsg(pCheck, zContext, 
57588             "Rowid %lld out of order (min less than parent max of %lld)",
57589             nMinKey, *pnParentMaxKey);
57590       }
57591     }
57592   }
57593
57594   /* Check for complete coverage of the page
57595   */
57596   data = pPage->aData;
57597   hdr = pPage->hdrOffset;
57598   hit = sqlite3PageMalloc( pBt->pageSize );
57599   if( hit==0 ){
57600     pCheck->mallocFailed = 1;
57601   }else{
57602     int contentOffset = get2byteNotZero(&data[hdr+5]);
57603     assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
57604     memset(hit+contentOffset, 0, usableSize-contentOffset);
57605     memset(hit, 1, contentOffset);
57606     nCell = get2byte(&data[hdr+3]);
57607     cellStart = hdr + 12 - 4*pPage->leaf;
57608     for(i=0; i<nCell; i++){
57609       int pc = get2byte(&data[cellStart+i*2]);
57610       u32 size = 65536;
57611       int j;
57612       if( pc<=usableSize-4 ){
57613         size = cellSizePtr(pPage, &data[pc]);
57614       }
57615       if( (int)(pc+size-1)>=usableSize ){
57616         checkAppendMsg(pCheck, 0, 
57617             "Corruption detected in cell %d on page %d",i,iPage);
57618       }else{
57619         for(j=pc+size-1; j>=pc; j--) hit[j]++;
57620       }
57621     }
57622     i = get2byte(&data[hdr+1]);
57623     while( i>0 ){
57624       int size, j;
57625       assert( i<=usableSize-4 );     /* Enforced by btreeInitPage() */
57626       size = get2byte(&data[i+2]);
57627       assert( i+size<=usableSize );  /* Enforced by btreeInitPage() */
57628       for(j=i+size-1; j>=i; j--) hit[j]++;
57629       j = get2byte(&data[i]);
57630       assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
57631       assert( j<=usableSize-4 );   /* Enforced by btreeInitPage() */
57632       i = j;
57633     }
57634     for(i=cnt=0; i<usableSize; i++){
57635       if( hit[i]==0 ){
57636         cnt++;
57637       }else if( hit[i]>1 ){
57638         checkAppendMsg(pCheck, 0,
57639           "Multiple uses for byte %d of page %d", i, iPage);
57640         break;
57641       }
57642     }
57643     if( cnt!=data[hdr+7] ){
57644       checkAppendMsg(pCheck, 0, 
57645           "Fragmentation of %d bytes reported as %d on page %d",
57646           cnt, data[hdr+7], iPage);
57647     }
57648   }
57649   sqlite3PageFree(hit);
57650   releasePage(pPage);
57651   return depth+1;
57652 }
57653 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
57654
57655 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
57656 /*
57657 ** This routine does a complete check of the given BTree file.  aRoot[] is
57658 ** an array of pages numbers were each page number is the root page of
57659 ** a table.  nRoot is the number of entries in aRoot.
57660 **
57661 ** A read-only or read-write transaction must be opened before calling
57662 ** this function.
57663 **
57664 ** Write the number of error seen in *pnErr.  Except for some memory
57665 ** allocation errors,  an error message held in memory obtained from
57666 ** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
57667 ** returned.  If a memory allocation error occurs, NULL is returned.
57668 */
57669 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
57670   Btree *p,     /* The btree to be checked */
57671   int *aRoot,   /* An array of root pages numbers for individual trees */
57672   int nRoot,    /* Number of entries in aRoot[] */
57673   int mxErr,    /* Stop reporting errors after this many */
57674   int *pnErr    /* Write number of errors seen to this variable */
57675 ){
57676   Pgno i;
57677   int nRef;
57678   IntegrityCk sCheck;
57679   BtShared *pBt = p->pBt;
57680   char zErr[100];
57681
57682   sqlite3BtreeEnter(p);
57683   assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
57684   nRef = sqlite3PagerRefcount(pBt->pPager);
57685   sCheck.pBt = pBt;
57686   sCheck.pPager = pBt->pPager;
57687   sCheck.nPage = btreePagecount(sCheck.pBt);
57688   sCheck.mxErr = mxErr;
57689   sCheck.nErr = 0;
57690   sCheck.mallocFailed = 0;
57691   *pnErr = 0;
57692   if( sCheck.nPage==0 ){
57693     sqlite3BtreeLeave(p);
57694     return 0;
57695   }
57696
57697   sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
57698   if( !sCheck.aPgRef ){
57699     *pnErr = 1;
57700     sqlite3BtreeLeave(p);
57701     return 0;
57702   }
57703   i = PENDING_BYTE_PAGE(pBt);
57704   if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
57705   sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
57706   sCheck.errMsg.useMalloc = 2;
57707
57708   /* Check the integrity of the freelist
57709   */
57710   checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
57711             get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
57712
57713   /* Check all the tables.
57714   */
57715   for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
57716     if( aRoot[i]==0 ) continue;
57717 #ifndef SQLITE_OMIT_AUTOVACUUM
57718     if( pBt->autoVacuum && aRoot[i]>1 ){
57719       checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
57720     }
57721 #endif
57722     checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
57723   }
57724
57725   /* Make sure every page in the file is referenced
57726   */
57727   for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
57728 #ifdef SQLITE_OMIT_AUTOVACUUM
57729     if( getPageReferenced(&sCheck, i)==0 ){
57730       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
57731     }
57732 #else
57733     /* If the database supports auto-vacuum, make sure no tables contain
57734     ** references to pointer-map pages.
57735     */
57736     if( getPageReferenced(&sCheck, i)==0 && 
57737        (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
57738       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
57739     }
57740     if( getPageReferenced(&sCheck, i)!=0 && 
57741        (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
57742       checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
57743     }
57744 #endif
57745   }
57746
57747   /* Make sure this analysis did not leave any unref() pages.
57748   ** This is an internal consistency check; an integrity check
57749   ** of the integrity check.
57750   */
57751   if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
57752     checkAppendMsg(&sCheck, 0, 
57753       "Outstanding page count goes from %d to %d during this analysis",
57754       nRef, sqlite3PagerRefcount(pBt->pPager)
57755     );
57756   }
57757
57758   /* Clean  up and report errors.
57759   */
57760   sqlite3BtreeLeave(p);
57761   sqlite3_free(sCheck.aPgRef);
57762   if( sCheck.mallocFailed ){
57763     sqlite3StrAccumReset(&sCheck.errMsg);
57764     *pnErr = sCheck.nErr+1;
57765     return 0;
57766   }
57767   *pnErr = sCheck.nErr;
57768   if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
57769   return sqlite3StrAccumFinish(&sCheck.errMsg);
57770 }
57771 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
57772
57773 /*
57774 ** Return the full pathname of the underlying database file.  Return
57775 ** an empty string if the database is in-memory or a TEMP database.
57776 **
57777 ** The pager filename is invariant as long as the pager is
57778 ** open so it is safe to access without the BtShared mutex.
57779 */
57780 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
57781   assert( p->pBt->pPager!=0 );
57782   return sqlite3PagerFilename(p->pBt->pPager, 1);
57783 }
57784
57785 /*
57786 ** Return the pathname of the journal file for this database. The return
57787 ** value of this routine is the same regardless of whether the journal file
57788 ** has been created or not.
57789 **
57790 ** The pager journal filename is invariant as long as the pager is
57791 ** open so it is safe to access without the BtShared mutex.
57792 */
57793 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
57794   assert( p->pBt->pPager!=0 );
57795   return sqlite3PagerJournalname(p->pBt->pPager);
57796 }
57797
57798 /*
57799 ** Return non-zero if a transaction is active.
57800 */
57801 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
57802   assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
57803   return (p && (p->inTrans==TRANS_WRITE));
57804 }
57805
57806 #ifndef SQLITE_OMIT_WAL
57807 /*
57808 ** Run a checkpoint on the Btree passed as the first argument.
57809 **
57810 ** Return SQLITE_LOCKED if this or any other connection has an open 
57811 ** transaction on the shared-cache the argument Btree is connected to.
57812 **
57813 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
57814 */
57815 SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
57816   int rc = SQLITE_OK;
57817   if( p ){
57818     BtShared *pBt = p->pBt;
57819     sqlite3BtreeEnter(p);
57820     if( pBt->inTransaction!=TRANS_NONE ){
57821       rc = SQLITE_LOCKED;
57822     }else{
57823       rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
57824     }
57825     sqlite3BtreeLeave(p);
57826   }
57827   return rc;
57828 }
57829 #endif
57830
57831 /*
57832 ** Return non-zero if a read (or write) transaction is active.
57833 */
57834 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
57835   assert( p );
57836   assert( sqlite3_mutex_held(p->db->mutex) );
57837   return p->inTrans!=TRANS_NONE;
57838 }
57839
57840 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
57841   assert( p );
57842   assert( sqlite3_mutex_held(p->db->mutex) );
57843   return p->nBackup!=0;
57844 }
57845
57846 /*
57847 ** This function returns a pointer to a blob of memory associated with
57848 ** a single shared-btree. The memory is used by client code for its own
57849 ** purposes (for example, to store a high-level schema associated with 
57850 ** the shared-btree). The btree layer manages reference counting issues.
57851 **
57852 ** The first time this is called on a shared-btree, nBytes bytes of memory
57853 ** are allocated, zeroed, and returned to the caller. For each subsequent 
57854 ** call the nBytes parameter is ignored and a pointer to the same blob
57855 ** of memory returned. 
57856 **
57857 ** If the nBytes parameter is 0 and the blob of memory has not yet been
57858 ** allocated, a null pointer is returned. If the blob has already been
57859 ** allocated, it is returned as normal.
57860 **
57861 ** Just before the shared-btree is closed, the function passed as the 
57862 ** xFree argument when the memory allocation was made is invoked on the 
57863 ** blob of allocated memory. The xFree function should not call sqlite3_free()
57864 ** on the memory, the btree layer does that.
57865 */
57866 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
57867   BtShared *pBt = p->pBt;
57868   sqlite3BtreeEnter(p);
57869   if( !pBt->pSchema && nBytes ){
57870     pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
57871     pBt->xFreeSchema = xFree;
57872   }
57873   sqlite3BtreeLeave(p);
57874   return pBt->pSchema;
57875 }
57876
57877 /*
57878 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared 
57879 ** btree as the argument handle holds an exclusive lock on the 
57880 ** sqlite_master table. Otherwise SQLITE_OK.
57881 */
57882 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
57883   int rc;
57884   assert( sqlite3_mutex_held(p->db->mutex) );
57885   sqlite3BtreeEnter(p);
57886   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
57887   assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
57888   sqlite3BtreeLeave(p);
57889   return rc;
57890 }
57891
57892
57893 #ifndef SQLITE_OMIT_SHARED_CACHE
57894 /*
57895 ** Obtain a lock on the table whose root page is iTab.  The
57896 ** lock is a write lock if isWritelock is true or a read lock
57897 ** if it is false.
57898 */
57899 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
57900   int rc = SQLITE_OK;
57901   assert( p->inTrans!=TRANS_NONE );
57902   if( p->sharable ){
57903     u8 lockType = READ_LOCK + isWriteLock;
57904     assert( READ_LOCK+1==WRITE_LOCK );
57905     assert( isWriteLock==0 || isWriteLock==1 );
57906
57907     sqlite3BtreeEnter(p);
57908     rc = querySharedCacheTableLock(p, iTab, lockType);
57909     if( rc==SQLITE_OK ){
57910       rc = setSharedCacheTableLock(p, iTab, lockType);
57911     }
57912     sqlite3BtreeLeave(p);
57913   }
57914   return rc;
57915 }
57916 #endif
57917
57918 #ifndef SQLITE_OMIT_INCRBLOB
57919 /*
57920 ** Argument pCsr must be a cursor opened for writing on an 
57921 ** INTKEY table currently pointing at a valid table entry. 
57922 ** This function modifies the data stored as part of that entry.
57923 **
57924 ** Only the data content may only be modified, it is not possible to 
57925 ** change the length of the data stored. If this function is called with
57926 ** parameters that attempt to write past the end of the existing data,
57927 ** no modifications are made and SQLITE_CORRUPT is returned.
57928 */
57929 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
57930   int rc;
57931   assert( cursorHoldsMutex(pCsr) );
57932   assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
57933   assert( pCsr->isIncrblobHandle );
57934
57935   rc = restoreCursorPosition(pCsr);
57936   if( rc!=SQLITE_OK ){
57937     return rc;
57938   }
57939   assert( pCsr->eState!=CURSOR_REQUIRESEEK );
57940   if( pCsr->eState!=CURSOR_VALID ){
57941     return SQLITE_ABORT;
57942   }
57943
57944   /* Save the positions of all other cursors open on this table. This is
57945   ** required in case any of them are holding references to an xFetch
57946   ** version of the b-tree page modified by the accessPayload call below.
57947   **
57948   ** Note that pCsr must be open on a BTREE_INTKEY table and saveCursorPosition()
57949   ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
57950   ** saveAllCursors can only return SQLITE_OK.
57951   */
57952   VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
57953   assert( rc==SQLITE_OK );
57954
57955   /* Check some assumptions: 
57956   **   (a) the cursor is open for writing,
57957   **   (b) there is a read/write transaction open,
57958   **   (c) the connection holds a write-lock on the table (if required),
57959   **   (d) there are no conflicting read-locks, and
57960   **   (e) the cursor points at a valid row of an intKey table.
57961   */
57962   if( !pCsr->wrFlag ){
57963     return SQLITE_READONLY;
57964   }
57965   assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
57966               && pCsr->pBt->inTransaction==TRANS_WRITE );
57967   assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
57968   assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
57969   assert( pCsr->apPage[pCsr->iPage]->intKey );
57970
57971   return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
57972 }
57973
57974 /* 
57975 ** Set a flag on this cursor to cache the locations of pages from the 
57976 ** overflow list for the current row. This is used by cursors opened
57977 ** for incremental blob IO only.
57978 **
57979 ** This function sets a flag only. The actual page location cache
57980 ** (stored in BtCursor.aOverflow[]) is allocated and used by function
57981 ** accessPayload() (the worker function for sqlite3BtreeData() and
57982 ** sqlite3BtreePutData()).
57983 */
57984 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
57985   assert( cursorHoldsMutex(pCur) );
57986   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
57987   invalidateOverflowCache(pCur);
57988   pCur->isIncrblobHandle = 1;
57989 }
57990 #endif
57991
57992 /*
57993 ** Set both the "read version" (single byte at byte offset 18) and 
57994 ** "write version" (single byte at byte offset 19) fields in the database
57995 ** header to iVersion.
57996 */
57997 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
57998   BtShared *pBt = pBtree->pBt;
57999   int rc;                         /* Return code */
58000  
58001   assert( iVersion==1 || iVersion==2 );
58002
58003   /* If setting the version fields to 1, do not automatically open the
58004   ** WAL connection, even if the version fields are currently set to 2.
58005   */
58006   pBt->btsFlags &= ~BTS_NO_WAL;
58007   if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
58008
58009   rc = sqlite3BtreeBeginTrans(pBtree, 0);
58010   if( rc==SQLITE_OK ){
58011     u8 *aData = pBt->pPage1->aData;
58012     if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
58013       rc = sqlite3BtreeBeginTrans(pBtree, 2);
58014       if( rc==SQLITE_OK ){
58015         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
58016         if( rc==SQLITE_OK ){
58017           aData[18] = (u8)iVersion;
58018           aData[19] = (u8)iVersion;
58019         }
58020       }
58021     }
58022   }
58023
58024   pBt->btsFlags &= ~BTS_NO_WAL;
58025   return rc;
58026 }
58027
58028 /*
58029 ** set the mask of hint flags for cursor pCsr. Currently the only valid
58030 ** values are 0 and BTREE_BULKLOAD.
58031 */
58032 SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *pCsr, unsigned int mask){
58033   assert( mask==BTREE_BULKLOAD || mask==0 );
58034   pCsr->hints = mask;
58035 }
58036
58037 /************** End of btree.c ***********************************************/
58038 /************** Begin file backup.c ******************************************/
58039 /*
58040 ** 2009 January 28
58041 **
58042 ** The author disclaims copyright to this source code.  In place of
58043 ** a legal notice, here is a blessing:
58044 **
58045 **    May you do good and not evil.
58046 **    May you find forgiveness for yourself and forgive others.
58047 **    May you share freely, never taking more than you give.
58048 **
58049 *************************************************************************
58050 ** This file contains the implementation of the sqlite3_backup_XXX() 
58051 ** API functions and the related features.
58052 */
58053
58054 /* Macro to find the minimum of two numeric values.
58055 */
58056 #ifndef MIN
58057 # define MIN(x,y) ((x)<(y)?(x):(y))
58058 #endif
58059
58060 /*
58061 ** Structure allocated for each backup operation.
58062 */
58063 struct sqlite3_backup {
58064   sqlite3* pDestDb;        /* Destination database handle */
58065   Btree *pDest;            /* Destination b-tree file */
58066   u32 iDestSchema;         /* Original schema cookie in destination */
58067   int bDestLocked;         /* True once a write-transaction is open on pDest */
58068
58069   Pgno iNext;              /* Page number of the next source page to copy */
58070   sqlite3* pSrcDb;         /* Source database handle */
58071   Btree *pSrc;             /* Source b-tree file */
58072
58073   int rc;                  /* Backup process error code */
58074
58075   /* These two variables are set by every call to backup_step(). They are
58076   ** read by calls to backup_remaining() and backup_pagecount().
58077   */
58078   Pgno nRemaining;         /* Number of pages left to copy */
58079   Pgno nPagecount;         /* Total number of pages to copy */
58080
58081   int isAttached;          /* True once backup has been registered with pager */
58082   sqlite3_backup *pNext;   /* Next backup associated with source pager */
58083 };
58084
58085 /*
58086 ** THREAD SAFETY NOTES:
58087 **
58088 **   Once it has been created using backup_init(), a single sqlite3_backup
58089 **   structure may be accessed via two groups of thread-safe entry points:
58090 **
58091 **     * Via the sqlite3_backup_XXX() API function backup_step() and 
58092 **       backup_finish(). Both these functions obtain the source database
58093 **       handle mutex and the mutex associated with the source BtShared 
58094 **       structure, in that order.
58095 **
58096 **     * Via the BackupUpdate() and BackupRestart() functions, which are
58097 **       invoked by the pager layer to report various state changes in
58098 **       the page cache associated with the source database. The mutex
58099 **       associated with the source database BtShared structure will always 
58100 **       be held when either of these functions are invoked.
58101 **
58102 **   The other sqlite3_backup_XXX() API functions, backup_remaining() and
58103 **   backup_pagecount() are not thread-safe functions. If they are called
58104 **   while some other thread is calling backup_step() or backup_finish(),
58105 **   the values returned may be invalid. There is no way for a call to
58106 **   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
58107 **   or backup_pagecount().
58108 **
58109 **   Depending on the SQLite configuration, the database handles and/or
58110 **   the Btree objects may have their own mutexes that require locking.
58111 **   Non-sharable Btrees (in-memory databases for example), do not have
58112 **   associated mutexes.
58113 */
58114
58115 /*
58116 ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
58117 ** in connection handle pDb. If such a database cannot be found, return
58118 ** a NULL pointer and write an error message to pErrorDb.
58119 **
58120 ** If the "temp" database is requested, it may need to be opened by this 
58121 ** function. If an error occurs while doing so, return 0 and write an 
58122 ** error message to pErrorDb.
58123 */
58124 static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
58125   int i = sqlite3FindDbName(pDb, zDb);
58126
58127   if( i==1 ){
58128     Parse *pParse;
58129     int rc = 0;
58130     pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
58131     if( pParse==0 ){
58132       sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
58133       rc = SQLITE_NOMEM;
58134     }else{
58135       pParse->db = pDb;
58136       if( sqlite3OpenTempDatabase(pParse) ){
58137         sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
58138         rc = SQLITE_ERROR;
58139       }
58140       sqlite3DbFree(pErrorDb, pParse->zErrMsg);
58141       sqlite3StackFree(pErrorDb, pParse);
58142     }
58143     if( rc ){
58144       return 0;
58145     }
58146   }
58147
58148   if( i<0 ){
58149     sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
58150     return 0;
58151   }
58152
58153   return pDb->aDb[i].pBt;
58154 }
58155
58156 /*
58157 ** Attempt to set the page size of the destination to match the page size
58158 ** of the source.
58159 */
58160 static int setDestPgsz(sqlite3_backup *p){
58161   int rc;
58162   rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
58163   return rc;
58164 }
58165
58166 /*
58167 ** Create an sqlite3_backup process to copy the contents of zSrcDb from
58168 ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
58169 ** a pointer to the new sqlite3_backup object.
58170 **
58171 ** If an error occurs, NULL is returned and an error code and error message
58172 ** stored in database handle pDestDb.
58173 */
58174 SQLITE_API sqlite3_backup *sqlite3_backup_init(
58175   sqlite3* pDestDb,                     /* Database to write to */
58176   const char *zDestDb,                  /* Name of database within pDestDb */
58177   sqlite3* pSrcDb,                      /* Database connection to read from */
58178   const char *zSrcDb                    /* Name of database within pSrcDb */
58179 ){
58180   sqlite3_backup *p;                    /* Value to return */
58181
58182   /* Lock the source database handle. The destination database
58183   ** handle is not locked in this routine, but it is locked in
58184   ** sqlite3_backup_step(). The user is required to ensure that no
58185   ** other thread accesses the destination handle for the duration
58186   ** of the backup operation.  Any attempt to use the destination
58187   ** database connection while a backup is in progress may cause
58188   ** a malfunction or a deadlock.
58189   */
58190   sqlite3_mutex_enter(pSrcDb->mutex);
58191   sqlite3_mutex_enter(pDestDb->mutex);
58192
58193   if( pSrcDb==pDestDb ){
58194     sqlite3Error(
58195         pDestDb, SQLITE_ERROR, "source and destination must be distinct"
58196     );
58197     p = 0;
58198   }else {
58199     /* Allocate space for a new sqlite3_backup object...
58200     ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
58201     ** call to sqlite3_backup_init() and is destroyed by a call to
58202     ** sqlite3_backup_finish(). */
58203     p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
58204     if( !p ){
58205       sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
58206     }
58207   }
58208
58209   /* If the allocation succeeded, populate the new object. */
58210   if( p ){
58211     p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
58212     p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
58213     p->pDestDb = pDestDb;
58214     p->pSrcDb = pSrcDb;
58215     p->iNext = 1;
58216     p->isAttached = 0;
58217
58218     if( 0==p->pSrc || 0==p->pDest || setDestPgsz(p)==SQLITE_NOMEM ){
58219       /* One (or both) of the named databases did not exist or an OOM
58220       ** error was hit.  The error has already been written into the
58221       ** pDestDb handle.  All that is left to do here is free the
58222       ** sqlite3_backup structure.
58223       */
58224       sqlite3_free(p);
58225       p = 0;
58226     }
58227   }
58228   if( p ){
58229     p->pSrc->nBackup++;
58230   }
58231
58232   sqlite3_mutex_leave(pDestDb->mutex);
58233   sqlite3_mutex_leave(pSrcDb->mutex);
58234   return p;
58235 }
58236
58237 /*
58238 ** Argument rc is an SQLite error code. Return true if this error is 
58239 ** considered fatal if encountered during a backup operation. All errors
58240 ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
58241 */
58242 static int isFatalError(int rc){
58243   return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
58244 }
58245
58246 /*
58247 ** Parameter zSrcData points to a buffer containing the data for 
58248 ** page iSrcPg from the source database. Copy this data into the 
58249 ** destination database.
58250 */
58251 static int backupOnePage(
58252   sqlite3_backup *p,              /* Backup handle */
58253   Pgno iSrcPg,                    /* Source database page to backup */
58254   const u8 *zSrcData,             /* Source database page data */
58255   int bUpdate                     /* True for an update, false otherwise */
58256 ){
58257   Pager * const pDestPager = sqlite3BtreePager(p->pDest);
58258   const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
58259   int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
58260   const int nCopy = MIN(nSrcPgsz, nDestPgsz);
58261   const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
58262 #ifdef SQLITE_HAS_CODEC
58263   /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
58264   ** guaranteed that the shared-mutex is held by this thread, handle
58265   ** p->pSrc may not actually be the owner.  */
58266   int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
58267   int nDestReserve = sqlite3BtreeGetReserve(p->pDest);
58268 #endif
58269   int rc = SQLITE_OK;
58270   i64 iOff;
58271
58272   assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
58273   assert( p->bDestLocked );
58274   assert( !isFatalError(p->rc) );
58275   assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
58276   assert( zSrcData );
58277
58278   /* Catch the case where the destination is an in-memory database and the
58279   ** page sizes of the source and destination differ. 
58280   */
58281   if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
58282     rc = SQLITE_READONLY;
58283   }
58284
58285 #ifdef SQLITE_HAS_CODEC
58286   /* Backup is not possible if the page size of the destination is changing
58287   ** and a codec is in use.
58288   */
58289   if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
58290     rc = SQLITE_READONLY;
58291   }
58292
58293   /* Backup is not possible if the number of bytes of reserve space differ
58294   ** between source and destination.  If there is a difference, try to
58295   ** fix the destination to agree with the source.  If that is not possible,
58296   ** then the backup cannot proceed.
58297   */
58298   if( nSrcReserve!=nDestReserve ){
58299     u32 newPgsz = nSrcPgsz;
58300     rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
58301     if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
58302   }
58303 #endif
58304
58305   /* This loop runs once for each destination page spanned by the source 
58306   ** page. For each iteration, variable iOff is set to the byte offset
58307   ** of the destination page.
58308   */
58309   for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
58310     DbPage *pDestPg = 0;
58311     Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
58312     if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
58313     if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
58314      && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
58315     ){
58316       const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
58317       u8 *zDestData = sqlite3PagerGetData(pDestPg);
58318       u8 *zOut = &zDestData[iOff%nDestPgsz];
58319
58320       /* Copy the data from the source page into the destination page.
58321       ** Then clear the Btree layer MemPage.isInit flag. Both this module
58322       ** and the pager code use this trick (clearing the first byte
58323       ** of the page 'extra' space to invalidate the Btree layers
58324       ** cached parse of the page). MemPage.isInit is marked 
58325       ** "MUST BE FIRST" for this purpose.
58326       */
58327       memcpy(zOut, zIn, nCopy);
58328       ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
58329       if( iOff==0 && bUpdate==0 ){
58330         sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
58331       }
58332     }
58333     sqlite3PagerUnref(pDestPg);
58334   }
58335
58336   return rc;
58337 }
58338
58339 /*
58340 ** If pFile is currently larger than iSize bytes, then truncate it to
58341 ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
58342 ** this function is a no-op.
58343 **
58344 ** Return SQLITE_OK if everything is successful, or an SQLite error 
58345 ** code if an error occurs.
58346 */
58347 static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
58348   i64 iCurrent;
58349   int rc = sqlite3OsFileSize(pFile, &iCurrent);
58350   if( rc==SQLITE_OK && iCurrent>iSize ){
58351     rc = sqlite3OsTruncate(pFile, iSize);
58352   }
58353   return rc;
58354 }
58355
58356 /*
58357 ** Register this backup object with the associated source pager for
58358 ** callbacks when pages are changed or the cache invalidated.
58359 */
58360 static void attachBackupObject(sqlite3_backup *p){
58361   sqlite3_backup **pp;
58362   assert( sqlite3BtreeHoldsMutex(p->pSrc) );
58363   pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
58364   p->pNext = *pp;
58365   *pp = p;
58366   p->isAttached = 1;
58367 }
58368
58369 /*
58370 ** Copy nPage pages from the source b-tree to the destination.
58371 */
58372 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
58373   int rc;
58374   int destMode;       /* Destination journal mode */
58375   int pgszSrc = 0;    /* Source page size */
58376   int pgszDest = 0;   /* Destination page size */
58377
58378   sqlite3_mutex_enter(p->pSrcDb->mutex);
58379   sqlite3BtreeEnter(p->pSrc);
58380   if( p->pDestDb ){
58381     sqlite3_mutex_enter(p->pDestDb->mutex);
58382   }
58383
58384   rc = p->rc;
58385   if( !isFatalError(rc) ){
58386     Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
58387     Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
58388     int ii;                            /* Iterator variable */
58389     int nSrcPage = -1;                 /* Size of source db in pages */
58390     int bCloseTrans = 0;               /* True if src db requires unlocking */
58391
58392     /* If the source pager is currently in a write-transaction, return
58393     ** SQLITE_BUSY immediately.
58394     */
58395     if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
58396       rc = SQLITE_BUSY;
58397     }else{
58398       rc = SQLITE_OK;
58399     }
58400
58401     /* Lock the destination database, if it is not locked already. */
58402     if( SQLITE_OK==rc && p->bDestLocked==0
58403      && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2)) 
58404     ){
58405       p->bDestLocked = 1;
58406       sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
58407     }
58408
58409     /* If there is no open read-transaction on the source database, open
58410     ** one now. If a transaction is opened here, then it will be closed
58411     ** before this function exits.
58412     */
58413     if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
58414       rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
58415       bCloseTrans = 1;
58416     }
58417
58418     /* Do not allow backup if the destination database is in WAL mode
58419     ** and the page sizes are different between source and destination */
58420     pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
58421     pgszDest = sqlite3BtreeGetPageSize(p->pDest);
58422     destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
58423     if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
58424       rc = SQLITE_READONLY;
58425     }
58426   
58427     /* Now that there is a read-lock on the source database, query the
58428     ** source pager for the number of pages in the database.
58429     */
58430     nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
58431     assert( nSrcPage>=0 );
58432     for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
58433       const Pgno iSrcPg = p->iNext;                 /* Source page number */
58434       if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
58435         DbPage *pSrcPg;                             /* Source page object */
58436         rc = sqlite3PagerAcquire(pSrcPager, iSrcPg, &pSrcPg,
58437                                  PAGER_ACQUIRE_READONLY);
58438         if( rc==SQLITE_OK ){
58439           rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
58440           sqlite3PagerUnref(pSrcPg);
58441         }
58442       }
58443       p->iNext++;
58444     }
58445     if( rc==SQLITE_OK ){
58446       p->nPagecount = nSrcPage;
58447       p->nRemaining = nSrcPage+1-p->iNext;
58448       if( p->iNext>(Pgno)nSrcPage ){
58449         rc = SQLITE_DONE;
58450       }else if( !p->isAttached ){
58451         attachBackupObject(p);
58452       }
58453     }
58454   
58455     /* Update the schema version field in the destination database. This
58456     ** is to make sure that the schema-version really does change in
58457     ** the case where the source and destination databases have the
58458     ** same schema version.
58459     */
58460     if( rc==SQLITE_DONE ){
58461       if( nSrcPage==0 ){
58462         rc = sqlite3BtreeNewDb(p->pDest);
58463         nSrcPage = 1;
58464       }
58465       if( rc==SQLITE_OK || rc==SQLITE_DONE ){
58466         rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
58467       }
58468       if( rc==SQLITE_OK ){
58469         if( p->pDestDb ){
58470           sqlite3ResetAllSchemasOfConnection(p->pDestDb);
58471         }
58472         if( destMode==PAGER_JOURNALMODE_WAL ){
58473           rc = sqlite3BtreeSetVersion(p->pDest, 2);
58474         }
58475       }
58476       if( rc==SQLITE_OK ){
58477         int nDestTruncate;
58478         /* Set nDestTruncate to the final number of pages in the destination
58479         ** database. The complication here is that the destination page
58480         ** size may be different to the source page size. 
58481         **
58482         ** If the source page size is smaller than the destination page size, 
58483         ** round up. In this case the call to sqlite3OsTruncate() below will
58484         ** fix the size of the file. However it is important to call
58485         ** sqlite3PagerTruncateImage() here so that any pages in the 
58486         ** destination file that lie beyond the nDestTruncate page mark are
58487         ** journalled by PagerCommitPhaseOne() before they are destroyed
58488         ** by the file truncation.
58489         */
58490         assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
58491         assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
58492         if( pgszSrc<pgszDest ){
58493           int ratio = pgszDest/pgszSrc;
58494           nDestTruncate = (nSrcPage+ratio-1)/ratio;
58495           if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
58496             nDestTruncate--;
58497           }
58498         }else{
58499           nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
58500         }
58501         assert( nDestTruncate>0 );
58502
58503         if( pgszSrc<pgszDest ){
58504           /* If the source page-size is smaller than the destination page-size,
58505           ** two extra things may need to happen:
58506           **
58507           **   * The destination may need to be truncated, and
58508           **
58509           **   * Data stored on the pages immediately following the 
58510           **     pending-byte page in the source database may need to be
58511           **     copied into the destination database.
58512           */
58513           const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
58514           sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
58515           Pgno iPg;
58516           int nDstPage;
58517           i64 iOff;
58518           i64 iEnd;
58519
58520           assert( pFile );
58521           assert( nDestTruncate==0 
58522               || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
58523                 nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
58524              && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
58525           ));
58526
58527           /* This block ensures that all data required to recreate the original
58528           ** database has been stored in the journal for pDestPager and the
58529           ** journal synced to disk. So at this point we may safely modify
58530           ** the database file in any way, knowing that if a power failure
58531           ** occurs, the original database will be reconstructed from the 
58532           ** journal file.  */
58533           sqlite3PagerPagecount(pDestPager, &nDstPage);
58534           for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
58535             if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
58536               DbPage *pPg;
58537               rc = sqlite3PagerGet(pDestPager, iPg, &pPg);
58538               if( rc==SQLITE_OK ){
58539                 rc = sqlite3PagerWrite(pPg);
58540                 sqlite3PagerUnref(pPg);
58541               }
58542             }
58543           }
58544           if( rc==SQLITE_OK ){
58545             rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
58546           }
58547
58548           /* Write the extra pages and truncate the database file as required */
58549           iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
58550           for(
58551             iOff=PENDING_BYTE+pgszSrc; 
58552             rc==SQLITE_OK && iOff<iEnd; 
58553             iOff+=pgszSrc
58554           ){
58555             PgHdr *pSrcPg = 0;
58556             const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
58557             rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
58558             if( rc==SQLITE_OK ){
58559               u8 *zData = sqlite3PagerGetData(pSrcPg);
58560               rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
58561             }
58562             sqlite3PagerUnref(pSrcPg);
58563           }
58564           if( rc==SQLITE_OK ){
58565             rc = backupTruncateFile(pFile, iSize);
58566           }
58567
58568           /* Sync the database file to disk. */
58569           if( rc==SQLITE_OK ){
58570             rc = sqlite3PagerSync(pDestPager);
58571           }
58572         }else{
58573           sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
58574           rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
58575         }
58576     
58577         /* Finish committing the transaction to the destination database. */
58578         if( SQLITE_OK==rc
58579          && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
58580         ){
58581           rc = SQLITE_DONE;
58582         }
58583       }
58584     }
58585   
58586     /* If bCloseTrans is true, then this function opened a read transaction
58587     ** on the source database. Close the read transaction here. There is
58588     ** no need to check the return values of the btree methods here, as
58589     ** "committing" a read-only transaction cannot fail.
58590     */
58591     if( bCloseTrans ){
58592       TESTONLY( int rc2 );
58593       TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
58594       TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
58595       assert( rc2==SQLITE_OK );
58596     }
58597   
58598     if( rc==SQLITE_IOERR_NOMEM ){
58599       rc = SQLITE_NOMEM;
58600     }
58601     p->rc = rc;
58602   }
58603   if( p->pDestDb ){
58604     sqlite3_mutex_leave(p->pDestDb->mutex);
58605   }
58606   sqlite3BtreeLeave(p->pSrc);
58607   sqlite3_mutex_leave(p->pSrcDb->mutex);
58608   return rc;
58609 }
58610
58611 /*
58612 ** Release all resources associated with an sqlite3_backup* handle.
58613 */
58614 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
58615   sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
58616   sqlite3 *pSrcDb;                     /* Source database connection */
58617   int rc;                              /* Value to return */
58618
58619   /* Enter the mutexes */
58620   if( p==0 ) return SQLITE_OK;
58621   pSrcDb = p->pSrcDb;
58622   sqlite3_mutex_enter(pSrcDb->mutex);
58623   sqlite3BtreeEnter(p->pSrc);
58624   if( p->pDestDb ){
58625     sqlite3_mutex_enter(p->pDestDb->mutex);
58626   }
58627
58628   /* Detach this backup from the source pager. */
58629   if( p->pDestDb ){
58630     p->pSrc->nBackup--;
58631   }
58632   if( p->isAttached ){
58633     pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
58634     while( *pp!=p ){
58635       pp = &(*pp)->pNext;
58636     }
58637     *pp = p->pNext;
58638   }
58639
58640   /* If a transaction is still open on the Btree, roll it back. */
58641   sqlite3BtreeRollback(p->pDest, SQLITE_OK);
58642
58643   /* Set the error code of the destination database handle. */
58644   rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
58645   sqlite3Error(p->pDestDb, rc, 0);
58646
58647   /* Exit the mutexes and free the backup context structure. */
58648   if( p->pDestDb ){
58649     sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
58650   }
58651   sqlite3BtreeLeave(p->pSrc);
58652   if( p->pDestDb ){
58653     /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
58654     ** call to sqlite3_backup_init() and is destroyed by a call to
58655     ** sqlite3_backup_finish(). */
58656     sqlite3_free(p);
58657   }
58658   sqlite3LeaveMutexAndCloseZombie(pSrcDb);
58659   return rc;
58660 }
58661
58662 /*
58663 ** Return the number of pages still to be backed up as of the most recent
58664 ** call to sqlite3_backup_step().
58665 */
58666 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
58667   return p->nRemaining;
58668 }
58669
58670 /*
58671 ** Return the total number of pages in the source database as of the most 
58672 ** recent call to sqlite3_backup_step().
58673 */
58674 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
58675   return p->nPagecount;
58676 }
58677
58678 /*
58679 ** This function is called after the contents of page iPage of the
58680 ** source database have been modified. If page iPage has already been 
58681 ** copied into the destination database, then the data written to the
58682 ** destination is now invalidated. The destination copy of iPage needs
58683 ** to be updated with the new data before the backup operation is
58684 ** complete.
58685 **
58686 ** It is assumed that the mutex associated with the BtShared object
58687 ** corresponding to the source database is held when this function is
58688 ** called.
58689 */
58690 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
58691   sqlite3_backup *p;                   /* Iterator variable */
58692   for(p=pBackup; p; p=p->pNext){
58693     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
58694     if( !isFatalError(p->rc) && iPage<p->iNext ){
58695       /* The backup process p has already copied page iPage. But now it
58696       ** has been modified by a transaction on the source pager. Copy
58697       ** the new data into the backup.
58698       */
58699       int rc;
58700       assert( p->pDestDb );
58701       sqlite3_mutex_enter(p->pDestDb->mutex);
58702       rc = backupOnePage(p, iPage, aData, 1);
58703       sqlite3_mutex_leave(p->pDestDb->mutex);
58704       assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
58705       if( rc!=SQLITE_OK ){
58706         p->rc = rc;
58707       }
58708     }
58709   }
58710 }
58711
58712 /*
58713 ** Restart the backup process. This is called when the pager layer
58714 ** detects that the database has been modified by an external database
58715 ** connection. In this case there is no way of knowing which of the
58716 ** pages that have been copied into the destination database are still 
58717 ** valid and which are not, so the entire process needs to be restarted.
58718 **
58719 ** It is assumed that the mutex associated with the BtShared object
58720 ** corresponding to the source database is held when this function is
58721 ** called.
58722 */
58723 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
58724   sqlite3_backup *p;                   /* Iterator variable */
58725   for(p=pBackup; p; p=p->pNext){
58726     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
58727     p->iNext = 1;
58728   }
58729 }
58730
58731 #ifndef SQLITE_OMIT_VACUUM
58732 /*
58733 ** Copy the complete content of pBtFrom into pBtTo.  A transaction
58734 ** must be active for both files.
58735 **
58736 ** The size of file pTo may be reduced by this operation. If anything 
58737 ** goes wrong, the transaction on pTo is rolled back. If successful, the 
58738 ** transaction is committed before returning.
58739 */
58740 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
58741   int rc;
58742   sqlite3_file *pFd;              /* File descriptor for database pTo */
58743   sqlite3_backup b;
58744   sqlite3BtreeEnter(pTo);
58745   sqlite3BtreeEnter(pFrom);
58746
58747   assert( sqlite3BtreeIsInTrans(pTo) );
58748   pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
58749   if( pFd->pMethods ){
58750     i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
58751     rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
58752     if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
58753     if( rc ) goto copy_finished;
58754   }
58755
58756   /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
58757   ** to 0. This is used by the implementations of sqlite3_backup_step()
58758   ** and sqlite3_backup_finish() to detect that they are being called
58759   ** from this function, not directly by the user.
58760   */
58761   memset(&b, 0, sizeof(b));
58762   b.pSrcDb = pFrom->db;
58763   b.pSrc = pFrom;
58764   b.pDest = pTo;
58765   b.iNext = 1;
58766
58767   /* 0x7FFFFFFF is the hard limit for the number of pages in a database
58768   ** file. By passing this as the number of pages to copy to
58769   ** sqlite3_backup_step(), we can guarantee that the copy finishes 
58770   ** within a single call (unless an error occurs). The assert() statement
58771   ** checks this assumption - (p->rc) should be set to either SQLITE_DONE 
58772   ** or an error code.
58773   */
58774   sqlite3_backup_step(&b, 0x7FFFFFFF);
58775   assert( b.rc!=SQLITE_OK );
58776   rc = sqlite3_backup_finish(&b);
58777   if( rc==SQLITE_OK ){
58778     pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
58779   }else{
58780     sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
58781   }
58782
58783   assert( sqlite3BtreeIsInTrans(pTo)==0 );
58784 copy_finished:
58785   sqlite3BtreeLeave(pFrom);
58786   sqlite3BtreeLeave(pTo);
58787   return rc;
58788 }
58789 #endif /* SQLITE_OMIT_VACUUM */
58790
58791 /************** End of backup.c **********************************************/
58792 /************** Begin file vdbemem.c *****************************************/
58793 /*
58794 ** 2004 May 26
58795 **
58796 ** The author disclaims copyright to this source code.  In place of
58797 ** a legal notice, here is a blessing:
58798 **
58799 **    May you do good and not evil.
58800 **    May you find forgiveness for yourself and forgive others.
58801 **    May you share freely, never taking more than you give.
58802 **
58803 *************************************************************************
58804 **
58805 ** This file contains code use to manipulate "Mem" structure.  A "Mem"
58806 ** stores a single value in the VDBE.  Mem is an opaque structure visible
58807 ** only within the VDBE.  Interface routines refer to a Mem using the
58808 ** name sqlite_value
58809 */
58810
58811 /*
58812 ** If pMem is an object with a valid string representation, this routine
58813 ** ensures the internal encoding for the string representation is
58814 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
58815 **
58816 ** If pMem is not a string object, or the encoding of the string
58817 ** representation is already stored using the requested encoding, then this
58818 ** routine is a no-op.
58819 **
58820 ** SQLITE_OK is returned if the conversion is successful (or not required).
58821 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
58822 ** between formats.
58823 */
58824 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
58825 #ifndef SQLITE_OMIT_UTF16
58826   int rc;
58827 #endif
58828   assert( (pMem->flags&MEM_RowSet)==0 );
58829   assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
58830            || desiredEnc==SQLITE_UTF16BE );
58831   if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
58832     return SQLITE_OK;
58833   }
58834   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
58835 #ifdef SQLITE_OMIT_UTF16
58836   return SQLITE_ERROR;
58837 #else
58838
58839   /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
58840   ** then the encoding of the value may not have changed.
58841   */
58842   rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
58843   assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
58844   assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
58845   assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
58846   return rc;
58847 #endif
58848 }
58849
58850 /*
58851 ** Make sure pMem->z points to a writable allocation of at least 
58852 ** n bytes.
58853 **
58854 ** If the third argument passed to this function is true, then memory
58855 ** cell pMem must contain a string or blob. In this case the content is
58856 ** preserved. Otherwise, if the third parameter to this function is false,
58857 ** any current string or blob value may be discarded.
58858 **
58859 ** This function sets the MEM_Dyn flag and clears any xDel callback.
58860 ** It also clears MEM_Ephem and MEM_Static. If the preserve flag is 
58861 ** not set, Mem.n is zeroed.
58862 */
58863 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
58864   assert( 1 >=
58865     ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
58866     (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) + 
58867     ((pMem->flags&MEM_Ephem) ? 1 : 0) + 
58868     ((pMem->flags&MEM_Static) ? 1 : 0)
58869   );
58870   assert( (pMem->flags&MEM_RowSet)==0 );
58871
58872   /* If the preserve flag is set to true, then the memory cell must already
58873   ** contain a valid string or blob value.  */
58874   assert( preserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
58875
58876   if( n<32 ) n = 32;
58877   if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
58878     if( preserve && pMem->z==pMem->zMalloc ){
58879       pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
58880       preserve = 0;
58881     }else{
58882       sqlite3DbFree(pMem->db, pMem->zMalloc);
58883       pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
58884     }
58885   }
58886
58887   if( pMem->z && preserve && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
58888     memcpy(pMem->zMalloc, pMem->z, pMem->n);
58889   }
58890   if( pMem->flags&MEM_Dyn && pMem->xDel ){
58891     assert( pMem->xDel!=SQLITE_DYNAMIC );
58892     pMem->xDel((void *)(pMem->z));
58893   }
58894
58895   pMem->z = pMem->zMalloc;
58896   if( pMem->z==0 ){
58897     pMem->flags = MEM_Null;
58898   }else{
58899     pMem->flags &= ~(MEM_Ephem|MEM_Static);
58900   }
58901   pMem->xDel = 0;
58902   return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
58903 }
58904
58905 /*
58906 ** Make the given Mem object MEM_Dyn.  In other words, make it so
58907 ** that any TEXT or BLOB content is stored in memory obtained from
58908 ** malloc().  In this way, we know that the memory is safe to be
58909 ** overwritten or altered.
58910 **
58911 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
58912 */
58913 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
58914   int f;
58915   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
58916   assert( (pMem->flags&MEM_RowSet)==0 );
58917   ExpandBlob(pMem);
58918   f = pMem->flags;
58919   if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
58920     if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
58921       return SQLITE_NOMEM;
58922     }
58923     pMem->z[pMem->n] = 0;
58924     pMem->z[pMem->n+1] = 0;
58925     pMem->flags |= MEM_Term;
58926 #ifdef SQLITE_DEBUG
58927     pMem->pScopyFrom = 0;
58928 #endif
58929   }
58930
58931   return SQLITE_OK;
58932 }
58933
58934 /*
58935 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
58936 ** blob stored in dynamically allocated space.
58937 */
58938 #ifndef SQLITE_OMIT_INCRBLOB
58939 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
58940   if( pMem->flags & MEM_Zero ){
58941     int nByte;
58942     assert( pMem->flags&MEM_Blob );
58943     assert( (pMem->flags&MEM_RowSet)==0 );
58944     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
58945
58946     /* Set nByte to the number of bytes required to store the expanded blob. */
58947     nByte = pMem->n + pMem->u.nZero;
58948     if( nByte<=0 ){
58949       nByte = 1;
58950     }
58951     if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
58952       return SQLITE_NOMEM;
58953     }
58954
58955     memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
58956     pMem->n += pMem->u.nZero;
58957     pMem->flags &= ~(MEM_Zero|MEM_Term);
58958   }
58959   return SQLITE_OK;
58960 }
58961 #endif
58962
58963
58964 /*
58965 ** Make sure the given Mem is \u0000 terminated.
58966 */
58967 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
58968   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
58969   if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
58970     return SQLITE_OK;   /* Nothing to do */
58971   }
58972   if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
58973     return SQLITE_NOMEM;
58974   }
58975   pMem->z[pMem->n] = 0;
58976   pMem->z[pMem->n+1] = 0;
58977   pMem->flags |= MEM_Term;
58978   return SQLITE_OK;
58979 }
58980
58981 /*
58982 ** Add MEM_Str to the set of representations for the given Mem.  Numbers
58983 ** are converted using sqlite3_snprintf().  Converting a BLOB to a string
58984 ** is a no-op.
58985 **
58986 ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
58987 **
58988 ** A MEM_Null value will never be passed to this function. This function is
58989 ** used for converting values to text for returning to the user (i.e. via
58990 ** sqlite3_value_text()), or for ensuring that values to be used as btree
58991 ** keys are strings. In the former case a NULL pointer is returned the
58992 ** user and the later is an internal programming error.
58993 */
58994 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
58995   int rc = SQLITE_OK;
58996   int fg = pMem->flags;
58997   const int nByte = 32;
58998
58999   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59000   assert( !(fg&MEM_Zero) );
59001   assert( !(fg&(MEM_Str|MEM_Blob)) );
59002   assert( fg&(MEM_Int|MEM_Real) );
59003   assert( (pMem->flags&MEM_RowSet)==0 );
59004   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
59005
59006
59007   if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
59008     return SQLITE_NOMEM;
59009   }
59010
59011   /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
59012   ** string representation of the value. Then, if the required encoding
59013   ** is UTF-16le or UTF-16be do a translation.
59014   ** 
59015   ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
59016   */
59017   if( fg & MEM_Int ){
59018     sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
59019   }else{
59020     assert( fg & MEM_Real );
59021     sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
59022   }
59023   pMem->n = sqlite3Strlen30(pMem->z);
59024   pMem->enc = SQLITE_UTF8;
59025   pMem->flags |= MEM_Str|MEM_Term;
59026   sqlite3VdbeChangeEncoding(pMem, enc);
59027   return rc;
59028 }
59029
59030 /*
59031 ** Memory cell pMem contains the context of an aggregate function.
59032 ** This routine calls the finalize method for that function.  The
59033 ** result of the aggregate is stored back into pMem.
59034 **
59035 ** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
59036 ** otherwise.
59037 */
59038 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
59039   int rc = SQLITE_OK;
59040   if( ALWAYS(pFunc && pFunc->xFinalize) ){
59041     sqlite3_context ctx;
59042     assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
59043     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59044     memset(&ctx, 0, sizeof(ctx));
59045     ctx.s.flags = MEM_Null;
59046     ctx.s.db = pMem->db;
59047     ctx.pMem = pMem;
59048     ctx.pFunc = pFunc;
59049     pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
59050     assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
59051     sqlite3DbFree(pMem->db, pMem->zMalloc);
59052     memcpy(pMem, &ctx.s, sizeof(ctx.s));
59053     rc = ctx.isError;
59054   }
59055   return rc;
59056 }
59057
59058 /*
59059 ** If the memory cell contains a string value that must be freed by
59060 ** invoking an external callback, free it now. Calling this function
59061 ** does not free any Mem.zMalloc buffer.
59062 */
59063 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
59064   assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
59065   if( p->flags&MEM_Agg ){
59066     sqlite3VdbeMemFinalize(p, p->u.pDef);
59067     assert( (p->flags & MEM_Agg)==0 );
59068     sqlite3VdbeMemRelease(p);
59069   }else if( p->flags&MEM_Dyn && p->xDel ){
59070     assert( (p->flags&MEM_RowSet)==0 );
59071     assert( p->xDel!=SQLITE_DYNAMIC );
59072     p->xDel((void *)p->z);
59073     p->xDel = 0;
59074   }else if( p->flags&MEM_RowSet ){
59075     sqlite3RowSetClear(p->u.pRowSet);
59076   }else if( p->flags&MEM_Frame ){
59077     sqlite3VdbeMemSetNull(p);
59078   }
59079 }
59080
59081 /*
59082 ** Release any memory held by the Mem. This may leave the Mem in an
59083 ** inconsistent state, for example with (Mem.z==0) and
59084 ** (Mem.type==SQLITE_TEXT).
59085 */
59086 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
59087   VdbeMemRelease(p);
59088   sqlite3DbFree(p->db, p->zMalloc);
59089   p->z = 0;
59090   p->zMalloc = 0;
59091   p->xDel = 0;
59092 }
59093
59094 /*
59095 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
59096 ** If the double is too large, return 0x8000000000000000.
59097 **
59098 ** Most systems appear to do this simply by assigning
59099 ** variables and without the extra range tests.  But
59100 ** there are reports that windows throws an expection
59101 ** if the floating point value is out of range. (See ticket #2880.)
59102 ** Because we do not completely understand the problem, we will
59103 ** take the conservative approach and always do range tests
59104 ** before attempting the conversion.
59105 */
59106 static i64 doubleToInt64(double r){
59107 #ifdef SQLITE_OMIT_FLOATING_POINT
59108   /* When floating-point is omitted, double and int64 are the same thing */
59109   return r;
59110 #else
59111   /*
59112   ** Many compilers we encounter do not define constants for the
59113   ** minimum and maximum 64-bit integers, or they define them
59114   ** inconsistently.  And many do not understand the "LL" notation.
59115   ** So we define our own static constants here using nothing
59116   ** larger than a 32-bit integer constant.
59117   */
59118   static const i64 maxInt = LARGEST_INT64;
59119   static const i64 minInt = SMALLEST_INT64;
59120
59121   if( r<(double)minInt ){
59122     return minInt;
59123   }else if( r>(double)maxInt ){
59124     /* minInt is correct here - not maxInt.  It turns out that assigning
59125     ** a very large positive number to an integer results in a very large
59126     ** negative integer.  This makes no sense, but it is what x86 hardware
59127     ** does so for compatibility we will do the same in software. */
59128     return minInt;
59129   }else{
59130     return (i64)r;
59131   }
59132 #endif
59133 }
59134
59135 /*
59136 ** Return some kind of integer value which is the best we can do
59137 ** at representing the value that *pMem describes as an integer.
59138 ** If pMem is an integer, then the value is exact.  If pMem is
59139 ** a floating-point then the value returned is the integer part.
59140 ** If pMem is a string or blob, then we make an attempt to convert
59141 ** it into a integer and return that.  If pMem represents an
59142 ** an SQL-NULL value, return 0.
59143 **
59144 ** If pMem represents a string value, its encoding might be changed.
59145 */
59146 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
59147   int flags;
59148   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59149   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
59150   flags = pMem->flags;
59151   if( flags & MEM_Int ){
59152     return pMem->u.i;
59153   }else if( flags & MEM_Real ){
59154     return doubleToInt64(pMem->r);
59155   }else if( flags & (MEM_Str|MEM_Blob) ){
59156     i64 value = 0;
59157     assert( pMem->z || pMem->n==0 );
59158     testcase( pMem->z==0 );
59159     sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
59160     return value;
59161   }else{
59162     return 0;
59163   }
59164 }
59165
59166 /*
59167 ** Return the best representation of pMem that we can get into a
59168 ** double.  If pMem is already a double or an integer, return its
59169 ** value.  If it is a string or blob, try to convert it to a double.
59170 ** If it is a NULL, return 0.0.
59171 */
59172 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
59173   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59174   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
59175   if( pMem->flags & MEM_Real ){
59176     return pMem->r;
59177   }else if( pMem->flags & MEM_Int ){
59178     return (double)pMem->u.i;
59179   }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
59180     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
59181     double val = (double)0;
59182     sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
59183     return val;
59184   }else{
59185     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
59186     return (double)0;
59187   }
59188 }
59189
59190 /*
59191 ** The MEM structure is already a MEM_Real.  Try to also make it a
59192 ** MEM_Int if we can.
59193 */
59194 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
59195   assert( pMem->flags & MEM_Real );
59196   assert( (pMem->flags & MEM_RowSet)==0 );
59197   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59198   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
59199
59200   pMem->u.i = doubleToInt64(pMem->r);
59201
59202   /* Only mark the value as an integer if
59203   **
59204   **    (1) the round-trip conversion real->int->real is a no-op, and
59205   **    (2) The integer is neither the largest nor the smallest
59206   **        possible integer (ticket #3922)
59207   **
59208   ** The second and third terms in the following conditional enforces
59209   ** the second condition under the assumption that addition overflow causes
59210   ** values to wrap around.  On x86 hardware, the third term is always
59211   ** true and could be omitted.  But we leave it in because other
59212   ** architectures might behave differently.
59213   */
59214   if( pMem->r==(double)pMem->u.i
59215    && pMem->u.i>SMALLEST_INT64
59216 #if defined(__i486__) || defined(__x86_64__)
59217    && ALWAYS(pMem->u.i<LARGEST_INT64)
59218 #else
59219    && pMem->u.i<LARGEST_INT64
59220 #endif
59221   ){
59222     pMem->flags |= MEM_Int;
59223   }
59224 }
59225
59226 /*
59227 ** Convert pMem to type integer.  Invalidate any prior representations.
59228 */
59229 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
59230   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59231   assert( (pMem->flags & MEM_RowSet)==0 );
59232   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
59233
59234   pMem->u.i = sqlite3VdbeIntValue(pMem);
59235   MemSetTypeFlag(pMem, MEM_Int);
59236   return SQLITE_OK;
59237 }
59238
59239 /*
59240 ** Convert pMem so that it is of type MEM_Real.
59241 ** Invalidate any prior representations.
59242 */
59243 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
59244   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59245   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
59246
59247   pMem->r = sqlite3VdbeRealValue(pMem);
59248   MemSetTypeFlag(pMem, MEM_Real);
59249   return SQLITE_OK;
59250 }
59251
59252 /*
59253 ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
59254 ** Invalidate any prior representations.
59255 **
59256 ** Every effort is made to force the conversion, even if the input
59257 ** is a string that does not look completely like a number.  Convert
59258 ** as much of the string as we can and ignore the rest.
59259 */
59260 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
59261   if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
59262     assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
59263     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59264     if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
59265       MemSetTypeFlag(pMem, MEM_Int);
59266     }else{
59267       pMem->r = sqlite3VdbeRealValue(pMem);
59268       MemSetTypeFlag(pMem, MEM_Real);
59269       sqlite3VdbeIntegerAffinity(pMem);
59270     }
59271   }
59272   assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
59273   pMem->flags &= ~(MEM_Str|MEM_Blob);
59274   return SQLITE_OK;
59275 }
59276
59277 /*
59278 ** Delete any previous value and set the value stored in *pMem to NULL.
59279 */
59280 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
59281   if( pMem->flags & MEM_Frame ){
59282     VdbeFrame *pFrame = pMem->u.pFrame;
59283     pFrame->pParent = pFrame->v->pDelFrame;
59284     pFrame->v->pDelFrame = pFrame;
59285   }
59286   if( pMem->flags & MEM_RowSet ){
59287     sqlite3RowSetClear(pMem->u.pRowSet);
59288   }
59289   MemSetTypeFlag(pMem, MEM_Null);
59290   pMem->type = SQLITE_NULL;
59291 }
59292
59293 /*
59294 ** Delete any previous value and set the value to be a BLOB of length
59295 ** n containing all zeros.
59296 */
59297 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
59298   sqlite3VdbeMemRelease(pMem);
59299   pMem->flags = MEM_Blob|MEM_Zero;
59300   pMem->type = SQLITE_BLOB;
59301   pMem->n = 0;
59302   if( n<0 ) n = 0;
59303   pMem->u.nZero = n;
59304   pMem->enc = SQLITE_UTF8;
59305
59306 #ifdef SQLITE_OMIT_INCRBLOB
59307   sqlite3VdbeMemGrow(pMem, n, 0);
59308   if( pMem->z ){
59309     pMem->n = n;
59310     memset(pMem->z, 0, n);
59311   }
59312 #endif
59313 }
59314
59315 /*
59316 ** Delete any previous value and set the value stored in *pMem to val,
59317 ** manifest type INTEGER.
59318 */
59319 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
59320   sqlite3VdbeMemRelease(pMem);
59321   pMem->u.i = val;
59322   pMem->flags = MEM_Int;
59323   pMem->type = SQLITE_INTEGER;
59324 }
59325
59326 #ifndef SQLITE_OMIT_FLOATING_POINT
59327 /*
59328 ** Delete any previous value and set the value stored in *pMem to val,
59329 ** manifest type REAL.
59330 */
59331 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
59332   if( sqlite3IsNaN(val) ){
59333     sqlite3VdbeMemSetNull(pMem);
59334   }else{
59335     sqlite3VdbeMemRelease(pMem);
59336     pMem->r = val;
59337     pMem->flags = MEM_Real;
59338     pMem->type = SQLITE_FLOAT;
59339   }
59340 }
59341 #endif
59342
59343 /*
59344 ** Delete any previous value and set the value of pMem to be an
59345 ** empty boolean index.
59346 */
59347 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
59348   sqlite3 *db = pMem->db;
59349   assert( db!=0 );
59350   assert( (pMem->flags & MEM_RowSet)==0 );
59351   sqlite3VdbeMemRelease(pMem);
59352   pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
59353   if( db->mallocFailed ){
59354     pMem->flags = MEM_Null;
59355   }else{
59356     assert( pMem->zMalloc );
59357     pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, 
59358                                        sqlite3DbMallocSize(db, pMem->zMalloc));
59359     assert( pMem->u.pRowSet!=0 );
59360     pMem->flags = MEM_RowSet;
59361   }
59362 }
59363
59364 /*
59365 ** Return true if the Mem object contains a TEXT or BLOB that is
59366 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
59367 */
59368 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
59369   assert( p->db!=0 );
59370   if( p->flags & (MEM_Str|MEM_Blob) ){
59371     int n = p->n;
59372     if( p->flags & MEM_Zero ){
59373       n += p->u.nZero;
59374     }
59375     return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
59376   }
59377   return 0; 
59378 }
59379
59380 #ifdef SQLITE_DEBUG
59381 /*
59382 ** This routine prepares a memory cell for modication by breaking
59383 ** its link to a shallow copy and by marking any current shallow
59384 ** copies of this cell as invalid.
59385 **
59386 ** This is used for testing and debugging only - to make sure shallow
59387 ** copies are not misused.
59388 */
59389 SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
59390   int i;
59391   Mem *pX;
59392   for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
59393     if( pX->pScopyFrom==pMem ){
59394       pX->flags |= MEM_Invalid;
59395       pX->pScopyFrom = 0;
59396     }
59397   }
59398   pMem->pScopyFrom = 0;
59399 }
59400 #endif /* SQLITE_DEBUG */
59401
59402 /*
59403 ** Size of struct Mem not including the Mem.zMalloc member.
59404 */
59405 #define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
59406
59407 /*
59408 ** Make an shallow copy of pFrom into pTo.  Prior contents of
59409 ** pTo are freed.  The pFrom->z field is not duplicated.  If
59410 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
59411 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
59412 */
59413 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
59414   assert( (pFrom->flags & MEM_RowSet)==0 );
59415   VdbeMemRelease(pTo);
59416   memcpy(pTo, pFrom, MEMCELLSIZE);
59417   pTo->xDel = 0;
59418   if( (pFrom->flags&MEM_Static)==0 ){
59419     pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
59420     assert( srcType==MEM_Ephem || srcType==MEM_Static );
59421     pTo->flags |= srcType;
59422   }
59423 }
59424
59425 /*
59426 ** Make a full copy of pFrom into pTo.  Prior contents of pTo are
59427 ** freed before the copy is made.
59428 */
59429 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
59430   int rc = SQLITE_OK;
59431
59432   assert( (pFrom->flags & MEM_RowSet)==0 );
59433   VdbeMemRelease(pTo);
59434   memcpy(pTo, pFrom, MEMCELLSIZE);
59435   pTo->flags &= ~MEM_Dyn;
59436
59437   if( pTo->flags&(MEM_Str|MEM_Blob) ){
59438     if( 0==(pFrom->flags&MEM_Static) ){
59439       pTo->flags |= MEM_Ephem;
59440       rc = sqlite3VdbeMemMakeWriteable(pTo);
59441     }
59442   }
59443
59444   return rc;
59445 }
59446
59447 /*
59448 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
59449 ** freed. If pFrom contains ephemeral data, a copy is made.
59450 **
59451 ** pFrom contains an SQL NULL when this routine returns.
59452 */
59453 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
59454   assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
59455   assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
59456   assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
59457
59458   sqlite3VdbeMemRelease(pTo);
59459   memcpy(pTo, pFrom, sizeof(Mem));
59460   pFrom->flags = MEM_Null;
59461   pFrom->xDel = 0;
59462   pFrom->zMalloc = 0;
59463 }
59464
59465 /*
59466 ** Change the value of a Mem to be a string or a BLOB.
59467 **
59468 ** The memory management strategy depends on the value of the xDel
59469 ** parameter. If the value passed is SQLITE_TRANSIENT, then the 
59470 ** string is copied into a (possibly existing) buffer managed by the 
59471 ** Mem structure. Otherwise, any existing buffer is freed and the
59472 ** pointer copied.
59473 **
59474 ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
59475 ** size limit) then no memory allocation occurs.  If the string can be
59476 ** stored without allocating memory, then it is.  If a memory allocation
59477 ** is required to store the string, then value of pMem is unchanged.  In
59478 ** either case, SQLITE_TOOBIG is returned.
59479 */
59480 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
59481   Mem *pMem,          /* Memory cell to set to string value */
59482   const char *z,      /* String pointer */
59483   int n,              /* Bytes in string, or negative */
59484   u8 enc,             /* Encoding of z.  0 for BLOBs */
59485   void (*xDel)(void*) /* Destructor function */
59486 ){
59487   int nByte = n;      /* New value for pMem->n */
59488   int iLimit;         /* Maximum allowed string or blob size */
59489   u16 flags = 0;      /* New value for pMem->flags */
59490
59491   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
59492   assert( (pMem->flags & MEM_RowSet)==0 );
59493
59494   /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
59495   if( !z ){
59496     sqlite3VdbeMemSetNull(pMem);
59497     return SQLITE_OK;
59498   }
59499
59500   if( pMem->db ){
59501     iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
59502   }else{
59503     iLimit = SQLITE_MAX_LENGTH;
59504   }
59505   flags = (enc==0?MEM_Blob:MEM_Str);
59506   if( nByte<0 ){
59507     assert( enc!=0 );
59508     if( enc==SQLITE_UTF8 ){
59509       for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
59510     }else{
59511       for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
59512     }
59513     flags |= MEM_Term;
59514   }
59515
59516   /* The following block sets the new values of Mem.z and Mem.xDel. It
59517   ** also sets a flag in local variable "flags" to indicate the memory
59518   ** management (one of MEM_Dyn or MEM_Static).
59519   */
59520   if( xDel==SQLITE_TRANSIENT ){
59521     int nAlloc = nByte;
59522     if( flags&MEM_Term ){
59523       nAlloc += (enc==SQLITE_UTF8?1:2);
59524     }
59525     if( nByte>iLimit ){
59526       return SQLITE_TOOBIG;
59527     }
59528     if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
59529       return SQLITE_NOMEM;
59530     }
59531     memcpy(pMem->z, z, nAlloc);
59532   }else if( xDel==SQLITE_DYNAMIC ){
59533     sqlite3VdbeMemRelease(pMem);
59534     pMem->zMalloc = pMem->z = (char *)z;
59535     pMem->xDel = 0;
59536   }else{
59537     sqlite3VdbeMemRelease(pMem);
59538     pMem->z = (char *)z;
59539     pMem->xDel = xDel;
59540     flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
59541   }
59542
59543   pMem->n = nByte;
59544   pMem->flags = flags;
59545   pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
59546   pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
59547
59548 #ifndef SQLITE_OMIT_UTF16
59549   if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
59550     return SQLITE_NOMEM;
59551   }
59552 #endif
59553
59554   if( nByte>iLimit ){
59555     return SQLITE_TOOBIG;
59556   }
59557
59558   return SQLITE_OK;
59559 }
59560
59561 /*
59562 ** Compare the values contained by the two memory cells, returning
59563 ** negative, zero or positive if pMem1 is less than, equal to, or greater
59564 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
59565 ** and reals) sorted numerically, followed by text ordered by the collating
59566 ** sequence pColl and finally blob's ordered by memcmp().
59567 **
59568 ** Two NULL values are considered equal by this function.
59569 */
59570 SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
59571   int rc;
59572   int f1, f2;
59573   int combined_flags;
59574
59575   f1 = pMem1->flags;
59576   f2 = pMem2->flags;
59577   combined_flags = f1|f2;
59578   assert( (combined_flags & MEM_RowSet)==0 );
59579  
59580   /* If one value is NULL, it is less than the other. If both values
59581   ** are NULL, return 0.
59582   */
59583   if( combined_flags&MEM_Null ){
59584     return (f2&MEM_Null) - (f1&MEM_Null);
59585   }
59586
59587   /* If one value is a number and the other is not, the number is less.
59588   ** If both are numbers, compare as reals if one is a real, or as integers
59589   ** if both values are integers.
59590   */
59591   if( combined_flags&(MEM_Int|MEM_Real) ){
59592     if( !(f1&(MEM_Int|MEM_Real)) ){
59593       return 1;
59594     }
59595     if( !(f2&(MEM_Int|MEM_Real)) ){
59596       return -1;
59597     }
59598     if( (f1 & f2 & MEM_Int)==0 ){
59599       double r1, r2;
59600       if( (f1&MEM_Real)==0 ){
59601         r1 = (double)pMem1->u.i;
59602       }else{
59603         r1 = pMem1->r;
59604       }
59605       if( (f2&MEM_Real)==0 ){
59606         r2 = (double)pMem2->u.i;
59607       }else{
59608         r2 = pMem2->r;
59609       }
59610       if( r1<r2 ) return -1;
59611       if( r1>r2 ) return 1;
59612       return 0;
59613     }else{
59614       assert( f1&MEM_Int );
59615       assert( f2&MEM_Int );
59616       if( pMem1->u.i < pMem2->u.i ) return -1;
59617       if( pMem1->u.i > pMem2->u.i ) return 1;
59618       return 0;
59619     }
59620   }
59621
59622   /* If one value is a string and the other is a blob, the string is less.
59623   ** If both are strings, compare using the collating functions.
59624   */
59625   if( combined_flags&MEM_Str ){
59626     if( (f1 & MEM_Str)==0 ){
59627       return 1;
59628     }
59629     if( (f2 & MEM_Str)==0 ){
59630       return -1;
59631     }
59632
59633     assert( pMem1->enc==pMem2->enc );
59634     assert( pMem1->enc==SQLITE_UTF8 || 
59635             pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
59636
59637     /* The collation sequence must be defined at this point, even if
59638     ** the user deletes the collation sequence after the vdbe program is
59639     ** compiled (this was not always the case).
59640     */
59641     assert( !pColl || pColl->xCmp );
59642
59643     if( pColl ){
59644       if( pMem1->enc==pColl->enc ){
59645         /* The strings are already in the correct encoding.  Call the
59646         ** comparison function directly */
59647         return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
59648       }else{
59649         const void *v1, *v2;
59650         int n1, n2;
59651         Mem c1;
59652         Mem c2;
59653         memset(&c1, 0, sizeof(c1));
59654         memset(&c2, 0, sizeof(c2));
59655         sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
59656         sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
59657         v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
59658         n1 = v1==0 ? 0 : c1.n;
59659         v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
59660         n2 = v2==0 ? 0 : c2.n;
59661         rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
59662         sqlite3VdbeMemRelease(&c1);
59663         sqlite3VdbeMemRelease(&c2);
59664         return rc;
59665       }
59666     }
59667     /* If a NULL pointer was passed as the collate function, fall through
59668     ** to the blob case and use memcmp().  */
59669   }
59670  
59671   /* Both values must be blobs.  Compare using memcmp().  */
59672   rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
59673   if( rc==0 ){
59674     rc = pMem1->n - pMem2->n;
59675   }
59676   return rc;
59677 }
59678
59679 /*
59680 ** Move data out of a btree key or data field and into a Mem structure.
59681 ** The data or key is taken from the entry that pCur is currently pointing
59682 ** to.  offset and amt determine what portion of the data or key to retrieve.
59683 ** key is true to get the key or false to get data.  The result is written
59684 ** into the pMem element.
59685 **
59686 ** The pMem structure is assumed to be uninitialized.  Any prior content
59687 ** is overwritten without being freed.
59688 **
59689 ** If this routine fails for any reason (malloc returns NULL or unable
59690 ** to read from the disk) then the pMem is left in an inconsistent state.
59691 */
59692 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
59693   BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
59694   int offset,       /* Offset from the start of data to return bytes from. */
59695   int amt,          /* Number of bytes to return. */
59696   int key,          /* If true, retrieve from the btree key, not data. */
59697   Mem *pMem         /* OUT: Return data in this Mem structure. */
59698 ){
59699   char *zData;        /* Data from the btree layer */
59700   int available = 0;  /* Number of bytes available on the local btree page */
59701   int rc = SQLITE_OK; /* Return code */
59702
59703   assert( sqlite3BtreeCursorIsValid(pCur) );
59704
59705   /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert() 
59706   ** that both the BtShared and database handle mutexes are held. */
59707   assert( (pMem->flags & MEM_RowSet)==0 );
59708   if( key ){
59709     zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
59710   }else{
59711     zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
59712   }
59713   assert( zData!=0 );
59714
59715   if( offset+amt<=available && (pMem->flags&MEM_Dyn)==0 ){
59716     sqlite3VdbeMemRelease(pMem);
59717     pMem->z = &zData[offset];
59718     pMem->flags = MEM_Blob|MEM_Ephem;
59719   }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
59720     pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
59721     pMem->enc = 0;
59722     pMem->type = SQLITE_BLOB;
59723     if( key ){
59724       rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
59725     }else{
59726       rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
59727     }
59728     pMem->z[amt] = 0;
59729     pMem->z[amt+1] = 0;
59730     if( rc!=SQLITE_OK ){
59731       sqlite3VdbeMemRelease(pMem);
59732     }
59733   }
59734   pMem->n = amt;
59735
59736   return rc;
59737 }
59738
59739 /* This function is only available internally, it is not part of the
59740 ** external API. It works in a similar way to sqlite3_value_text(),
59741 ** except the data returned is in the encoding specified by the second
59742 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
59743 ** SQLITE_UTF8.
59744 **
59745 ** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
59746 ** If that is the case, then the result must be aligned on an even byte
59747 ** boundary.
59748 */
59749 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
59750   if( !pVal ) return 0;
59751
59752   assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
59753   assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
59754   assert( (pVal->flags & MEM_RowSet)==0 );
59755
59756   if( pVal->flags&MEM_Null ){
59757     return 0;
59758   }
59759   assert( (MEM_Blob>>3) == MEM_Str );
59760   pVal->flags |= (pVal->flags & MEM_Blob)>>3;
59761   ExpandBlob(pVal);
59762   if( pVal->flags&MEM_Str ){
59763     sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
59764     if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
59765       assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
59766       if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
59767         return 0;
59768       }
59769     }
59770     sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
59771   }else{
59772     assert( (pVal->flags&MEM_Blob)==0 );
59773     sqlite3VdbeMemStringify(pVal, enc);
59774     assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
59775   }
59776   assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
59777               || pVal->db->mallocFailed );
59778   if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
59779     return pVal->z;
59780   }else{
59781     return 0;
59782   }
59783 }
59784
59785 /*
59786 ** Create a new sqlite3_value object.
59787 */
59788 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
59789   Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
59790   if( p ){
59791     p->flags = MEM_Null;
59792     p->type = SQLITE_NULL;
59793     p->db = db;
59794   }
59795   return p;
59796 }
59797
59798 /*
59799 ** Create a new sqlite3_value object, containing the value of pExpr.
59800 **
59801 ** This only works for very simple expressions that consist of one constant
59802 ** token (i.e. "5", "5.1", "'a string'"). If the expression can
59803 ** be converted directly into a value, then the value is allocated and
59804 ** a pointer written to *ppVal. The caller is responsible for deallocating
59805 ** the value by passing it to sqlite3ValueFree() later on. If the expression
59806 ** cannot be converted to a value, then *ppVal is set to NULL.
59807 */
59808 SQLITE_PRIVATE int sqlite3ValueFromExpr(
59809   sqlite3 *db,              /* The database connection */
59810   Expr *pExpr,              /* The expression to evaluate */
59811   u8 enc,                   /* Encoding to use */
59812   u8 affinity,              /* Affinity to use */
59813   sqlite3_value **ppVal     /* Write the new value here */
59814 ){
59815   int op;
59816   char *zVal = 0;
59817   sqlite3_value *pVal = 0;
59818   int negInt = 1;
59819   const char *zNeg = "";
59820
59821   if( !pExpr ){
59822     *ppVal = 0;
59823     return SQLITE_OK;
59824   }
59825   op = pExpr->op;
59826
59827   /* op can only be TK_REGISTER if we have compiled with SQLITE_ENABLE_STAT3.
59828   ** The ifdef here is to enable us to achieve 100% branch test coverage even
59829   ** when SQLITE_ENABLE_STAT3 is omitted.
59830   */
59831 #ifdef SQLITE_ENABLE_STAT3
59832   if( op==TK_REGISTER ) op = pExpr->op2;
59833 #else
59834   if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
59835 #endif
59836
59837   /* Handle negative integers in a single step.  This is needed in the
59838   ** case when the value is -9223372036854775808.
59839   */
59840   if( op==TK_UMINUS
59841    && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
59842     pExpr = pExpr->pLeft;
59843     op = pExpr->op;
59844     negInt = -1;
59845     zNeg = "-";
59846   }
59847
59848   if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
59849     pVal = sqlite3ValueNew(db);
59850     if( pVal==0 ) goto no_mem;
59851     if( ExprHasProperty(pExpr, EP_IntValue) ){
59852       sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
59853     }else{
59854       zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
59855       if( zVal==0 ) goto no_mem;
59856       sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
59857       if( op==TK_FLOAT ) pVal->type = SQLITE_FLOAT;
59858     }
59859     if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
59860       sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
59861     }else{
59862       sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
59863     }
59864     if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
59865     if( enc!=SQLITE_UTF8 ){
59866       sqlite3VdbeChangeEncoding(pVal, enc);
59867     }
59868   }else if( op==TK_UMINUS ) {
59869     /* This branch happens for multiple negative signs.  Ex: -(-5) */
59870     if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
59871       sqlite3VdbeMemNumerify(pVal);
59872       if( pVal->u.i==SMALLEST_INT64 ){
59873         pVal->flags &= MEM_Int;
59874         pVal->flags |= MEM_Real;
59875         pVal->r = (double)LARGEST_INT64;
59876       }else{
59877         pVal->u.i = -pVal->u.i;
59878       }
59879       pVal->r = -pVal->r;
59880       sqlite3ValueApplyAffinity(pVal, affinity, enc);
59881     }
59882   }else if( op==TK_NULL ){
59883     pVal = sqlite3ValueNew(db);
59884     if( pVal==0 ) goto no_mem;
59885   }
59886 #ifndef SQLITE_OMIT_BLOB_LITERAL
59887   else if( op==TK_BLOB ){
59888     int nVal;
59889     assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
59890     assert( pExpr->u.zToken[1]=='\'' );
59891     pVal = sqlite3ValueNew(db);
59892     if( !pVal ) goto no_mem;
59893     zVal = &pExpr->u.zToken[2];
59894     nVal = sqlite3Strlen30(zVal)-1;
59895     assert( zVal[nVal]=='\'' );
59896     sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
59897                          0, SQLITE_DYNAMIC);
59898   }
59899 #endif
59900
59901   if( pVal ){
59902     sqlite3VdbeMemStoreType(pVal);
59903   }
59904   *ppVal = pVal;
59905   return SQLITE_OK;
59906
59907 no_mem:
59908   db->mallocFailed = 1;
59909   sqlite3DbFree(db, zVal);
59910   sqlite3ValueFree(pVal);
59911   *ppVal = 0;
59912   return SQLITE_NOMEM;
59913 }
59914
59915 /*
59916 ** Change the string value of an sqlite3_value object
59917 */
59918 SQLITE_PRIVATE void sqlite3ValueSetStr(
59919   sqlite3_value *v,     /* Value to be set */
59920   int n,                /* Length of string z */
59921   const void *z,        /* Text of the new string */
59922   u8 enc,               /* Encoding to use */
59923   void (*xDel)(void*)   /* Destructor for the string */
59924 ){
59925   if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
59926 }
59927
59928 /*
59929 ** Free an sqlite3_value object
59930 */
59931 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
59932   if( !v ) return;
59933   sqlite3VdbeMemRelease((Mem *)v);
59934   sqlite3DbFree(((Mem*)v)->db, v);
59935 }
59936
59937 /*
59938 ** Return the number of bytes in the sqlite3_value object assuming
59939 ** that it uses the encoding "enc"
59940 */
59941 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
59942   Mem *p = (Mem*)pVal;
59943   if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
59944     if( p->flags & MEM_Zero ){
59945       return p->n + p->u.nZero;
59946     }else{
59947       return p->n;
59948     }
59949   }
59950   return 0;
59951 }
59952
59953 /************** End of vdbemem.c *********************************************/
59954 /************** Begin file vdbeaux.c *****************************************/
59955 /*
59956 ** 2003 September 6
59957 **
59958 ** The author disclaims copyright to this source code.  In place of
59959 ** a legal notice, here is a blessing:
59960 **
59961 **    May you do good and not evil.
59962 **    May you find forgiveness for yourself and forgive others.
59963 **    May you share freely, never taking more than you give.
59964 **
59965 *************************************************************************
59966 ** This file contains code used for creating, destroying, and populating
59967 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)  Prior
59968 ** to version 2.8.7, all this code was combined into the vdbe.c source file.
59969 ** But that file was getting too big so this subroutines were split out.
59970 */
59971
59972 /*
59973 ** Create a new virtual database engine.
59974 */
59975 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
59976   Vdbe *p;
59977   p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
59978   if( p==0 ) return 0;
59979   p->db = db;
59980   if( db->pVdbe ){
59981     db->pVdbe->pPrev = p;
59982   }
59983   p->pNext = db->pVdbe;
59984   p->pPrev = 0;
59985   db->pVdbe = p;
59986   p->magic = VDBE_MAGIC_INIT;
59987   return p;
59988 }
59989
59990 /*
59991 ** Remember the SQL string for a prepared statement.
59992 */
59993 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
59994   assert( isPrepareV2==1 || isPrepareV2==0 );
59995   if( p==0 ) return;
59996 #if defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_ENABLE_SQLLOG)
59997   if( !isPrepareV2 ) return;
59998 #endif
59999   assert( p->zSql==0 );
60000   p->zSql = sqlite3DbStrNDup(p->db, z, n);
60001   p->isPrepareV2 = (u8)isPrepareV2;
60002 }
60003
60004 /*
60005 ** Return the SQL associated with a prepared statement
60006 */
60007 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
60008   Vdbe *p = (Vdbe *)pStmt;
60009   return (p && p->isPrepareV2) ? p->zSql : 0;
60010 }
60011
60012 /*
60013 ** Swap all content between two VDBE structures.
60014 */
60015 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
60016   Vdbe tmp, *pTmp;
60017   char *zTmp;
60018   tmp = *pA;
60019   *pA = *pB;
60020   *pB = tmp;
60021   pTmp = pA->pNext;
60022   pA->pNext = pB->pNext;
60023   pB->pNext = pTmp;
60024   pTmp = pA->pPrev;
60025   pA->pPrev = pB->pPrev;
60026   pB->pPrev = pTmp;
60027   zTmp = pA->zSql;
60028   pA->zSql = pB->zSql;
60029   pB->zSql = zTmp;
60030   pB->isPrepareV2 = pA->isPrepareV2;
60031 }
60032
60033 #ifdef SQLITE_DEBUG
60034 /*
60035 ** Turn tracing on or off
60036 */
60037 SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
60038   p->trace = trace;
60039 }
60040 #endif
60041
60042 /*
60043 ** Resize the Vdbe.aOp array so that it is at least one op larger than 
60044 ** it was.
60045 **
60046 ** If an out-of-memory error occurs while resizing the array, return
60047 ** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain 
60048 ** unchanged (this is so that any opcodes already allocated can be 
60049 ** correctly deallocated along with the rest of the Vdbe).
60050 */
60051 static int growOpArray(Vdbe *p){
60052   VdbeOp *pNew;
60053   int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
60054   pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
60055   if( pNew ){
60056     p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
60057     p->aOp = pNew;
60058   }
60059   return (pNew ? SQLITE_OK : SQLITE_NOMEM);
60060 }
60061
60062 /*
60063 ** Add a new instruction to the list of instructions current in the
60064 ** VDBE.  Return the address of the new instruction.
60065 **
60066 ** Parameters:
60067 **
60068 **    p               Pointer to the VDBE
60069 **
60070 **    op              The opcode for this instruction
60071 **
60072 **    p1, p2, p3      Operands
60073 **
60074 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
60075 ** the sqlite3VdbeChangeP4() function to change the value of the P4
60076 ** operand.
60077 */
60078 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
60079   int i;
60080   VdbeOp *pOp;
60081
60082   i = p->nOp;
60083   assert( p->magic==VDBE_MAGIC_INIT );
60084   assert( op>0 && op<0xff );
60085   if( p->nOpAlloc<=i ){
60086     if( growOpArray(p) ){
60087       return 1;
60088     }
60089   }
60090   p->nOp++;
60091   pOp = &p->aOp[i];
60092   pOp->opcode = (u8)op;
60093   pOp->p5 = 0;
60094   pOp->p1 = p1;
60095   pOp->p2 = p2;
60096   pOp->p3 = p3;
60097   pOp->p4.p = 0;
60098   pOp->p4type = P4_NOTUSED;
60099 #ifdef SQLITE_DEBUG
60100   pOp->zComment = 0;
60101   if( p->db->flags & SQLITE_VdbeAddopTrace ){
60102     sqlite3VdbePrintOp(0, i, &p->aOp[i]);
60103   }
60104 #endif
60105 #ifdef VDBE_PROFILE
60106   pOp->cycles = 0;
60107   pOp->cnt = 0;
60108 #endif
60109   return i;
60110 }
60111 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
60112   return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
60113 }
60114 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
60115   return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
60116 }
60117 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
60118   return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
60119 }
60120
60121
60122 /*
60123 ** Add an opcode that includes the p4 value as a pointer.
60124 */
60125 SQLITE_PRIVATE int sqlite3VdbeAddOp4(
60126   Vdbe *p,            /* Add the opcode to this VM */
60127   int op,             /* The new opcode */
60128   int p1,             /* The P1 operand */
60129   int p2,             /* The P2 operand */
60130   int p3,             /* The P3 operand */
60131   const char *zP4,    /* The P4 operand */
60132   int p4type          /* P4 operand type */
60133 ){
60134   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
60135   sqlite3VdbeChangeP4(p, addr, zP4, p4type);
60136   return addr;
60137 }
60138
60139 /*
60140 ** Add an OP_ParseSchema opcode.  This routine is broken out from
60141 ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
60142 ** as having been used.
60143 **
60144 ** The zWhere string must have been obtained from sqlite3_malloc().
60145 ** This routine will take ownership of the allocated memory.
60146 */
60147 SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
60148   int j;
60149   int addr = sqlite3VdbeAddOp3(p, OP_ParseSchema, iDb, 0, 0);
60150   sqlite3VdbeChangeP4(p, addr, zWhere, P4_DYNAMIC);
60151   for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
60152 }
60153
60154 /*
60155 ** Add an opcode that includes the p4 value as an integer.
60156 */
60157 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
60158   Vdbe *p,            /* Add the opcode to this VM */
60159   int op,             /* The new opcode */
60160   int p1,             /* The P1 operand */
60161   int p2,             /* The P2 operand */
60162   int p3,             /* The P3 operand */
60163   int p4              /* The P4 operand as an integer */
60164 ){
60165   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
60166   sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
60167   return addr;
60168 }
60169
60170 /*
60171 ** Create a new symbolic label for an instruction that has yet to be
60172 ** coded.  The symbolic label is really just a negative number.  The
60173 ** label can be used as the P2 value of an operation.  Later, when
60174 ** the label is resolved to a specific address, the VDBE will scan
60175 ** through its operation list and change all values of P2 which match
60176 ** the label into the resolved address.
60177 **
60178 ** The VDBE knows that a P2 value is a label because labels are
60179 ** always negative and P2 values are suppose to be non-negative.
60180 ** Hence, a negative P2 value is a label that has yet to be resolved.
60181 **
60182 ** Zero is returned if a malloc() fails.
60183 */
60184 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
60185   int i = p->nLabel++;
60186   assert( p->magic==VDBE_MAGIC_INIT );
60187   if( (i & (i-1))==0 ){
60188     p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel, 
60189                                        (i*2+1)*sizeof(p->aLabel[0]));
60190   }
60191   if( p->aLabel ){
60192     p->aLabel[i] = -1;
60193   }
60194   return -1-i;
60195 }
60196
60197 /*
60198 ** Resolve label "x" to be the address of the next instruction to
60199 ** be inserted.  The parameter "x" must have been obtained from
60200 ** a prior call to sqlite3VdbeMakeLabel().
60201 */
60202 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
60203   int j = -1-x;
60204   assert( p->magic==VDBE_MAGIC_INIT );
60205   assert( j>=0 && j<p->nLabel );
60206   if( p->aLabel ){
60207     p->aLabel[j] = p->nOp;
60208   }
60209 }
60210
60211 /*
60212 ** Mark the VDBE as one that can only be run one time.
60213 */
60214 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
60215   p->runOnlyOnce = 1;
60216 }
60217
60218 #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
60219
60220 /*
60221 ** The following type and function are used to iterate through all opcodes
60222 ** in a Vdbe main program and each of the sub-programs (triggers) it may 
60223 ** invoke directly or indirectly. It should be used as follows:
60224 **
60225 **   Op *pOp;
60226 **   VdbeOpIter sIter;
60227 **
60228 **   memset(&sIter, 0, sizeof(sIter));
60229 **   sIter.v = v;                            // v is of type Vdbe* 
60230 **   while( (pOp = opIterNext(&sIter)) ){
60231 **     // Do something with pOp
60232 **   }
60233 **   sqlite3DbFree(v->db, sIter.apSub);
60234 ** 
60235 */
60236 typedef struct VdbeOpIter VdbeOpIter;
60237 struct VdbeOpIter {
60238   Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
60239   SubProgram **apSub;        /* Array of subprograms */
60240   int nSub;                  /* Number of entries in apSub */
60241   int iAddr;                 /* Address of next instruction to return */
60242   int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
60243 };
60244 static Op *opIterNext(VdbeOpIter *p){
60245   Vdbe *v = p->v;
60246   Op *pRet = 0;
60247   Op *aOp;
60248   int nOp;
60249
60250   if( p->iSub<=p->nSub ){
60251
60252     if( p->iSub==0 ){
60253       aOp = v->aOp;
60254       nOp = v->nOp;
60255     }else{
60256       aOp = p->apSub[p->iSub-1]->aOp;
60257       nOp = p->apSub[p->iSub-1]->nOp;
60258     }
60259     assert( p->iAddr<nOp );
60260
60261     pRet = &aOp[p->iAddr];
60262     p->iAddr++;
60263     if( p->iAddr==nOp ){
60264       p->iSub++;
60265       p->iAddr = 0;
60266     }
60267   
60268     if( pRet->p4type==P4_SUBPROGRAM ){
60269       int nByte = (p->nSub+1)*sizeof(SubProgram*);
60270       int j;
60271       for(j=0; j<p->nSub; j++){
60272         if( p->apSub[j]==pRet->p4.pProgram ) break;
60273       }
60274       if( j==p->nSub ){
60275         p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
60276         if( !p->apSub ){
60277           pRet = 0;
60278         }else{
60279           p->apSub[p->nSub++] = pRet->p4.pProgram;
60280         }
60281       }
60282     }
60283   }
60284
60285   return pRet;
60286 }
60287
60288 /*
60289 ** Check if the program stored in the VM associated with pParse may
60290 ** throw an ABORT exception (causing the statement, but not entire transaction
60291 ** to be rolled back). This condition is true if the main program or any
60292 ** sub-programs contains any of the following:
60293 **
60294 **   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
60295 **   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
60296 **   *  OP_Destroy
60297 **   *  OP_VUpdate
60298 **   *  OP_VRename
60299 **   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
60300 **
60301 ** Then check that the value of Parse.mayAbort is true if an
60302 ** ABORT may be thrown, or false otherwise. Return true if it does
60303 ** match, or false otherwise. This function is intended to be used as
60304 ** part of an assert statement in the compiler. Similar to:
60305 **
60306 **   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
60307 */
60308 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
60309   int hasAbort = 0;
60310   Op *pOp;
60311   VdbeOpIter sIter;
60312   memset(&sIter, 0, sizeof(sIter));
60313   sIter.v = v;
60314
60315   while( (pOp = opIterNext(&sIter))!=0 ){
60316     int opcode = pOp->opcode;
60317     if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename 
60318 #ifndef SQLITE_OMIT_FOREIGN_KEY
60319      || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1) 
60320 #endif
60321      || ((opcode==OP_Halt || opcode==OP_HaltIfNull) 
60322       && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
60323     ){
60324       hasAbort = 1;
60325       break;
60326     }
60327   }
60328   sqlite3DbFree(v->db, sIter.apSub);
60329
60330   /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
60331   ** If malloc failed, then the while() loop above may not have iterated
60332   ** through all opcodes and hasAbort may be set incorrectly. Return
60333   ** true for this case to prevent the assert() in the callers frame
60334   ** from failing.  */
60335   return ( v->db->mallocFailed || hasAbort==mayAbort );
60336 }
60337 #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
60338
60339 /*
60340 ** Loop through the program looking for P2 values that are negative
60341 ** on jump instructions.  Each such value is a label.  Resolve the
60342 ** label by setting the P2 value to its correct non-zero value.
60343 **
60344 ** This routine is called once after all opcodes have been inserted.
60345 **
60346 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument 
60347 ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by 
60348 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
60349 **
60350 ** The Op.opflags field is set on all opcodes.
60351 */
60352 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
60353   int i;
60354   int nMaxArgs = *pMaxFuncArgs;
60355   Op *pOp;
60356   int *aLabel = p->aLabel;
60357   p->readOnly = 1;
60358   for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
60359     u8 opcode = pOp->opcode;
60360
60361     pOp->opflags = sqlite3OpcodeProperty[opcode];
60362     if( opcode==OP_Function || opcode==OP_AggStep ){
60363       if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
60364     }else if( (opcode==OP_Transaction && pOp->p2!=0) || opcode==OP_Vacuum ){
60365       p->readOnly = 0;
60366 #ifndef SQLITE_OMIT_VIRTUALTABLE
60367     }else if( opcode==OP_VUpdate ){
60368       if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
60369     }else if( opcode==OP_VFilter ){
60370       int n;
60371       assert( p->nOp - i >= 3 );
60372       assert( pOp[-1].opcode==OP_Integer );
60373       n = pOp[-1].p1;
60374       if( n>nMaxArgs ) nMaxArgs = n;
60375 #endif
60376     }else if( opcode==OP_Next || opcode==OP_SorterNext ){
60377       pOp->p4.xAdvance = sqlite3BtreeNext;
60378       pOp->p4type = P4_ADVANCE;
60379     }else if( opcode==OP_Prev ){
60380       pOp->p4.xAdvance = sqlite3BtreePrevious;
60381       pOp->p4type = P4_ADVANCE;
60382     }
60383
60384     if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
60385       assert( -1-pOp->p2<p->nLabel );
60386       pOp->p2 = aLabel[-1-pOp->p2];
60387     }
60388   }
60389   sqlite3DbFree(p->db, p->aLabel);
60390   p->aLabel = 0;
60391
60392   *pMaxFuncArgs = nMaxArgs;
60393 }
60394
60395 /*
60396 ** Return the address of the next instruction to be inserted.
60397 */
60398 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
60399   assert( p->magic==VDBE_MAGIC_INIT );
60400   return p->nOp;
60401 }
60402
60403 /*
60404 ** This function returns a pointer to the array of opcodes associated with
60405 ** the Vdbe passed as the first argument. It is the callers responsibility
60406 ** to arrange for the returned array to be eventually freed using the 
60407 ** vdbeFreeOpArray() function.
60408 **
60409 ** Before returning, *pnOp is set to the number of entries in the returned
60410 ** array. Also, *pnMaxArg is set to the larger of its current value and 
60411 ** the number of entries in the Vdbe.apArg[] array required to execute the 
60412 ** returned program.
60413 */
60414 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
60415   VdbeOp *aOp = p->aOp;
60416   assert( aOp && !p->db->mallocFailed );
60417
60418   /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
60419   assert( p->btreeMask==0 );
60420
60421   resolveP2Values(p, pnMaxArg);
60422   *pnOp = p->nOp;
60423   p->aOp = 0;
60424   return aOp;
60425 }
60426
60427 /*
60428 ** Add a whole list of operations to the operation stack.  Return the
60429 ** address of the first operation added.
60430 */
60431 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
60432   int addr;
60433   assert( p->magic==VDBE_MAGIC_INIT );
60434   if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
60435     return 0;
60436   }
60437   addr = p->nOp;
60438   if( ALWAYS(nOp>0) ){
60439     int i;
60440     VdbeOpList const *pIn = aOp;
60441     for(i=0; i<nOp; i++, pIn++){
60442       int p2 = pIn->p2;
60443       VdbeOp *pOut = &p->aOp[i+addr];
60444       pOut->opcode = pIn->opcode;
60445       pOut->p1 = pIn->p1;
60446       if( p2<0 && (sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP)!=0 ){
60447         pOut->p2 = addr + ADDR(p2);
60448       }else{
60449         pOut->p2 = p2;
60450       }
60451       pOut->p3 = pIn->p3;
60452       pOut->p4type = P4_NOTUSED;
60453       pOut->p4.p = 0;
60454       pOut->p5 = 0;
60455 #ifdef SQLITE_DEBUG
60456       pOut->zComment = 0;
60457       if( p->db->flags & SQLITE_VdbeAddopTrace ){
60458         sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
60459       }
60460 #endif
60461     }
60462     p->nOp += nOp;
60463   }
60464   return addr;
60465 }
60466
60467 /*
60468 ** Change the value of the P1 operand for a specific instruction.
60469 ** This routine is useful when a large program is loaded from a
60470 ** static array using sqlite3VdbeAddOpList but we want to make a
60471 ** few minor changes to the program.
60472 */
60473 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
60474   assert( p!=0 );
60475   if( ((u32)p->nOp)>addr ){
60476     p->aOp[addr].p1 = val;
60477   }
60478 }
60479
60480 /*
60481 ** Change the value of the P2 operand for a specific instruction.
60482 ** This routine is useful for setting a jump destination.
60483 */
60484 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
60485   assert( p!=0 );
60486   if( ((u32)p->nOp)>addr ){
60487     p->aOp[addr].p2 = val;
60488   }
60489 }
60490
60491 /*
60492 ** Change the value of the P3 operand for a specific instruction.
60493 */
60494 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
60495   assert( p!=0 );
60496   if( ((u32)p->nOp)>addr ){
60497     p->aOp[addr].p3 = val;
60498   }
60499 }
60500
60501 /*
60502 ** Change the value of the P5 operand for the most recently
60503 ** added operation.
60504 */
60505 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
60506   assert( p!=0 );
60507   if( p->aOp ){
60508     assert( p->nOp>0 );
60509     p->aOp[p->nOp-1].p5 = val;
60510   }
60511 }
60512
60513 /*
60514 ** Change the P2 operand of instruction addr so that it points to
60515 ** the address of the next instruction to be coded.
60516 */
60517 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
60518   assert( addr>=0 || p->db->mallocFailed );
60519   if( addr>=0 ) sqlite3VdbeChangeP2(p, addr, p->nOp);
60520 }
60521
60522
60523 /*
60524 ** If the input FuncDef structure is ephemeral, then free it.  If
60525 ** the FuncDef is not ephermal, then do nothing.
60526 */
60527 static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
60528   if( ALWAYS(pDef) && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
60529     sqlite3DbFree(db, pDef);
60530   }
60531 }
60532
60533 static void vdbeFreeOpArray(sqlite3 *, Op *, int);
60534
60535 /*
60536 ** Delete a P4 value if necessary.
60537 */
60538 static void freeP4(sqlite3 *db, int p4type, void *p4){
60539   if( p4 ){
60540     assert( db );
60541     switch( p4type ){
60542       case P4_REAL:
60543       case P4_INT64:
60544       case P4_DYNAMIC:
60545       case P4_KEYINFO:
60546       case P4_INTARRAY:
60547       case P4_KEYINFO_HANDOFF: {
60548         sqlite3DbFree(db, p4);
60549         break;
60550       }
60551       case P4_MPRINTF: {
60552         if( db->pnBytesFreed==0 ) sqlite3_free(p4);
60553         break;
60554       }
60555       case P4_VDBEFUNC: {
60556         VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
60557         freeEphemeralFunction(db, pVdbeFunc->pFunc);
60558         if( db->pnBytesFreed==0 ) sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
60559         sqlite3DbFree(db, pVdbeFunc);
60560         break;
60561       }
60562       case P4_FUNCDEF: {
60563         freeEphemeralFunction(db, (FuncDef*)p4);
60564         break;
60565       }
60566       case P4_MEM: {
60567         if( db->pnBytesFreed==0 ){
60568           sqlite3ValueFree((sqlite3_value*)p4);
60569         }else{
60570           Mem *p = (Mem*)p4;
60571           sqlite3DbFree(db, p->zMalloc);
60572           sqlite3DbFree(db, p);
60573         }
60574         break;
60575       }
60576       case P4_VTAB : {
60577         if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
60578         break;
60579       }
60580     }
60581   }
60582 }
60583
60584 /*
60585 ** Free the space allocated for aOp and any p4 values allocated for the
60586 ** opcodes contained within. If aOp is not NULL it is assumed to contain 
60587 ** nOp entries. 
60588 */
60589 static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
60590   if( aOp ){
60591     Op *pOp;
60592     for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
60593       freeP4(db, pOp->p4type, pOp->p4.p);
60594 #ifdef SQLITE_DEBUG
60595       sqlite3DbFree(db, pOp->zComment);
60596 #endif     
60597     }
60598   }
60599   sqlite3DbFree(db, aOp);
60600 }
60601
60602 /*
60603 ** Link the SubProgram object passed as the second argument into the linked
60604 ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
60605 ** objects when the VM is no longer required.
60606 */
60607 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
60608   p->pNext = pVdbe->pProgram;
60609   pVdbe->pProgram = p;
60610 }
60611
60612 /*
60613 ** Change the opcode at addr into OP_Noop
60614 */
60615 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
60616   if( p->aOp ){
60617     VdbeOp *pOp = &p->aOp[addr];
60618     sqlite3 *db = p->db;
60619     freeP4(db, pOp->p4type, pOp->p4.p);
60620     memset(pOp, 0, sizeof(pOp[0]));
60621     pOp->opcode = OP_Noop;
60622   }
60623 }
60624
60625 /*
60626 ** Change the value of the P4 operand for a specific instruction.
60627 ** This routine is useful when a large program is loaded from a
60628 ** static array using sqlite3VdbeAddOpList but we want to make a
60629 ** few minor changes to the program.
60630 **
60631 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
60632 ** the string is made into memory obtained from sqlite3_malloc().
60633 ** A value of n==0 means copy bytes of zP4 up to and including the
60634 ** first null byte.  If n>0 then copy n+1 bytes of zP4.
60635 **
60636 ** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
60637 ** A copy is made of the KeyInfo structure into memory obtained from
60638 ** sqlite3_malloc, to be freed when the Vdbe is finalized.
60639 ** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
60640 ** stored in memory that the caller has obtained from sqlite3_malloc. The 
60641 ** caller should not free the allocation, it will be freed when the Vdbe is
60642 ** finalized.
60643 ** 
60644 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
60645 ** to a string or structure that is guaranteed to exist for the lifetime of
60646 ** the Vdbe. In these cases we can just copy the pointer.
60647 **
60648 ** If addr<0 then change P4 on the most recently inserted instruction.
60649 */
60650 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
60651   Op *pOp;
60652   sqlite3 *db;
60653   assert( p!=0 );
60654   db = p->db;
60655   assert( p->magic==VDBE_MAGIC_INIT );
60656   if( p->aOp==0 || db->mallocFailed ){
60657     if ( n!=P4_KEYINFO && n!=P4_VTAB ) {
60658       freeP4(db, n, (void*)*(char**)&zP4);
60659     }
60660     return;
60661   }
60662   assert( p->nOp>0 );
60663   assert( addr<p->nOp );
60664   if( addr<0 ){
60665     addr = p->nOp - 1;
60666   }
60667   pOp = &p->aOp[addr];
60668   assert( pOp->p4type==P4_NOTUSED || pOp->p4type==P4_INT32 );
60669   freeP4(db, pOp->p4type, pOp->p4.p);
60670   pOp->p4.p = 0;
60671   if( n==P4_INT32 ){
60672     /* Note: this cast is safe, because the origin data point was an int
60673     ** that was cast to a (const char *). */
60674     pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
60675     pOp->p4type = P4_INT32;
60676   }else if( zP4==0 ){
60677     pOp->p4.p = 0;
60678     pOp->p4type = P4_NOTUSED;
60679   }else if( n==P4_KEYINFO ){
60680     KeyInfo *pKeyInfo;
60681     int nField, nByte;
60682
60683     nField = ((KeyInfo*)zP4)->nField;
60684     nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
60685     pKeyInfo = sqlite3DbMallocRaw(0, nByte);
60686     pOp->p4.pKeyInfo = pKeyInfo;
60687     if( pKeyInfo ){
60688       u8 *aSortOrder;
60689       memcpy((char*)pKeyInfo, zP4, nByte - nField);
60690       aSortOrder = pKeyInfo->aSortOrder;
60691       assert( aSortOrder!=0 );
60692       pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
60693       memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
60694       pOp->p4type = P4_KEYINFO;
60695     }else{
60696       p->db->mallocFailed = 1;
60697       pOp->p4type = P4_NOTUSED;
60698     }
60699   }else if( n==P4_KEYINFO_HANDOFF ){
60700     pOp->p4.p = (void*)zP4;
60701     pOp->p4type = P4_KEYINFO;
60702   }else if( n==P4_VTAB ){
60703     pOp->p4.p = (void*)zP4;
60704     pOp->p4type = P4_VTAB;
60705     sqlite3VtabLock((VTable *)zP4);
60706     assert( ((VTable *)zP4)->db==p->db );
60707   }else if( n<0 ){
60708     pOp->p4.p = (void*)zP4;
60709     pOp->p4type = (signed char)n;
60710   }else{
60711     if( n==0 ) n = sqlite3Strlen30(zP4);
60712     pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
60713     pOp->p4type = P4_DYNAMIC;
60714   }
60715 }
60716
60717 #ifndef NDEBUG
60718 /*
60719 ** Change the comment on the most recently coded instruction.  Or
60720 ** insert a No-op and add the comment to that new instruction.  This
60721 ** makes the code easier to read during debugging.  None of this happens
60722 ** in a production build.
60723 */
60724 static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
60725   assert( p->nOp>0 || p->aOp==0 );
60726   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
60727   if( p->nOp ){
60728     assert( p->aOp );
60729     sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
60730     p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
60731   }
60732 }
60733 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
60734   va_list ap;
60735   if( p ){
60736     va_start(ap, zFormat);
60737     vdbeVComment(p, zFormat, ap);
60738     va_end(ap);
60739   }
60740 }
60741 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
60742   va_list ap;
60743   if( p ){
60744     sqlite3VdbeAddOp0(p, OP_Noop);
60745     va_start(ap, zFormat);
60746     vdbeVComment(p, zFormat, ap);
60747     va_end(ap);
60748   }
60749 }
60750 #endif  /* NDEBUG */
60751
60752 /*
60753 ** Return the opcode for a given address.  If the address is -1, then
60754 ** return the most recently inserted opcode.
60755 **
60756 ** If a memory allocation error has occurred prior to the calling of this
60757 ** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
60758 ** is readable but not writable, though it is cast to a writable value.
60759 ** The return of a dummy opcode allows the call to continue functioning
60760 ** after a OOM fault without having to check to see if the return from 
60761 ** this routine is a valid pointer.  But because the dummy.opcode is 0,
60762 ** dummy will never be written to.  This is verified by code inspection and
60763 ** by running with Valgrind.
60764 **
60765 ** About the #ifdef SQLITE_OMIT_TRACE:  Normally, this routine is never called
60766 ** unless p->nOp>0.  This is because in the absense of SQLITE_OMIT_TRACE,
60767 ** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as
60768 ** a new VDBE is created.  So we are free to set addr to p->nOp-1 without
60769 ** having to double-check to make sure that the result is non-negative. But
60770 ** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
60771 ** check the value of p->nOp-1 before continuing.
60772 */
60773 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
60774   /* C89 specifies that the constant "dummy" will be initialized to all
60775   ** zeros, which is correct.  MSVC generates a warning, nevertheless. */
60776   static VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */
60777   assert( p->magic==VDBE_MAGIC_INIT );
60778   if( addr<0 ){
60779 #ifdef SQLITE_OMIT_TRACE
60780     if( p->nOp==0 ) return (VdbeOp*)&dummy;
60781 #endif
60782     addr = p->nOp - 1;
60783   }
60784   assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
60785   if( p->db->mallocFailed ){
60786     return (VdbeOp*)&dummy;
60787   }else{
60788     return &p->aOp[addr];
60789   }
60790 }
60791
60792 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
60793      || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
60794 /*
60795 ** Compute a string that describes the P4 parameter for an opcode.
60796 ** Use zTemp for any required temporary buffer space.
60797 */
60798 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
60799   char *zP4 = zTemp;
60800   assert( nTemp>=20 );
60801   switch( pOp->p4type ){
60802     case P4_KEYINFO_STATIC:
60803     case P4_KEYINFO: {
60804       int i, j;
60805       KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
60806       assert( pKeyInfo->aSortOrder!=0 );
60807       sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
60808       i = sqlite3Strlen30(zTemp);
60809       for(j=0; j<pKeyInfo->nField; j++){
60810         CollSeq *pColl = pKeyInfo->aColl[j];
60811         const char *zColl = pColl ? pColl->zName : "nil";
60812         int n = sqlite3Strlen30(zColl);
60813         if( i+n>nTemp-6 ){
60814           memcpy(&zTemp[i],",...",4);
60815           break;
60816         }
60817         zTemp[i++] = ',';
60818         if( pKeyInfo->aSortOrder[j] ){
60819           zTemp[i++] = '-';
60820         }
60821         memcpy(&zTemp[i], zColl, n+1);
60822         i += n;
60823       }
60824       zTemp[i++] = ')';
60825       zTemp[i] = 0;
60826       assert( i<nTemp );
60827       break;
60828     }
60829     case P4_COLLSEQ: {
60830       CollSeq *pColl = pOp->p4.pColl;
60831       sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
60832       break;
60833     }
60834     case P4_FUNCDEF: {
60835       FuncDef *pDef = pOp->p4.pFunc;
60836       sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
60837       break;
60838     }
60839     case P4_INT64: {
60840       sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
60841       break;
60842     }
60843     case P4_INT32: {
60844       sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
60845       break;
60846     }
60847     case P4_REAL: {
60848       sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
60849       break;
60850     }
60851     case P4_MEM: {
60852       Mem *pMem = pOp->p4.pMem;
60853       if( pMem->flags & MEM_Str ){
60854         zP4 = pMem->z;
60855       }else if( pMem->flags & MEM_Int ){
60856         sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
60857       }else if( pMem->flags & MEM_Real ){
60858         sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
60859       }else if( pMem->flags & MEM_Null ){
60860         sqlite3_snprintf(nTemp, zTemp, "NULL");
60861       }else{
60862         assert( pMem->flags & MEM_Blob );
60863         zP4 = "(blob)";
60864       }
60865       break;
60866     }
60867 #ifndef SQLITE_OMIT_VIRTUALTABLE
60868     case P4_VTAB: {
60869       sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
60870       sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
60871       break;
60872     }
60873 #endif
60874     case P4_INTARRAY: {
60875       sqlite3_snprintf(nTemp, zTemp, "intarray");
60876       break;
60877     }
60878     case P4_SUBPROGRAM: {
60879       sqlite3_snprintf(nTemp, zTemp, "program");
60880       break;
60881     }
60882     case P4_ADVANCE: {
60883       zTemp[0] = 0;
60884       break;
60885     }
60886     default: {
60887       zP4 = pOp->p4.z;
60888       if( zP4==0 ){
60889         zP4 = zTemp;
60890         zTemp[0] = 0;
60891       }
60892     }
60893   }
60894   assert( zP4!=0 );
60895   return zP4;
60896 }
60897 #endif
60898
60899 /*
60900 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
60901 **
60902 ** The prepared statements need to know in advance the complete set of
60903 ** attached databases that will be use.  A mask of these databases
60904 ** is maintained in p->btreeMask.  The p->lockMask value is the subset of
60905 ** p->btreeMask of databases that will require a lock.
60906 */
60907 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
60908   assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
60909   assert( i<(int)sizeof(p->btreeMask)*8 );
60910   p->btreeMask |= ((yDbMask)1)<<i;
60911   if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
60912     p->lockMask |= ((yDbMask)1)<<i;
60913   }
60914 }
60915
60916 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
60917 /*
60918 ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
60919 ** this routine obtains the mutex associated with each BtShared structure
60920 ** that may be accessed by the VM passed as an argument. In doing so it also
60921 ** sets the BtShared.db member of each of the BtShared structures, ensuring
60922 ** that the correct busy-handler callback is invoked if required.
60923 **
60924 ** If SQLite is not threadsafe but does support shared-cache mode, then
60925 ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
60926 ** of all of BtShared structures accessible via the database handle 
60927 ** associated with the VM.
60928 **
60929 ** If SQLite is not threadsafe and does not support shared-cache mode, this
60930 ** function is a no-op.
60931 **
60932 ** The p->btreeMask field is a bitmask of all btrees that the prepared 
60933 ** statement p will ever use.  Let N be the number of bits in p->btreeMask
60934 ** corresponding to btrees that use shared cache.  Then the runtime of
60935 ** this routine is N*N.  But as N is rarely more than 1, this should not
60936 ** be a problem.
60937 */
60938 SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
60939   int i;
60940   yDbMask mask;
60941   sqlite3 *db;
60942   Db *aDb;
60943   int nDb;
60944   if( p->lockMask==0 ) return;  /* The common case */
60945   db = p->db;
60946   aDb = db->aDb;
60947   nDb = db->nDb;
60948   for(i=0, mask=1; i<nDb; i++, mask += mask){
60949     if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
60950       sqlite3BtreeEnter(aDb[i].pBt);
60951     }
60952   }
60953 }
60954 #endif
60955
60956 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
60957 /*
60958 ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
60959 */
60960 SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
60961   int i;
60962   yDbMask mask;
60963   sqlite3 *db;
60964   Db *aDb;
60965   int nDb;
60966   if( p->lockMask==0 ) return;  /* The common case */
60967   db = p->db;
60968   aDb = db->aDb;
60969   nDb = db->nDb;
60970   for(i=0, mask=1; i<nDb; i++, mask += mask){
60971     if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
60972       sqlite3BtreeLeave(aDb[i].pBt);
60973     }
60974   }
60975 }
60976 #endif
60977
60978 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
60979 /*
60980 ** Print a single opcode.  This routine is used for debugging only.
60981 */
60982 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
60983   char *zP4;
60984   char zPtr[50];
60985   static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
60986   if( pOut==0 ) pOut = stdout;
60987   zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
60988   fprintf(pOut, zFormat1, pc, 
60989       sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
60990 #ifdef SQLITE_DEBUG
60991       pOp->zComment ? pOp->zComment : ""
60992 #else
60993       ""
60994 #endif
60995   );
60996   fflush(pOut);
60997 }
60998 #endif
60999
61000 /*
61001 ** Release an array of N Mem elements
61002 */
61003 static void releaseMemArray(Mem *p, int N){
61004   if( p && N ){
61005     Mem *pEnd;
61006     sqlite3 *db = p->db;
61007     u8 malloc_failed = db->mallocFailed;
61008     if( db->pnBytesFreed ){
61009       for(pEnd=&p[N]; p<pEnd; p++){
61010         sqlite3DbFree(db, p->zMalloc);
61011       }
61012       return;
61013     }
61014     for(pEnd=&p[N]; p<pEnd; p++){
61015       assert( (&p[1])==pEnd || p[0].db==p[1].db );
61016
61017       /* This block is really an inlined version of sqlite3VdbeMemRelease()
61018       ** that takes advantage of the fact that the memory cell value is 
61019       ** being set to NULL after releasing any dynamic resources.
61020       **
61021       ** The justification for duplicating code is that according to 
61022       ** callgrind, this causes a certain test case to hit the CPU 4.7 
61023       ** percent less (x86 linux, gcc version 4.1.2, -O6) than if 
61024       ** sqlite3MemRelease() were called from here. With -O2, this jumps
61025       ** to 6.6 percent. The test case is inserting 1000 rows into a table 
61026       ** with no indexes using a single prepared INSERT statement, bind() 
61027       ** and reset(). Inserts are grouped into a transaction.
61028       */
61029       if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
61030         sqlite3VdbeMemRelease(p);
61031       }else if( p->zMalloc ){
61032         sqlite3DbFree(db, p->zMalloc);
61033         p->zMalloc = 0;
61034       }
61035
61036       p->flags = MEM_Invalid;
61037     }
61038     db->mallocFailed = malloc_failed;
61039   }
61040 }
61041
61042 /*
61043 ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
61044 ** allocated by the OP_Program opcode in sqlite3VdbeExec().
61045 */
61046 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
61047   int i;
61048   Mem *aMem = VdbeFrameMem(p);
61049   VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
61050   for(i=0; i<p->nChildCsr; i++){
61051     sqlite3VdbeFreeCursor(p->v, apCsr[i]);
61052   }
61053   releaseMemArray(aMem, p->nChildMem);
61054   sqlite3DbFree(p->v->db, p);
61055 }
61056
61057 #ifndef SQLITE_OMIT_EXPLAIN
61058 /*
61059 ** Give a listing of the program in the virtual machine.
61060 **
61061 ** The interface is the same as sqlite3VdbeExec().  But instead of
61062 ** running the code, it invokes the callback once for each instruction.
61063 ** This feature is used to implement "EXPLAIN".
61064 **
61065 ** When p->explain==1, each instruction is listed.  When
61066 ** p->explain==2, only OP_Explain instructions are listed and these
61067 ** are shown in a different format.  p->explain==2 is used to implement
61068 ** EXPLAIN QUERY PLAN.
61069 **
61070 ** When p->explain==1, first the main program is listed, then each of
61071 ** the trigger subprograms are listed one by one.
61072 */
61073 SQLITE_PRIVATE int sqlite3VdbeList(
61074   Vdbe *p                   /* The VDBE */
61075 ){
61076   int nRow;                            /* Stop when row count reaches this */
61077   int nSub = 0;                        /* Number of sub-vdbes seen so far */
61078   SubProgram **apSub = 0;              /* Array of sub-vdbes */
61079   Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
61080   sqlite3 *db = p->db;                 /* The database connection */
61081   int i;                               /* Loop counter */
61082   int rc = SQLITE_OK;                  /* Return code */
61083   Mem *pMem = &p->aMem[1];             /* First Mem of result set */
61084
61085   assert( p->explain );
61086   assert( p->magic==VDBE_MAGIC_RUN );
61087   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
61088
61089   /* Even though this opcode does not use dynamic strings for
61090   ** the result, result columns may become dynamic if the user calls
61091   ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
61092   */
61093   releaseMemArray(pMem, 8);
61094   p->pResultSet = 0;
61095
61096   if( p->rc==SQLITE_NOMEM ){
61097     /* This happens if a malloc() inside a call to sqlite3_column_text() or
61098     ** sqlite3_column_text16() failed.  */
61099     db->mallocFailed = 1;
61100     return SQLITE_ERROR;
61101   }
61102
61103   /* When the number of output rows reaches nRow, that means the
61104   ** listing has finished and sqlite3_step() should return SQLITE_DONE.
61105   ** nRow is the sum of the number of rows in the main program, plus
61106   ** the sum of the number of rows in all trigger subprograms encountered
61107   ** so far.  The nRow value will increase as new trigger subprograms are
61108   ** encountered, but p->pc will eventually catch up to nRow.
61109   */
61110   nRow = p->nOp;
61111   if( p->explain==1 ){
61112     /* The first 8 memory cells are used for the result set.  So we will
61113     ** commandeer the 9th cell to use as storage for an array of pointers
61114     ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
61115     ** cells.  */
61116     assert( p->nMem>9 );
61117     pSub = &p->aMem[9];
61118     if( pSub->flags&MEM_Blob ){
61119       /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
61120       ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
61121       nSub = pSub->n/sizeof(Vdbe*);
61122       apSub = (SubProgram **)pSub->z;
61123     }
61124     for(i=0; i<nSub; i++){
61125       nRow += apSub[i]->nOp;
61126     }
61127   }
61128
61129   do{
61130     i = p->pc++;
61131   }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
61132   if( i>=nRow ){
61133     p->rc = SQLITE_OK;
61134     rc = SQLITE_DONE;
61135   }else if( db->u1.isInterrupted ){
61136     p->rc = SQLITE_INTERRUPT;
61137     rc = SQLITE_ERROR;
61138     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
61139   }else{
61140     char *z;
61141     Op *pOp;
61142     if( i<p->nOp ){
61143       /* The output line number is small enough that we are still in the
61144       ** main program. */
61145       pOp = &p->aOp[i];
61146     }else{
61147       /* We are currently listing subprograms.  Figure out which one and
61148       ** pick up the appropriate opcode. */
61149       int j;
61150       i -= p->nOp;
61151       for(j=0; i>=apSub[j]->nOp; j++){
61152         i -= apSub[j]->nOp;
61153       }
61154       pOp = &apSub[j]->aOp[i];
61155     }
61156     if( p->explain==1 ){
61157       pMem->flags = MEM_Int;
61158       pMem->type = SQLITE_INTEGER;
61159       pMem->u.i = i;                                /* Program counter */
61160       pMem++;
61161   
61162       pMem->flags = MEM_Static|MEM_Str|MEM_Term;
61163       pMem->z = (char*)sqlite3OpcodeName(pOp->opcode);  /* Opcode */
61164       assert( pMem->z!=0 );
61165       pMem->n = sqlite3Strlen30(pMem->z);
61166       pMem->type = SQLITE_TEXT;
61167       pMem->enc = SQLITE_UTF8;
61168       pMem++;
61169
61170       /* When an OP_Program opcode is encounter (the only opcode that has
61171       ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
61172       ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
61173       ** has not already been seen.
61174       */
61175       if( pOp->p4type==P4_SUBPROGRAM ){
61176         int nByte = (nSub+1)*sizeof(SubProgram*);
61177         int j;
61178         for(j=0; j<nSub; j++){
61179           if( apSub[j]==pOp->p4.pProgram ) break;
61180         }
61181         if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
61182           apSub = (SubProgram **)pSub->z;
61183           apSub[nSub++] = pOp->p4.pProgram;
61184           pSub->flags |= MEM_Blob;
61185           pSub->n = nSub*sizeof(SubProgram*);
61186         }
61187       }
61188     }
61189
61190     pMem->flags = MEM_Int;
61191     pMem->u.i = pOp->p1;                          /* P1 */
61192     pMem->type = SQLITE_INTEGER;
61193     pMem++;
61194
61195     pMem->flags = MEM_Int;
61196     pMem->u.i = pOp->p2;                          /* P2 */
61197     pMem->type = SQLITE_INTEGER;
61198     pMem++;
61199
61200     pMem->flags = MEM_Int;
61201     pMem->u.i = pOp->p3;                          /* P3 */
61202     pMem->type = SQLITE_INTEGER;
61203     pMem++;
61204
61205     if( sqlite3VdbeMemGrow(pMem, 32, 0) ){            /* P4 */
61206       assert( p->db->mallocFailed );
61207       return SQLITE_ERROR;
61208     }
61209     pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
61210     z = displayP4(pOp, pMem->z, 32);
61211     if( z!=pMem->z ){
61212       sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
61213     }else{
61214       assert( pMem->z!=0 );
61215       pMem->n = sqlite3Strlen30(pMem->z);
61216       pMem->enc = SQLITE_UTF8;
61217     }
61218     pMem->type = SQLITE_TEXT;
61219     pMem++;
61220
61221     if( p->explain==1 ){
61222       if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
61223         assert( p->db->mallocFailed );
61224         return SQLITE_ERROR;
61225       }
61226       pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
61227       pMem->n = 2;
61228       sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
61229       pMem->type = SQLITE_TEXT;
61230       pMem->enc = SQLITE_UTF8;
61231       pMem++;
61232   
61233 #ifdef SQLITE_DEBUG
61234       if( pOp->zComment ){
61235         pMem->flags = MEM_Str|MEM_Term;
61236         pMem->z = pOp->zComment;
61237         pMem->n = sqlite3Strlen30(pMem->z);
61238         pMem->enc = SQLITE_UTF8;
61239         pMem->type = SQLITE_TEXT;
61240       }else
61241 #endif
61242       {
61243         pMem->flags = MEM_Null;                       /* Comment */
61244         pMem->type = SQLITE_NULL;
61245       }
61246     }
61247
61248     p->nResColumn = 8 - 4*(p->explain-1);
61249     p->pResultSet = &p->aMem[1];
61250     p->rc = SQLITE_OK;
61251     rc = SQLITE_ROW;
61252   }
61253   return rc;
61254 }
61255 #endif /* SQLITE_OMIT_EXPLAIN */
61256
61257 #ifdef SQLITE_DEBUG
61258 /*
61259 ** Print the SQL that was used to generate a VDBE program.
61260 */
61261 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
61262   int nOp = p->nOp;
61263   VdbeOp *pOp;
61264   if( nOp<1 ) return;
61265   pOp = &p->aOp[0];
61266   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
61267     const char *z = pOp->p4.z;
61268     while( sqlite3Isspace(*z) ) z++;
61269     printf("SQL: [%s]\n", z);
61270   }
61271 }
61272 #endif
61273
61274 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
61275 /*
61276 ** Print an IOTRACE message showing SQL content.
61277 */
61278 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
61279   int nOp = p->nOp;
61280   VdbeOp *pOp;
61281   if( sqlite3IoTrace==0 ) return;
61282   if( nOp<1 ) return;
61283   pOp = &p->aOp[0];
61284   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
61285     int i, j;
61286     char z[1000];
61287     sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
61288     for(i=0; sqlite3Isspace(z[i]); i++){}
61289     for(j=0; z[i]; i++){
61290       if( sqlite3Isspace(z[i]) ){
61291         if( z[i-1]!=' ' ){
61292           z[j++] = ' ';
61293         }
61294       }else{
61295         z[j++] = z[i];
61296       }
61297     }
61298     z[j] = 0;
61299     sqlite3IoTrace("SQL %s\n", z);
61300   }
61301 }
61302 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
61303
61304 /*
61305 ** Allocate space from a fixed size buffer and return a pointer to
61306 ** that space.  If insufficient space is available, return NULL.
61307 **
61308 ** The pBuf parameter is the initial value of a pointer which will
61309 ** receive the new memory.  pBuf is normally NULL.  If pBuf is not
61310 ** NULL, it means that memory space has already been allocated and that
61311 ** this routine should not allocate any new memory.  When pBuf is not
61312 ** NULL simply return pBuf.  Only allocate new memory space when pBuf
61313 ** is NULL.
61314 **
61315 ** nByte is the number of bytes of space needed.
61316 **
61317 ** *ppFrom points to available space and pEnd points to the end of the
61318 ** available space.  When space is allocated, *ppFrom is advanced past
61319 ** the end of the allocated space.
61320 **
61321 ** *pnByte is a counter of the number of bytes of space that have failed
61322 ** to allocate.  If there is insufficient space in *ppFrom to satisfy the
61323 ** request, then increment *pnByte by the amount of the request.
61324 */
61325 static void *allocSpace(
61326   void *pBuf,          /* Where return pointer will be stored */
61327   int nByte,           /* Number of bytes to allocate */
61328   u8 **ppFrom,         /* IN/OUT: Allocate from *ppFrom */
61329   u8 *pEnd,            /* Pointer to 1 byte past the end of *ppFrom buffer */
61330   int *pnByte          /* If allocation cannot be made, increment *pnByte */
61331 ){
61332   assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
61333   if( pBuf ) return pBuf;
61334   nByte = ROUND8(nByte);
61335   if( &(*ppFrom)[nByte] <= pEnd ){
61336     pBuf = (void*)*ppFrom;
61337     *ppFrom += nByte;
61338   }else{
61339     *pnByte += nByte;
61340   }
61341   return pBuf;
61342 }
61343
61344 /*
61345 ** Rewind the VDBE back to the beginning in preparation for
61346 ** running it.
61347 */
61348 SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
61349 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
61350   int i;
61351 #endif
61352   assert( p!=0 );
61353   assert( p->magic==VDBE_MAGIC_INIT );
61354
61355   /* There should be at least one opcode.
61356   */
61357   assert( p->nOp>0 );
61358
61359   /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
61360   p->magic = VDBE_MAGIC_RUN;
61361
61362 #ifdef SQLITE_DEBUG
61363   for(i=1; i<p->nMem; i++){
61364     assert( p->aMem[i].db==p->db );
61365   }
61366 #endif
61367   p->pc = -1;
61368   p->rc = SQLITE_OK;
61369   p->errorAction = OE_Abort;
61370   p->magic = VDBE_MAGIC_RUN;
61371   p->nChange = 0;
61372   p->cacheCtr = 1;
61373   p->minWriteFileFormat = 255;
61374   p->iStatement = 0;
61375   p->nFkConstraint = 0;
61376 #ifdef VDBE_PROFILE
61377   for(i=0; i<p->nOp; i++){
61378     p->aOp[i].cnt = 0;
61379     p->aOp[i].cycles = 0;
61380   }
61381 #endif
61382 }
61383
61384 /*
61385 ** Prepare a virtual machine for execution for the first time after
61386 ** creating the virtual machine.  This involves things such
61387 ** as allocating stack space and initializing the program counter.
61388 ** After the VDBE has be prepped, it can be executed by one or more
61389 ** calls to sqlite3VdbeExec().  
61390 **
61391 ** This function may be called exact once on a each virtual machine.
61392 ** After this routine is called the VM has been "packaged" and is ready
61393 ** to run.  After this routine is called, futher calls to 
61394 ** sqlite3VdbeAddOp() functions are prohibited.  This routine disconnects
61395 ** the Vdbe from the Parse object that helped generate it so that the
61396 ** the Vdbe becomes an independent entity and the Parse object can be
61397 ** destroyed.
61398 **
61399 ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
61400 ** to its initial state after it has been run.
61401 */
61402 SQLITE_PRIVATE void sqlite3VdbeMakeReady(
61403   Vdbe *p,                       /* The VDBE */
61404   Parse *pParse                  /* Parsing context */
61405 ){
61406   sqlite3 *db;                   /* The database connection */
61407   int nVar;                      /* Number of parameters */
61408   int nMem;                      /* Number of VM memory registers */
61409   int nCursor;                   /* Number of cursors required */
61410   int nArg;                      /* Number of arguments in subprograms */
61411   int nOnce;                     /* Number of OP_Once instructions */
61412   int n;                         /* Loop counter */
61413   u8 *zCsr;                      /* Memory available for allocation */
61414   u8 *zEnd;                      /* First byte past allocated memory */
61415   int nByte;                     /* How much extra memory is needed */
61416
61417   assert( p!=0 );
61418   assert( p->nOp>0 );
61419   assert( pParse!=0 );
61420   assert( p->magic==VDBE_MAGIC_INIT );
61421   db = p->db;
61422   assert( db->mallocFailed==0 );
61423   nVar = pParse->nVar;
61424   nMem = pParse->nMem;
61425   nCursor = pParse->nTab;
61426   nArg = pParse->nMaxArg;
61427   nOnce = pParse->nOnce;
61428   if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */
61429   
61430   /* For each cursor required, also allocate a memory cell. Memory
61431   ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
61432   ** the vdbe program. Instead they are used to allocate space for
61433   ** VdbeCursor/BtCursor structures. The blob of memory associated with 
61434   ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
61435   ** stores the blob of memory associated with cursor 1, etc.
61436   **
61437   ** See also: allocateCursor().
61438   */
61439   nMem += nCursor;
61440
61441   /* Allocate space for memory registers, SQL variables, VDBE cursors and 
61442   ** an array to marshal SQL function arguments in.
61443   */
61444   zCsr = (u8*)&p->aOp[p->nOp];       /* Memory avaliable for allocation */
61445   zEnd = (u8*)&p->aOp[p->nOpAlloc];  /* First byte past end of zCsr[] */
61446
61447   resolveP2Values(p, &nArg);
61448   p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
61449   if( pParse->explain && nMem<10 ){
61450     nMem = 10;
61451   }
61452   memset(zCsr, 0, zEnd-zCsr);
61453   zCsr += (zCsr - (u8*)0)&7;
61454   assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
61455   p->expired = 0;
61456
61457   /* Memory for registers, parameters, cursor, etc, is allocated in two
61458   ** passes.  On the first pass, we try to reuse unused space at the 
61459   ** end of the opcode array.  If we are unable to satisfy all memory
61460   ** requirements by reusing the opcode array tail, then the second
61461   ** pass will fill in the rest using a fresh allocation.  
61462   **
61463   ** This two-pass approach that reuses as much memory as possible from
61464   ** the leftover space at the end of the opcode array can significantly
61465   ** reduce the amount of memory held by a prepared statement.
61466   */
61467   do {
61468     nByte = 0;
61469     p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
61470     p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
61471     p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
61472     p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
61473     p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
61474                           &zCsr, zEnd, &nByte);
61475     p->aOnceFlag = allocSpace(p->aOnceFlag, nOnce, &zCsr, zEnd, &nByte);
61476     if( nByte ){
61477       p->pFree = sqlite3DbMallocZero(db, nByte);
61478     }
61479     zCsr = p->pFree;
61480     zEnd = &zCsr[nByte];
61481   }while( nByte && !db->mallocFailed );
61482
61483   p->nCursor = nCursor;
61484   p->nOnceFlag = nOnce;
61485   if( p->aVar ){
61486     p->nVar = (ynVar)nVar;
61487     for(n=0; n<nVar; n++){
61488       p->aVar[n].flags = MEM_Null;
61489       p->aVar[n].db = db;
61490     }
61491   }
61492   if( p->azVar ){
61493     p->nzVar = pParse->nzVar;
61494     memcpy(p->azVar, pParse->azVar, p->nzVar*sizeof(p->azVar[0]));
61495     memset(pParse->azVar, 0, pParse->nzVar*sizeof(pParse->azVar[0]));
61496   }
61497   if( p->aMem ){
61498     p->aMem--;                      /* aMem[] goes from 1..nMem */
61499     p->nMem = nMem;                 /*       not from 0..nMem-1 */
61500     for(n=1; n<=nMem; n++){
61501       p->aMem[n].flags = MEM_Invalid;
61502       p->aMem[n].db = db;
61503     }
61504   }
61505   p->explain = pParse->explain;
61506   sqlite3VdbeRewind(p);
61507 }
61508
61509 /*
61510 ** Close a VDBE cursor and release all the resources that cursor 
61511 ** happens to hold.
61512 */
61513 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
61514   if( pCx==0 ){
61515     return;
61516   }
61517   sqlite3VdbeSorterClose(p->db, pCx);
61518   if( pCx->pBt ){
61519     sqlite3BtreeClose(pCx->pBt);
61520     /* The pCx->pCursor will be close automatically, if it exists, by
61521     ** the call above. */
61522   }else if( pCx->pCursor ){
61523     sqlite3BtreeCloseCursor(pCx->pCursor);
61524   }
61525 #ifndef SQLITE_OMIT_VIRTUALTABLE
61526   if( pCx->pVtabCursor ){
61527     sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
61528     const sqlite3_module *pModule = pCx->pModule;
61529     p->inVtabMethod = 1;
61530     pModule->xClose(pVtabCursor);
61531     p->inVtabMethod = 0;
61532   }
61533 #endif
61534 }
61535
61536 /*
61537 ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
61538 ** is used, for example, when a trigger sub-program is halted to restore
61539 ** control to the main program.
61540 */
61541 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
61542   Vdbe *v = pFrame->v;
61543   v->aOnceFlag = pFrame->aOnceFlag;
61544   v->nOnceFlag = pFrame->nOnceFlag;
61545   v->aOp = pFrame->aOp;
61546   v->nOp = pFrame->nOp;
61547   v->aMem = pFrame->aMem;
61548   v->nMem = pFrame->nMem;
61549   v->apCsr = pFrame->apCsr;
61550   v->nCursor = pFrame->nCursor;
61551   v->db->lastRowid = pFrame->lastRowid;
61552   v->nChange = pFrame->nChange;
61553   return pFrame->pc;
61554 }
61555
61556 /*
61557 ** Close all cursors.
61558 **
61559 ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory 
61560 ** cell array. This is necessary as the memory cell array may contain
61561 ** pointers to VdbeFrame objects, which may in turn contain pointers to
61562 ** open cursors.
61563 */
61564 static void closeAllCursors(Vdbe *p){
61565   if( p->pFrame ){
61566     VdbeFrame *pFrame;
61567     for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
61568     sqlite3VdbeFrameRestore(pFrame);
61569   }
61570   p->pFrame = 0;
61571   p->nFrame = 0;
61572
61573   if( p->apCsr ){
61574     int i;
61575     for(i=0; i<p->nCursor; i++){
61576       VdbeCursor *pC = p->apCsr[i];
61577       if( pC ){
61578         sqlite3VdbeFreeCursor(p, pC);
61579         p->apCsr[i] = 0;
61580       }
61581     }
61582   }
61583   if( p->aMem ){
61584     releaseMemArray(&p->aMem[1], p->nMem);
61585   }
61586   while( p->pDelFrame ){
61587     VdbeFrame *pDel = p->pDelFrame;
61588     p->pDelFrame = pDel->pParent;
61589     sqlite3VdbeFrameDelete(pDel);
61590   }
61591 }
61592
61593 /*
61594 ** Clean up the VM after execution.
61595 **
61596 ** This routine will automatically close any cursors, lists, and/or
61597 ** sorters that were left open.  It also deletes the values of
61598 ** variables in the aVar[] array.
61599 */
61600 static void Cleanup(Vdbe *p){
61601   sqlite3 *db = p->db;
61602
61603 #ifdef SQLITE_DEBUG
61604   /* Execute assert() statements to ensure that the Vdbe.apCsr[] and 
61605   ** Vdbe.aMem[] arrays have already been cleaned up.  */
61606   int i;
61607   if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
61608   if( p->aMem ){
61609     for(i=1; i<=p->nMem; i++) assert( p->aMem[i].flags==MEM_Invalid );
61610   }
61611 #endif
61612
61613   sqlite3DbFree(db, p->zErrMsg);
61614   p->zErrMsg = 0;
61615   p->pResultSet = 0;
61616 }
61617
61618 /*
61619 ** Set the number of result columns that will be returned by this SQL
61620 ** statement. This is now set at compile time, rather than during
61621 ** execution of the vdbe program so that sqlite3_column_count() can
61622 ** be called on an SQL statement before sqlite3_step().
61623 */
61624 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
61625   Mem *pColName;
61626   int n;
61627   sqlite3 *db = p->db;
61628
61629   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
61630   sqlite3DbFree(db, p->aColName);
61631   n = nResColumn*COLNAME_N;
61632   p->nResColumn = (u16)nResColumn;
61633   p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
61634   if( p->aColName==0 ) return;
61635   while( n-- > 0 ){
61636     pColName->flags = MEM_Null;
61637     pColName->db = p->db;
61638     pColName++;
61639   }
61640 }
61641
61642 /*
61643 ** Set the name of the idx'th column to be returned by the SQL statement.
61644 ** zName must be a pointer to a nul terminated string.
61645 **
61646 ** This call must be made after a call to sqlite3VdbeSetNumCols().
61647 **
61648 ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
61649 ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
61650 ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
61651 */
61652 SQLITE_PRIVATE int sqlite3VdbeSetColName(
61653   Vdbe *p,                         /* Vdbe being configured */
61654   int idx,                         /* Index of column zName applies to */
61655   int var,                         /* One of the COLNAME_* constants */
61656   const char *zName,               /* Pointer to buffer containing name */
61657   void (*xDel)(void*)              /* Memory management strategy for zName */
61658 ){
61659   int rc;
61660   Mem *pColName;
61661   assert( idx<p->nResColumn );
61662   assert( var<COLNAME_N );
61663   if( p->db->mallocFailed ){
61664     assert( !zName || xDel!=SQLITE_DYNAMIC );
61665     return SQLITE_NOMEM;
61666   }
61667   assert( p->aColName!=0 );
61668   pColName = &(p->aColName[idx+var*p->nResColumn]);
61669   rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
61670   assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
61671   return rc;
61672 }
61673
61674 /*
61675 ** A read or write transaction may or may not be active on database handle
61676 ** db. If a transaction is active, commit it. If there is a
61677 ** write-transaction spanning more than one database file, this routine
61678 ** takes care of the master journal trickery.
61679 */
61680 static int vdbeCommit(sqlite3 *db, Vdbe *p){
61681   int i;
61682   int nTrans = 0;  /* Number of databases with an active write-transaction */
61683   int rc = SQLITE_OK;
61684   int needXcommit = 0;
61685
61686 #ifdef SQLITE_OMIT_VIRTUALTABLE
61687   /* With this option, sqlite3VtabSync() is defined to be simply 
61688   ** SQLITE_OK so p is not used. 
61689   */
61690   UNUSED_PARAMETER(p);
61691 #endif
61692
61693   /* Before doing anything else, call the xSync() callback for any
61694   ** virtual module tables written in this transaction. This has to
61695   ** be done before determining whether a master journal file is 
61696   ** required, as an xSync() callback may add an attached database
61697   ** to the transaction.
61698   */
61699   rc = sqlite3VtabSync(db, &p->zErrMsg);
61700
61701   /* This loop determines (a) if the commit hook should be invoked and
61702   ** (b) how many database files have open write transactions, not 
61703   ** including the temp database. (b) is important because if more than 
61704   ** one database file has an open write transaction, a master journal
61705   ** file is required for an atomic commit.
61706   */ 
61707   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
61708     Btree *pBt = db->aDb[i].pBt;
61709     if( sqlite3BtreeIsInTrans(pBt) ){
61710       needXcommit = 1;
61711       if( i!=1 ) nTrans++;
61712       sqlite3BtreeEnter(pBt);
61713       rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
61714       sqlite3BtreeLeave(pBt);
61715     }
61716   }
61717   if( rc!=SQLITE_OK ){
61718     return rc;
61719   }
61720
61721   /* If there are any write-transactions at all, invoke the commit hook */
61722   if( needXcommit && db->xCommitCallback ){
61723     rc = db->xCommitCallback(db->pCommitArg);
61724     if( rc ){
61725       return SQLITE_CONSTRAINT_COMMITHOOK;
61726     }
61727   }
61728
61729   /* The simple case - no more than one database file (not counting the
61730   ** TEMP database) has a transaction active.   There is no need for the
61731   ** master-journal.
61732   **
61733   ** If the return value of sqlite3BtreeGetFilename() is a zero length
61734   ** string, it means the main database is :memory: or a temp file.  In 
61735   ** that case we do not support atomic multi-file commits, so use the 
61736   ** simple case then too.
61737   */
61738   if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
61739    || nTrans<=1
61740   ){
61741     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
61742       Btree *pBt = db->aDb[i].pBt;
61743       if( pBt ){
61744         rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
61745       }
61746     }
61747
61748     /* Do the commit only if all databases successfully complete phase 1. 
61749     ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
61750     ** IO error while deleting or truncating a journal file. It is unlikely,
61751     ** but could happen. In this case abandon processing and return the error.
61752     */
61753     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
61754       Btree *pBt = db->aDb[i].pBt;
61755       if( pBt ){
61756         rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
61757       }
61758     }
61759     if( rc==SQLITE_OK ){
61760       sqlite3VtabCommit(db);
61761     }
61762   }
61763
61764   /* The complex case - There is a multi-file write-transaction active.
61765   ** This requires a master journal file to ensure the transaction is
61766   ** committed atomicly.
61767   */
61768 #ifndef SQLITE_OMIT_DISKIO
61769   else{
61770     sqlite3_vfs *pVfs = db->pVfs;
61771     int needSync = 0;
61772     char *zMaster = 0;   /* File-name for the master journal */
61773     char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
61774     sqlite3_file *pMaster = 0;
61775     i64 offset = 0;
61776     int res;
61777     int retryCount = 0;
61778     int nMainFile;
61779
61780     /* Select a master journal file name */
61781     nMainFile = sqlite3Strlen30(zMainFile);
61782     zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
61783     if( zMaster==0 ) return SQLITE_NOMEM;
61784     do {
61785       u32 iRandom;
61786       if( retryCount ){
61787         if( retryCount>100 ){
61788           sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
61789           sqlite3OsDelete(pVfs, zMaster, 0);
61790           break;
61791         }else if( retryCount==1 ){
61792           sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
61793         }
61794       }
61795       retryCount++;
61796       sqlite3_randomness(sizeof(iRandom), &iRandom);
61797       sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
61798                                (iRandom>>8)&0xffffff, iRandom&0xff);
61799       /* The antipenultimate character of the master journal name must
61800       ** be "9" to avoid name collisions when using 8+3 filenames. */
61801       assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
61802       sqlite3FileSuffix3(zMainFile, zMaster);
61803       rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
61804     }while( rc==SQLITE_OK && res );
61805     if( rc==SQLITE_OK ){
61806       /* Open the master journal. */
61807       rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster, 
61808           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
61809           SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
61810       );
61811     }
61812     if( rc!=SQLITE_OK ){
61813       sqlite3DbFree(db, zMaster);
61814       return rc;
61815     }
61816  
61817     /* Write the name of each database file in the transaction into the new
61818     ** master journal file. If an error occurs at this point close
61819     ** and delete the master journal file. All the individual journal files
61820     ** still have 'null' as the master journal pointer, so they will roll
61821     ** back independently if a failure occurs.
61822     */
61823     for(i=0; i<db->nDb; i++){
61824       Btree *pBt = db->aDb[i].pBt;
61825       if( sqlite3BtreeIsInTrans(pBt) ){
61826         char const *zFile = sqlite3BtreeGetJournalname(pBt);
61827         if( zFile==0 ){
61828           continue;  /* Ignore TEMP and :memory: databases */
61829         }
61830         assert( zFile[0]!=0 );
61831         if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
61832           needSync = 1;
61833         }
61834         rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
61835         offset += sqlite3Strlen30(zFile)+1;
61836         if( rc!=SQLITE_OK ){
61837           sqlite3OsCloseFree(pMaster);
61838           sqlite3OsDelete(pVfs, zMaster, 0);
61839           sqlite3DbFree(db, zMaster);
61840           return rc;
61841         }
61842       }
61843     }
61844
61845     /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
61846     ** flag is set this is not required.
61847     */
61848     if( needSync 
61849      && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
61850      && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
61851     ){
61852       sqlite3OsCloseFree(pMaster);
61853       sqlite3OsDelete(pVfs, zMaster, 0);
61854       sqlite3DbFree(db, zMaster);
61855       return rc;
61856     }
61857
61858     /* Sync all the db files involved in the transaction. The same call
61859     ** sets the master journal pointer in each individual journal. If
61860     ** an error occurs here, do not delete the master journal file.
61861     **
61862     ** If the error occurs during the first call to
61863     ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
61864     ** master journal file will be orphaned. But we cannot delete it,
61865     ** in case the master journal file name was written into the journal
61866     ** file before the failure occurred.
61867     */
61868     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
61869       Btree *pBt = db->aDb[i].pBt;
61870       if( pBt ){
61871         rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
61872       }
61873     }
61874     sqlite3OsCloseFree(pMaster);
61875     assert( rc!=SQLITE_BUSY );
61876     if( rc!=SQLITE_OK ){
61877       sqlite3DbFree(db, zMaster);
61878       return rc;
61879     }
61880
61881     /* Delete the master journal file. This commits the transaction. After
61882     ** doing this the directory is synced again before any individual
61883     ** transaction files are deleted.
61884     */
61885     rc = sqlite3OsDelete(pVfs, zMaster, 1);
61886     sqlite3DbFree(db, zMaster);
61887     zMaster = 0;
61888     if( rc ){
61889       return rc;
61890     }
61891
61892     /* All files and directories have already been synced, so the following
61893     ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
61894     ** deleting or truncating journals. If something goes wrong while
61895     ** this is happening we don't really care. The integrity of the
61896     ** transaction is already guaranteed, but some stray 'cold' journals
61897     ** may be lying around. Returning an error code won't help matters.
61898     */
61899     disable_simulated_io_errors();
61900     sqlite3BeginBenignMalloc();
61901     for(i=0; i<db->nDb; i++){ 
61902       Btree *pBt = db->aDb[i].pBt;
61903       if( pBt ){
61904         sqlite3BtreeCommitPhaseTwo(pBt, 1);
61905       }
61906     }
61907     sqlite3EndBenignMalloc();
61908     enable_simulated_io_errors();
61909
61910     sqlite3VtabCommit(db);
61911   }
61912 #endif
61913
61914   return rc;
61915 }
61916
61917 /* 
61918 ** This routine checks that the sqlite3.activeVdbeCnt count variable
61919 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
61920 ** currently active. An assertion fails if the two counts do not match.
61921 ** This is an internal self-check only - it is not an essential processing
61922 ** step.
61923 **
61924 ** This is a no-op if NDEBUG is defined.
61925 */
61926 #ifndef NDEBUG
61927 static void checkActiveVdbeCnt(sqlite3 *db){
61928   Vdbe *p;
61929   int cnt = 0;
61930   int nWrite = 0;
61931   p = db->pVdbe;
61932   while( p ){
61933     if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
61934       cnt++;
61935       if( p->readOnly==0 ) nWrite++;
61936     }
61937     p = p->pNext;
61938   }
61939   assert( cnt==db->activeVdbeCnt );
61940   assert( nWrite==db->writeVdbeCnt );
61941 }
61942 #else
61943 #define checkActiveVdbeCnt(x)
61944 #endif
61945
61946 /*
61947 ** If the Vdbe passed as the first argument opened a statement-transaction,
61948 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
61949 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
61950 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the 
61951 ** statement transaction is commtted.
61952 **
61953 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned. 
61954 ** Otherwise SQLITE_OK.
61955 */
61956 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
61957   sqlite3 *const db = p->db;
61958   int rc = SQLITE_OK;
61959
61960   /* If p->iStatement is greater than zero, then this Vdbe opened a 
61961   ** statement transaction that should be closed here. The only exception
61962   ** is that an IO error may have occurred, causing an emergency rollback.
61963   ** In this case (db->nStatement==0), and there is nothing to do.
61964   */
61965   if( db->nStatement && p->iStatement ){
61966     int i;
61967     const int iSavepoint = p->iStatement-1;
61968
61969     assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
61970     assert( db->nStatement>0 );
61971     assert( p->iStatement==(db->nStatement+db->nSavepoint) );
61972
61973     for(i=0; i<db->nDb; i++){ 
61974       int rc2 = SQLITE_OK;
61975       Btree *pBt = db->aDb[i].pBt;
61976       if( pBt ){
61977         if( eOp==SAVEPOINT_ROLLBACK ){
61978           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
61979         }
61980         if( rc2==SQLITE_OK ){
61981           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
61982         }
61983         if( rc==SQLITE_OK ){
61984           rc = rc2;
61985         }
61986       }
61987     }
61988     db->nStatement--;
61989     p->iStatement = 0;
61990
61991     if( rc==SQLITE_OK ){
61992       if( eOp==SAVEPOINT_ROLLBACK ){
61993         rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
61994       }
61995       if( rc==SQLITE_OK ){
61996         rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
61997       }
61998     }
61999
62000     /* If the statement transaction is being rolled back, also restore the 
62001     ** database handles deferred constraint counter to the value it had when 
62002     ** the statement transaction was opened.  */
62003     if( eOp==SAVEPOINT_ROLLBACK ){
62004       db->nDeferredCons = p->nStmtDefCons;
62005     }
62006   }
62007   return rc;
62008 }
62009
62010 /*
62011 ** This function is called when a transaction opened by the database 
62012 ** handle associated with the VM passed as an argument is about to be 
62013 ** committed. If there are outstanding deferred foreign key constraint
62014 ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
62015 **
62016 ** If there are outstanding FK violations and this function returns 
62017 ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
62018 ** and write an error message to it. Then return SQLITE_ERROR.
62019 */
62020 #ifndef SQLITE_OMIT_FOREIGN_KEY
62021 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
62022   sqlite3 *db = p->db;
62023   if( (deferred && db->nDeferredCons>0) || (!deferred && p->nFkConstraint>0) ){
62024     p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
62025     p->errorAction = OE_Abort;
62026     sqlite3SetString(&p->zErrMsg, db, "foreign key constraint failed");
62027     return SQLITE_ERROR;
62028   }
62029   return SQLITE_OK;
62030 }
62031 #endif
62032
62033 /*
62034 ** This routine is called the when a VDBE tries to halt.  If the VDBE
62035 ** has made changes and is in autocommit mode, then commit those
62036 ** changes.  If a rollback is needed, then do the rollback.
62037 **
62038 ** This routine is the only way to move the state of a VM from
62039 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
62040 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
62041 **
62042 ** Return an error code.  If the commit could not complete because of
62043 ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
62044 ** means the close did not happen and needs to be repeated.
62045 */
62046 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
62047   int rc;                         /* Used to store transient return codes */
62048   sqlite3 *db = p->db;
62049
62050   /* This function contains the logic that determines if a statement or
62051   ** transaction will be committed or rolled back as a result of the
62052   ** execution of this virtual machine. 
62053   **
62054   ** If any of the following errors occur:
62055   **
62056   **     SQLITE_NOMEM
62057   **     SQLITE_IOERR
62058   **     SQLITE_FULL
62059   **     SQLITE_INTERRUPT
62060   **
62061   ** Then the internal cache might have been left in an inconsistent
62062   ** state.  We need to rollback the statement transaction, if there is
62063   ** one, or the complete transaction if there is no statement transaction.
62064   */
62065
62066   if( p->db->mallocFailed ){
62067     p->rc = SQLITE_NOMEM;
62068   }
62069   if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag);
62070   closeAllCursors(p);
62071   if( p->magic!=VDBE_MAGIC_RUN ){
62072     return SQLITE_OK;
62073   }
62074   checkActiveVdbeCnt(db);
62075
62076   /* No commit or rollback needed if the program never started */
62077   if( p->pc>=0 ){
62078     int mrc;   /* Primary error code from p->rc */
62079     int eStatementOp = 0;
62080     int isSpecialError;            /* Set to true if a 'special' error */
62081
62082     /* Lock all btrees used by the statement */
62083     sqlite3VdbeEnter(p);
62084
62085     /* Check for one of the special errors */
62086     mrc = p->rc & 0xff;
62087     assert( p->rc!=SQLITE_IOERR_BLOCKED );  /* This error no longer exists */
62088     isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
62089                      || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
62090     if( isSpecialError ){
62091       /* If the query was read-only and the error code is SQLITE_INTERRUPT, 
62092       ** no rollback is necessary. Otherwise, at least a savepoint 
62093       ** transaction must be rolled back to restore the database to a 
62094       ** consistent state.
62095       **
62096       ** Even if the statement is read-only, it is important to perform
62097       ** a statement or transaction rollback operation. If the error 
62098       ** occurred while writing to the journal, sub-journal or database
62099       ** file as part of an effort to free up cache space (see function
62100       ** pagerStress() in pager.c), the rollback is required to restore 
62101       ** the pager to a consistent state.
62102       */
62103       if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
62104         if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
62105           eStatementOp = SAVEPOINT_ROLLBACK;
62106         }else{
62107           /* We are forced to roll back the active transaction. Before doing
62108           ** so, abort any other statements this handle currently has active.
62109           */
62110           sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
62111           sqlite3CloseSavepoints(db);
62112           db->autoCommit = 1;
62113         }
62114       }
62115     }
62116
62117     /* Check for immediate foreign key violations. */
62118     if( p->rc==SQLITE_OK ){
62119       sqlite3VdbeCheckFk(p, 0);
62120     }
62121   
62122     /* If the auto-commit flag is set and this is the only active writer 
62123     ** VM, then we do either a commit or rollback of the current transaction. 
62124     **
62125     ** Note: This block also runs if one of the special errors handled 
62126     ** above has occurred. 
62127     */
62128     if( !sqlite3VtabInSync(db) 
62129      && db->autoCommit 
62130      && db->writeVdbeCnt==(p->readOnly==0) 
62131     ){
62132       if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
62133         rc = sqlite3VdbeCheckFk(p, 1);
62134         if( rc!=SQLITE_OK ){
62135           if( NEVER(p->readOnly) ){
62136             sqlite3VdbeLeave(p);
62137             return SQLITE_ERROR;
62138           }
62139           rc = SQLITE_CONSTRAINT_FOREIGNKEY;
62140         }else{ 
62141           /* The auto-commit flag is true, the vdbe program was successful 
62142           ** or hit an 'OR FAIL' constraint and there are no deferred foreign
62143           ** key constraints to hold up the transaction. This means a commit 
62144           ** is required. */
62145           rc = vdbeCommit(db, p);
62146         }
62147         if( rc==SQLITE_BUSY && p->readOnly ){
62148           sqlite3VdbeLeave(p);
62149           return SQLITE_BUSY;
62150         }else if( rc!=SQLITE_OK ){
62151           p->rc = rc;
62152           sqlite3RollbackAll(db, SQLITE_OK);
62153         }else{
62154           db->nDeferredCons = 0;
62155           sqlite3CommitInternalChanges(db);
62156         }
62157       }else{
62158         sqlite3RollbackAll(db, SQLITE_OK);
62159       }
62160       db->nStatement = 0;
62161     }else if( eStatementOp==0 ){
62162       if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
62163         eStatementOp = SAVEPOINT_RELEASE;
62164       }else if( p->errorAction==OE_Abort ){
62165         eStatementOp = SAVEPOINT_ROLLBACK;
62166       }else{
62167         sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
62168         sqlite3CloseSavepoints(db);
62169         db->autoCommit = 1;
62170       }
62171     }
62172   
62173     /* If eStatementOp is non-zero, then a statement transaction needs to
62174     ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
62175     ** do so. If this operation returns an error, and the current statement
62176     ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
62177     ** current statement error code.
62178     */
62179     if( eStatementOp ){
62180       rc = sqlite3VdbeCloseStatement(p, eStatementOp);
62181       if( rc ){
62182         if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
62183           p->rc = rc;
62184           sqlite3DbFree(db, p->zErrMsg);
62185           p->zErrMsg = 0;
62186         }
62187         sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
62188         sqlite3CloseSavepoints(db);
62189         db->autoCommit = 1;
62190       }
62191     }
62192   
62193     /* If this was an INSERT, UPDATE or DELETE and no statement transaction
62194     ** has been rolled back, update the database connection change-counter. 
62195     */
62196     if( p->changeCntOn ){
62197       if( eStatementOp!=SAVEPOINT_ROLLBACK ){
62198         sqlite3VdbeSetChanges(db, p->nChange);
62199       }else{
62200         sqlite3VdbeSetChanges(db, 0);
62201       }
62202       p->nChange = 0;
62203     }
62204
62205     /* Release the locks */
62206     sqlite3VdbeLeave(p);
62207   }
62208
62209   /* We have successfully halted and closed the VM.  Record this fact. */
62210   if( p->pc>=0 ){
62211     db->activeVdbeCnt--;
62212     if( !p->readOnly ){
62213       db->writeVdbeCnt--;
62214     }
62215     assert( db->activeVdbeCnt>=db->writeVdbeCnt );
62216   }
62217   p->magic = VDBE_MAGIC_HALT;
62218   checkActiveVdbeCnt(db);
62219   if( p->db->mallocFailed ){
62220     p->rc = SQLITE_NOMEM;
62221   }
62222
62223   /* If the auto-commit flag is set to true, then any locks that were held
62224   ** by connection db have now been released. Call sqlite3ConnectionUnlocked() 
62225   ** to invoke any required unlock-notify callbacks.
62226   */
62227   if( db->autoCommit ){
62228     sqlite3ConnectionUnlocked(db);
62229   }
62230
62231   assert( db->activeVdbeCnt>0 || db->autoCommit==0 || db->nStatement==0 );
62232   return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
62233 }
62234
62235
62236 /*
62237 ** Each VDBE holds the result of the most recent sqlite3_step() call
62238 ** in p->rc.  This routine sets that result back to SQLITE_OK.
62239 */
62240 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
62241   p->rc = SQLITE_OK;
62242 }
62243
62244 /*
62245 ** Copy the error code and error message belonging to the VDBE passed
62246 ** as the first argument to its database handle (so that they will be 
62247 ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
62248 **
62249 ** This function does not clear the VDBE error code or message, just
62250 ** copies them to the database handle.
62251 */
62252 SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
62253   sqlite3 *db = p->db;
62254   int rc = p->rc;
62255   if( p->zErrMsg ){
62256     u8 mallocFailed = db->mallocFailed;
62257     sqlite3BeginBenignMalloc();
62258     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
62259     sqlite3EndBenignMalloc();
62260     db->mallocFailed = mallocFailed;
62261     db->errCode = rc;
62262   }else{
62263     sqlite3Error(db, rc, 0);
62264   }
62265   return rc;
62266 }
62267
62268 #ifdef SQLITE_ENABLE_SQLLOG
62269 /*
62270 ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run, 
62271 ** invoke it.
62272 */
62273 static void vdbeInvokeSqllog(Vdbe *v){
62274   if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
62275     char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
62276     assert( v->db->init.busy==0 );
62277     if( zExpanded ){
62278       sqlite3GlobalConfig.xSqllog(
62279           sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
62280       );
62281       sqlite3DbFree(v->db, zExpanded);
62282     }
62283   }
62284 }
62285 #else
62286 # define vdbeInvokeSqllog(x)
62287 #endif
62288
62289 /*
62290 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
62291 ** Write any error messages into *pzErrMsg.  Return the result code.
62292 **
62293 ** After this routine is run, the VDBE should be ready to be executed
62294 ** again.
62295 **
62296 ** To look at it another way, this routine resets the state of the
62297 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
62298 ** VDBE_MAGIC_INIT.
62299 */
62300 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
62301   sqlite3 *db;
62302   db = p->db;
62303
62304   /* If the VM did not run to completion or if it encountered an
62305   ** error, then it might not have been halted properly.  So halt
62306   ** it now.
62307   */
62308   sqlite3VdbeHalt(p);
62309
62310   /* If the VDBE has be run even partially, then transfer the error code
62311   ** and error message from the VDBE into the main database structure.  But
62312   ** if the VDBE has just been set to run but has not actually executed any
62313   ** instructions yet, leave the main database error information unchanged.
62314   */
62315   if( p->pc>=0 ){
62316     vdbeInvokeSqllog(p);
62317     sqlite3VdbeTransferError(p);
62318     sqlite3DbFree(db, p->zErrMsg);
62319     p->zErrMsg = 0;
62320     if( p->runOnlyOnce ) p->expired = 1;
62321   }else if( p->rc && p->expired ){
62322     /* The expired flag was set on the VDBE before the first call
62323     ** to sqlite3_step(). For consistency (since sqlite3_step() was
62324     ** called), set the database error in this case as well.
62325     */
62326     sqlite3Error(db, p->rc, 0);
62327     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
62328     sqlite3DbFree(db, p->zErrMsg);
62329     p->zErrMsg = 0;
62330   }
62331
62332   /* Reclaim all memory used by the VDBE
62333   */
62334   Cleanup(p);
62335
62336   /* Save profiling information from this VDBE run.
62337   */
62338 #ifdef VDBE_PROFILE
62339   {
62340     FILE *out = fopen("vdbe_profile.out", "a");
62341     if( out ){
62342       int i;
62343       fprintf(out, "---- ");
62344       for(i=0; i<p->nOp; i++){
62345         fprintf(out, "%02x", p->aOp[i].opcode);
62346       }
62347       fprintf(out, "\n");
62348       for(i=0; i<p->nOp; i++){
62349         fprintf(out, "%6d %10lld %8lld ",
62350            p->aOp[i].cnt,
62351            p->aOp[i].cycles,
62352            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
62353         );
62354         sqlite3VdbePrintOp(out, i, &p->aOp[i]);
62355       }
62356       fclose(out);
62357     }
62358   }
62359 #endif
62360   p->magic = VDBE_MAGIC_INIT;
62361   return p->rc & db->errMask;
62362 }
62363  
62364 /*
62365 ** Clean up and delete a VDBE after execution.  Return an integer which is
62366 ** the result code.  Write any error message text into *pzErrMsg.
62367 */
62368 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
62369   int rc = SQLITE_OK;
62370   if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
62371     rc = sqlite3VdbeReset(p);
62372     assert( (rc & p->db->errMask)==rc );
62373   }
62374   sqlite3VdbeDelete(p);
62375   return rc;
62376 }
62377
62378 /*
62379 ** Call the destructor for each auxdata entry in pVdbeFunc for which
62380 ** the corresponding bit in mask is clear.  Auxdata entries beyond 31
62381 ** are always destroyed.  To destroy all auxdata entries, call this
62382 ** routine with mask==0.
62383 */
62384 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
62385   int i;
62386   for(i=0; i<pVdbeFunc->nAux; i++){
62387     struct AuxData *pAux = &pVdbeFunc->apAux[i];
62388     if( (i>31 || !(mask&(((u32)1)<<i))) && pAux->pAux ){
62389       if( pAux->xDelete ){
62390         pAux->xDelete(pAux->pAux);
62391       }
62392       pAux->pAux = 0;
62393     }
62394   }
62395 }
62396
62397 /*
62398 ** Free all memory associated with the Vdbe passed as the second argument,
62399 ** except for object itself, which is preserved.
62400 **
62401 ** The difference between this function and sqlite3VdbeDelete() is that
62402 ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
62403 ** the database connection and frees the object itself.
62404 */
62405 SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
62406   SubProgram *pSub, *pNext;
62407   int i;
62408   assert( p->db==0 || p->db==db );
62409   releaseMemArray(p->aVar, p->nVar);
62410   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
62411   for(pSub=p->pProgram; pSub; pSub=pNext){
62412     pNext = pSub->pNext;
62413     vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
62414     sqlite3DbFree(db, pSub);
62415   }
62416   for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
62417   vdbeFreeOpArray(db, p->aOp, p->nOp);
62418   sqlite3DbFree(db, p->aLabel);
62419   sqlite3DbFree(db, p->aColName);
62420   sqlite3DbFree(db, p->zSql);
62421   sqlite3DbFree(db, p->pFree);
62422 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
62423   sqlite3DbFree(db, p->zExplain);
62424   sqlite3DbFree(db, p->pExplain);
62425 #endif
62426 }
62427
62428 /*
62429 ** Delete an entire VDBE.
62430 */
62431 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
62432   sqlite3 *db;
62433
62434   if( NEVER(p==0) ) return;
62435   db = p->db;
62436   assert( sqlite3_mutex_held(db->mutex) );
62437   sqlite3VdbeClearObject(db, p);
62438   if( p->pPrev ){
62439     p->pPrev->pNext = p->pNext;
62440   }else{
62441     assert( db->pVdbe==p );
62442     db->pVdbe = p->pNext;
62443   }
62444   if( p->pNext ){
62445     p->pNext->pPrev = p->pPrev;
62446   }
62447   p->magic = VDBE_MAGIC_DEAD;
62448   p->db = 0;
62449   sqlite3DbFree(db, p);
62450 }
62451
62452 /*
62453 ** Make sure the cursor p is ready to read or write the row to which it
62454 ** was last positioned.  Return an error code if an OOM fault or I/O error
62455 ** prevents us from positioning the cursor to its correct position.
62456 **
62457 ** If a MoveTo operation is pending on the given cursor, then do that
62458 ** MoveTo now.  If no move is pending, check to see if the row has been
62459 ** deleted out from under the cursor and if it has, mark the row as
62460 ** a NULL row.
62461 **
62462 ** If the cursor is already pointing to the correct row and that row has
62463 ** not been deleted out from under the cursor, then this routine is a no-op.
62464 */
62465 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
62466   if( p->deferredMoveto ){
62467     int res, rc;
62468 #ifdef SQLITE_TEST
62469     extern int sqlite3_search_count;
62470 #endif
62471     assert( p->isTable );
62472     rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
62473     if( rc ) return rc;
62474     p->lastRowid = p->movetoTarget;
62475     if( res!=0 ) return SQLITE_CORRUPT_BKPT;
62476     p->rowidIsValid = 1;
62477 #ifdef SQLITE_TEST
62478     sqlite3_search_count++;
62479 #endif
62480     p->deferredMoveto = 0;
62481     p->cacheStatus = CACHE_STALE;
62482   }else if( ALWAYS(p->pCursor) ){
62483     int hasMoved;
62484     int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
62485     if( rc ) return rc;
62486     if( hasMoved ){
62487       p->cacheStatus = CACHE_STALE;
62488       p->nullRow = 1;
62489     }
62490   }
62491   return SQLITE_OK;
62492 }
62493
62494 /*
62495 ** The following functions:
62496 **
62497 ** sqlite3VdbeSerialType()
62498 ** sqlite3VdbeSerialTypeLen()
62499 ** sqlite3VdbeSerialLen()
62500 ** sqlite3VdbeSerialPut()
62501 ** sqlite3VdbeSerialGet()
62502 **
62503 ** encapsulate the code that serializes values for storage in SQLite
62504 ** data and index records. Each serialized value consists of a
62505 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
62506 ** integer, stored as a varint.
62507 **
62508 ** In an SQLite index record, the serial type is stored directly before
62509 ** the blob of data that it corresponds to. In a table record, all serial
62510 ** types are stored at the start of the record, and the blobs of data at
62511 ** the end. Hence these functions allow the caller to handle the
62512 ** serial-type and data blob separately.
62513 **
62514 ** The following table describes the various storage classes for data:
62515 **
62516 **   serial type        bytes of data      type
62517 **   --------------     ---------------    ---------------
62518 **      0                     0            NULL
62519 **      1                     1            signed integer
62520 **      2                     2            signed integer
62521 **      3                     3            signed integer
62522 **      4                     4            signed integer
62523 **      5                     6            signed integer
62524 **      6                     8            signed integer
62525 **      7                     8            IEEE float
62526 **      8                     0            Integer constant 0
62527 **      9                     0            Integer constant 1
62528 **     10,11                               reserved for expansion
62529 **    N>=12 and even       (N-12)/2        BLOB
62530 **    N>=13 and odd        (N-13)/2        text
62531 **
62532 ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
62533 ** of SQLite will not understand those serial types.
62534 */
62535
62536 /*
62537 ** Return the serial-type for the value stored in pMem.
62538 */
62539 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
62540   int flags = pMem->flags;
62541   int n;
62542
62543   if( flags&MEM_Null ){
62544     return 0;
62545   }
62546   if( flags&MEM_Int ){
62547     /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
62548 #   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
62549     i64 i = pMem->u.i;
62550     u64 u;
62551     if( i<0 ){
62552       if( i<(-MAX_6BYTE) ) return 6;
62553       /* Previous test prevents:  u = -(-9223372036854775808) */
62554       u = -i;
62555     }else{
62556       u = i;
62557     }
62558     if( u<=127 ){
62559       return ((i&1)==i && file_format>=4) ? 8+(u32)u : 1;
62560     }
62561     if( u<=32767 ) return 2;
62562     if( u<=8388607 ) return 3;
62563     if( u<=2147483647 ) return 4;
62564     if( u<=MAX_6BYTE ) return 5;
62565     return 6;
62566   }
62567   if( flags&MEM_Real ){
62568     return 7;
62569   }
62570   assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
62571   n = pMem->n;
62572   if( flags & MEM_Zero ){
62573     n += pMem->u.nZero;
62574   }
62575   assert( n>=0 );
62576   return ((n*2) + 12 + ((flags&MEM_Str)!=0));
62577 }
62578
62579 /*
62580 ** Return the length of the data corresponding to the supplied serial-type.
62581 */
62582 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
62583   if( serial_type>=12 ){
62584     return (serial_type-12)/2;
62585   }else{
62586     static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
62587     return aSize[serial_type];
62588   }
62589 }
62590
62591 /*
62592 ** If we are on an architecture with mixed-endian floating 
62593 ** points (ex: ARM7) then swap the lower 4 bytes with the 
62594 ** upper 4 bytes.  Return the result.
62595 **
62596 ** For most architectures, this is a no-op.
62597 **
62598 ** (later):  It is reported to me that the mixed-endian problem
62599 ** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
62600 ** that early versions of GCC stored the two words of a 64-bit
62601 ** float in the wrong order.  And that error has been propagated
62602 ** ever since.  The blame is not necessarily with GCC, though.
62603 ** GCC might have just copying the problem from a prior compiler.
62604 ** I am also told that newer versions of GCC that follow a different
62605 ** ABI get the byte order right.
62606 **
62607 ** Developers using SQLite on an ARM7 should compile and run their
62608 ** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
62609 ** enabled, some asserts below will ensure that the byte order of
62610 ** floating point values is correct.
62611 **
62612 ** (2007-08-30)  Frank van Vugt has studied this problem closely
62613 ** and has send his findings to the SQLite developers.  Frank
62614 ** writes that some Linux kernels offer floating point hardware
62615 ** emulation that uses only 32-bit mantissas instead of a full 
62616 ** 48-bits as required by the IEEE standard.  (This is the
62617 ** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
62618 ** byte swapping becomes very complicated.  To avoid problems,
62619 ** the necessary byte swapping is carried out using a 64-bit integer
62620 ** rather than a 64-bit float.  Frank assures us that the code here
62621 ** works for him.  We, the developers, have no way to independently
62622 ** verify this, but Frank seems to know what he is talking about
62623 ** so we trust him.
62624 */
62625 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
62626 static u64 floatSwap(u64 in){
62627   union {
62628     u64 r;
62629     u32 i[2];
62630   } u;
62631   u32 t;
62632
62633   u.r = in;
62634   t = u.i[0];
62635   u.i[0] = u.i[1];
62636   u.i[1] = t;
62637   return u.r;
62638 }
62639 # define swapMixedEndianFloat(X)  X = floatSwap(X)
62640 #else
62641 # define swapMixedEndianFloat(X)
62642 #endif
62643
62644 /*
62645 ** Write the serialized data blob for the value stored in pMem into 
62646 ** buf. It is assumed that the caller has allocated sufficient space.
62647 ** Return the number of bytes written.
62648 **
62649 ** nBuf is the amount of space left in buf[].  nBuf must always be
62650 ** large enough to hold the entire field.  Except, if the field is
62651 ** a blob with a zero-filled tail, then buf[] might be just the right
62652 ** size to hold everything except for the zero-filled tail.  If buf[]
62653 ** is only big enough to hold the non-zero prefix, then only write that
62654 ** prefix into buf[].  But if buf[] is large enough to hold both the
62655 ** prefix and the tail then write the prefix and set the tail to all
62656 ** zeros.
62657 **
62658 ** Return the number of bytes actually written into buf[].  The number
62659 ** of bytes in the zero-filled tail is included in the return value only
62660 ** if those bytes were zeroed in buf[].
62661 */ 
62662 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
62663   u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
62664   u32 len;
62665
62666   /* Integer and Real */
62667   if( serial_type<=7 && serial_type>0 ){
62668     u64 v;
62669     u32 i;
62670     if( serial_type==7 ){
62671       assert( sizeof(v)==sizeof(pMem->r) );
62672       memcpy(&v, &pMem->r, sizeof(v));
62673       swapMixedEndianFloat(v);
62674     }else{
62675       v = pMem->u.i;
62676     }
62677     len = i = sqlite3VdbeSerialTypeLen(serial_type);
62678     assert( len<=(u32)nBuf );
62679     while( i-- ){
62680       buf[i] = (u8)(v&0xFF);
62681       v >>= 8;
62682     }
62683     return len;
62684   }
62685
62686   /* String or blob */
62687   if( serial_type>=12 ){
62688     assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
62689              == (int)sqlite3VdbeSerialTypeLen(serial_type) );
62690     assert( pMem->n<=nBuf );
62691     len = pMem->n;
62692     memcpy(buf, pMem->z, len);
62693     if( pMem->flags & MEM_Zero ){
62694       len += pMem->u.nZero;
62695       assert( nBuf>=0 );
62696       if( len > (u32)nBuf ){
62697         len = (u32)nBuf;
62698       }
62699       memset(&buf[pMem->n], 0, len-pMem->n);
62700     }
62701     return len;
62702   }
62703
62704   /* NULL or constants 0 or 1 */
62705   return 0;
62706 }
62707
62708 /*
62709 ** Deserialize the data blob pointed to by buf as serial type serial_type
62710 ** and store the result in pMem.  Return the number of bytes read.
62711 */ 
62712 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
62713   const unsigned char *buf,     /* Buffer to deserialize from */
62714   u32 serial_type,              /* Serial type to deserialize */
62715   Mem *pMem                     /* Memory cell to write value into */
62716 ){
62717   switch( serial_type ){
62718     case 10:   /* Reserved for future use */
62719     case 11:   /* Reserved for future use */
62720     case 0: {  /* NULL */
62721       pMem->flags = MEM_Null;
62722       break;
62723     }
62724     case 1: { /* 1-byte signed integer */
62725       pMem->u.i = (signed char)buf[0];
62726       pMem->flags = MEM_Int;
62727       return 1;
62728     }
62729     case 2: { /* 2-byte signed integer */
62730       pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
62731       pMem->flags = MEM_Int;
62732       return 2;
62733     }
62734     case 3: { /* 3-byte signed integer */
62735       pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
62736       pMem->flags = MEM_Int;
62737       return 3;
62738     }
62739     case 4: { /* 4-byte signed integer */
62740       pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
62741       pMem->flags = MEM_Int;
62742       return 4;
62743     }
62744     case 5: { /* 6-byte signed integer */
62745       u64 x = (((signed char)buf[0])<<8) | buf[1];
62746       u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
62747       x = (x<<32) | y;
62748       pMem->u.i = *(i64*)&x;
62749       pMem->flags = MEM_Int;
62750       return 6;
62751     }
62752     case 6:   /* 8-byte signed integer */
62753     case 7: { /* IEEE floating point */
62754       u64 x;
62755       u32 y;
62756 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
62757       /* Verify that integers and floating point values use the same
62758       ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
62759       ** defined that 64-bit floating point values really are mixed
62760       ** endian.
62761       */
62762       static const u64 t1 = ((u64)0x3ff00000)<<32;
62763       static const double r1 = 1.0;
62764       u64 t2 = t1;
62765       swapMixedEndianFloat(t2);
62766       assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
62767 #endif
62768
62769       x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
62770       y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
62771       x = (x<<32) | y;
62772       if( serial_type==6 ){
62773         pMem->u.i = *(i64*)&x;
62774         pMem->flags = MEM_Int;
62775       }else{
62776         assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
62777         swapMixedEndianFloat(x);
62778         memcpy(&pMem->r, &x, sizeof(x));
62779         pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
62780       }
62781       return 8;
62782     }
62783     case 8:    /* Integer 0 */
62784     case 9: {  /* Integer 1 */
62785       pMem->u.i = serial_type-8;
62786       pMem->flags = MEM_Int;
62787       return 0;
62788     }
62789     default: {
62790       u32 len = (serial_type-12)/2;
62791       pMem->z = (char *)buf;
62792       pMem->n = len;
62793       pMem->xDel = 0;
62794       if( serial_type&0x01 ){
62795         pMem->flags = MEM_Str | MEM_Ephem;
62796       }else{
62797         pMem->flags = MEM_Blob | MEM_Ephem;
62798       }
62799       return len;
62800     }
62801   }
62802   return 0;
62803 }
62804
62805 /*
62806 ** This routine is used to allocate sufficient space for an UnpackedRecord
62807 ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
62808 ** the first argument is a pointer to KeyInfo structure pKeyInfo.
62809 **
62810 ** The space is either allocated using sqlite3DbMallocRaw() or from within
62811 ** the unaligned buffer passed via the second and third arguments (presumably
62812 ** stack space). If the former, then *ppFree is set to a pointer that should
62813 ** be eventually freed by the caller using sqlite3DbFree(). Or, if the 
62814 ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
62815 ** before returning.
62816 **
62817 ** If an OOM error occurs, NULL is returned.
62818 */
62819 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
62820   KeyInfo *pKeyInfo,              /* Description of the record */
62821   char *pSpace,                   /* Unaligned space available */
62822   int szSpace,                    /* Size of pSpace[] in bytes */
62823   char **ppFree                   /* OUT: Caller should free this pointer */
62824 ){
62825   UnpackedRecord *p;              /* Unpacked record to return */
62826   int nOff;                       /* Increment pSpace by nOff to align it */
62827   int nByte;                      /* Number of bytes required for *p */
62828
62829   /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
62830   ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift 
62831   ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.
62832   */
62833   nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
62834   nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
62835   if( nByte>szSpace+nOff ){
62836     p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
62837     *ppFree = (char *)p;
62838     if( !p ) return 0;
62839   }else{
62840     p = (UnpackedRecord*)&pSpace[nOff];
62841     *ppFree = 0;
62842   }
62843
62844   p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
62845   assert( pKeyInfo->aSortOrder!=0 );
62846   p->pKeyInfo = pKeyInfo;
62847   p->nField = pKeyInfo->nField + 1;
62848   return p;
62849 }
62850
62851 /*
62852 ** Given the nKey-byte encoding of a record in pKey[], populate the 
62853 ** UnpackedRecord structure indicated by the fourth argument with the
62854 ** contents of the decoded record.
62855 */ 
62856 SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
62857   KeyInfo *pKeyInfo,     /* Information about the record format */
62858   int nKey,              /* Size of the binary record */
62859   const void *pKey,      /* The binary record */
62860   UnpackedRecord *p      /* Populate this structure before returning. */
62861 ){
62862   const unsigned char *aKey = (const unsigned char *)pKey;
62863   int d; 
62864   u32 idx;                        /* Offset in aKey[] to read from */
62865   u16 u;                          /* Unsigned loop counter */
62866   u32 szHdr;
62867   Mem *pMem = p->aMem;
62868
62869   p->flags = 0;
62870   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
62871   idx = getVarint32(aKey, szHdr);
62872   d = szHdr;
62873   u = 0;
62874   while( idx<szHdr && u<p->nField && d<=nKey ){
62875     u32 serial_type;
62876
62877     idx += getVarint32(&aKey[idx], serial_type);
62878     pMem->enc = pKeyInfo->enc;
62879     pMem->db = pKeyInfo->db;
62880     /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
62881     pMem->zMalloc = 0;
62882     d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
62883     pMem++;
62884     u++;
62885   }
62886   assert( u<=pKeyInfo->nField + 1 );
62887   p->nField = u;
62888 }
62889
62890 /*
62891 ** This function compares the two table rows or index records
62892 ** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
62893 ** or positive integer if key1 is less than, equal to or 
62894 ** greater than key2.  The {nKey1, pKey1} key must be a blob
62895 ** created by th OP_MakeRecord opcode of the VDBE.  The pPKey2
62896 ** key must be a parsed key such as obtained from
62897 ** sqlite3VdbeParseRecord.
62898 **
62899 ** Key1 and Key2 do not have to contain the same number of fields.
62900 ** The key with fewer fields is usually compares less than the 
62901 ** longer key.  However if the UNPACKED_INCRKEY flags in pPKey2 is set
62902 ** and the common prefixes are equal, then key1 is less than key2.
62903 ** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
62904 ** equal, then the keys are considered to be equal and
62905 ** the parts beyond the common prefix are ignored.
62906 */
62907 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
62908   int nKey1, const void *pKey1, /* Left key */
62909   UnpackedRecord *pPKey2        /* Right key */
62910 ){
62911   int d1;            /* Offset into aKey[] of next data element */
62912   u32 idx1;          /* Offset into aKey[] of next header element */
62913   u32 szHdr1;        /* Number of bytes in header */
62914   int i = 0;
62915   int nField;
62916   int rc = 0;
62917   const unsigned char *aKey1 = (const unsigned char *)pKey1;
62918   KeyInfo *pKeyInfo;
62919   Mem mem1;
62920
62921   pKeyInfo = pPKey2->pKeyInfo;
62922   mem1.enc = pKeyInfo->enc;
62923   mem1.db = pKeyInfo->db;
62924   /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
62925   VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
62926
62927   /* Compilers may complain that mem1.u.i is potentially uninitialized.
62928   ** We could initialize it, as shown here, to silence those complaints.
62929   ** But in fact, mem1.u.i will never actually be used uninitialized, and doing 
62930   ** the unnecessary initialization has a measurable negative performance
62931   ** impact, since this routine is a very high runner.  And so, we choose
62932   ** to ignore the compiler warnings and leave this variable uninitialized.
62933   */
62934   /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
62935   
62936   idx1 = getVarint32(aKey1, szHdr1);
62937   d1 = szHdr1;
62938   nField = pKeyInfo->nField;
62939   assert( pKeyInfo->aSortOrder!=0 );
62940   while( idx1<szHdr1 && i<pPKey2->nField ){
62941     u32 serial_type1;
62942
62943     /* Read the serial types for the next element in each key. */
62944     idx1 += getVarint32( aKey1+idx1, serial_type1 );
62945     if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
62946
62947     /* Extract the values to be compared.
62948     */
62949     d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
62950
62951     /* Do the comparison
62952     */
62953     rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
62954                            i<nField ? pKeyInfo->aColl[i] : 0);
62955     if( rc!=0 ){
62956       assert( mem1.zMalloc==0 );  /* See comment below */
62957
62958       /* Invert the result if we are using DESC sort order. */
62959       if( i<nField && pKeyInfo->aSortOrder[i] ){
62960         rc = -rc;
62961       }
62962     
62963       /* If the PREFIX_SEARCH flag is set and all fields except the final
62964       ** rowid field were equal, then clear the PREFIX_SEARCH flag and set 
62965       ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
62966       ** This is used by the OP_IsUnique opcode.
62967       */
62968       if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){
62969         assert( idx1==szHdr1 && rc );
62970         assert( mem1.flags & MEM_Int );
62971         pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;
62972         pPKey2->rowid = mem1.u.i;
62973       }
62974     
62975       return rc;
62976     }
62977     i++;
62978   }
62979
62980   /* No memory allocation is ever used on mem1.  Prove this using
62981   ** the following assert().  If the assert() fails, it indicates a
62982   ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
62983   */
62984   assert( mem1.zMalloc==0 );
62985
62986   /* rc==0 here means that one of the keys ran out of fields and
62987   ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
62988   ** flag is set, then break the tie by treating key2 as larger.
62989   ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
62990   ** are considered to be equal.  Otherwise, the longer key is the 
62991   ** larger.  As it happens, the pPKey2 will always be the longer
62992   ** if there is a difference.
62993   */
62994   assert( rc==0 );
62995   if( pPKey2->flags & UNPACKED_INCRKEY ){
62996     rc = -1;
62997   }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
62998     /* Leave rc==0 */
62999   }else if( idx1<szHdr1 ){
63000     rc = 1;
63001   }
63002   return rc;
63003 }
63004  
63005
63006 /*
63007 ** pCur points at an index entry created using the OP_MakeRecord opcode.
63008 ** Read the rowid (the last field in the record) and store it in *rowid.
63009 ** Return SQLITE_OK if everything works, or an error code otherwise.
63010 **
63011 ** pCur might be pointing to text obtained from a corrupt database file.
63012 ** So the content cannot be trusted.  Do appropriate checks on the content.
63013 */
63014 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
63015   i64 nCellKey = 0;
63016   int rc;
63017   u32 szHdr;        /* Size of the header */
63018   u32 typeRowid;    /* Serial type of the rowid */
63019   u32 lenRowid;     /* Size of the rowid */
63020   Mem m, v;
63021
63022   UNUSED_PARAMETER(db);
63023
63024   /* Get the size of the index entry.  Only indices entries of less
63025   ** than 2GiB are support - anything large must be database corruption.
63026   ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
63027   ** this code can safely assume that nCellKey is 32-bits  
63028   */
63029   assert( sqlite3BtreeCursorIsValid(pCur) );
63030   VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
63031   assert( rc==SQLITE_OK );     /* pCur is always valid so KeySize cannot fail */
63032   assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
63033
63034   /* Read in the complete content of the index entry */
63035   memset(&m, 0, sizeof(m));
63036   rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
63037   if( rc ){
63038     return rc;
63039   }
63040
63041   /* The index entry must begin with a header size */
63042   (void)getVarint32((u8*)m.z, szHdr);
63043   testcase( szHdr==3 );
63044   testcase( szHdr==m.n );
63045   if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
63046     goto idx_rowid_corruption;
63047   }
63048
63049   /* The last field of the index should be an integer - the ROWID.
63050   ** Verify that the last entry really is an integer. */
63051   (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
63052   testcase( typeRowid==1 );
63053   testcase( typeRowid==2 );
63054   testcase( typeRowid==3 );
63055   testcase( typeRowid==4 );
63056   testcase( typeRowid==5 );
63057   testcase( typeRowid==6 );
63058   testcase( typeRowid==8 );
63059   testcase( typeRowid==9 );
63060   if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
63061     goto idx_rowid_corruption;
63062   }
63063   lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
63064   testcase( (u32)m.n==szHdr+lenRowid );
63065   if( unlikely((u32)m.n<szHdr+lenRowid) ){
63066     goto idx_rowid_corruption;
63067   }
63068
63069   /* Fetch the integer off the end of the index record */
63070   sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
63071   *rowid = v.u.i;
63072   sqlite3VdbeMemRelease(&m);
63073   return SQLITE_OK;
63074
63075   /* Jump here if database corruption is detected after m has been
63076   ** allocated.  Free the m object and return SQLITE_CORRUPT. */
63077 idx_rowid_corruption:
63078   testcase( m.zMalloc!=0 );
63079   sqlite3VdbeMemRelease(&m);
63080   return SQLITE_CORRUPT_BKPT;
63081 }
63082
63083 /*
63084 ** Compare the key of the index entry that cursor pC is pointing to against
63085 ** the key string in pUnpacked.  Write into *pRes a number
63086 ** that is negative, zero, or positive if pC is less than, equal to,
63087 ** or greater than pUnpacked.  Return SQLITE_OK on success.
63088 **
63089 ** pUnpacked is either created without a rowid or is truncated so that it
63090 ** omits the rowid at the end.  The rowid at the end of the index entry
63091 ** is ignored as well.  Hence, this routine only compares the prefixes 
63092 ** of the keys prior to the final rowid, not the entire key.
63093 */
63094 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
63095   VdbeCursor *pC,             /* The cursor to compare against */
63096   UnpackedRecord *pUnpacked,  /* Unpacked version of key to compare against */
63097   int *res                    /* Write the comparison result here */
63098 ){
63099   i64 nCellKey = 0;
63100   int rc;
63101   BtCursor *pCur = pC->pCursor;
63102   Mem m;
63103
63104   assert( sqlite3BtreeCursorIsValid(pCur) );
63105   VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
63106   assert( rc==SQLITE_OK );    /* pCur is always valid so KeySize cannot fail */
63107   /* nCellKey will always be between 0 and 0xffffffff because of the say
63108   ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
63109   if( nCellKey<=0 || nCellKey>0x7fffffff ){
63110     *res = 0;
63111     return SQLITE_CORRUPT_BKPT;
63112   }
63113   memset(&m, 0, sizeof(m));
63114   rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
63115   if( rc ){
63116     return rc;
63117   }
63118   assert( pUnpacked->flags & UNPACKED_PREFIX_MATCH );
63119   *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
63120   sqlite3VdbeMemRelease(&m);
63121   return SQLITE_OK;
63122 }
63123
63124 /*
63125 ** This routine sets the value to be returned by subsequent calls to
63126 ** sqlite3_changes() on the database handle 'db'. 
63127 */
63128 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
63129   assert( sqlite3_mutex_held(db->mutex) );
63130   db->nChange = nChange;
63131   db->nTotalChange += nChange;
63132 }
63133
63134 /*
63135 ** Set a flag in the vdbe to update the change counter when it is finalised
63136 ** or reset.
63137 */
63138 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
63139   v->changeCntOn = 1;
63140 }
63141
63142 /*
63143 ** Mark every prepared statement associated with a database connection
63144 ** as expired.
63145 **
63146 ** An expired statement means that recompilation of the statement is
63147 ** recommend.  Statements expire when things happen that make their
63148 ** programs obsolete.  Removing user-defined functions or collating
63149 ** sequences, or changing an authorization function are the types of
63150 ** things that make prepared statements obsolete.
63151 */
63152 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
63153   Vdbe *p;
63154   for(p = db->pVdbe; p; p=p->pNext){
63155     p->expired = 1;
63156   }
63157 }
63158
63159 /*
63160 ** Return the database associated with the Vdbe.
63161 */
63162 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
63163   return v->db;
63164 }
63165
63166 /*
63167 ** Return a pointer to an sqlite3_value structure containing the value bound
63168 ** parameter iVar of VM v. Except, if the value is an SQL NULL, return 
63169 ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
63170 ** constants) to the value before returning it.
63171 **
63172 ** The returned value must be freed by the caller using sqlite3ValueFree().
63173 */
63174 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe *v, int iVar, u8 aff){
63175   assert( iVar>0 );
63176   if( v ){
63177     Mem *pMem = &v->aVar[iVar-1];
63178     if( 0==(pMem->flags & MEM_Null) ){
63179       sqlite3_value *pRet = sqlite3ValueNew(v->db);
63180       if( pRet ){
63181         sqlite3VdbeMemCopy((Mem *)pRet, pMem);
63182         sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
63183         sqlite3VdbeMemStoreType((Mem *)pRet);
63184       }
63185       return pRet;
63186     }
63187   }
63188   return 0;
63189 }
63190
63191 /*
63192 ** Configure SQL variable iVar so that binding a new value to it signals
63193 ** to sqlite3_reoptimize() that re-preparing the statement may result
63194 ** in a better query plan.
63195 */
63196 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
63197   assert( iVar>0 );
63198   if( iVar>32 ){
63199     v->expmask = 0xffffffff;
63200   }else{
63201     v->expmask |= ((u32)1 << (iVar-1));
63202   }
63203 }
63204
63205 /************** End of vdbeaux.c *********************************************/
63206 /************** Begin file vdbeapi.c *****************************************/
63207 /*
63208 ** 2004 May 26
63209 **
63210 ** The author disclaims copyright to this source code.  In place of
63211 ** a legal notice, here is a blessing:
63212 **
63213 **    May you do good and not evil.
63214 **    May you find forgiveness for yourself and forgive others.
63215 **    May you share freely, never taking more than you give.
63216 **
63217 *************************************************************************
63218 **
63219 ** This file contains code use to implement APIs that are part of the
63220 ** VDBE.
63221 */
63222
63223 #ifndef SQLITE_OMIT_DEPRECATED
63224 /*
63225 ** Return TRUE (non-zero) of the statement supplied as an argument needs
63226 ** to be recompiled.  A statement needs to be recompiled whenever the
63227 ** execution environment changes in a way that would alter the program
63228 ** that sqlite3_prepare() generates.  For example, if new functions or
63229 ** collating sequences are registered or if an authorizer function is
63230 ** added or changed.
63231 */
63232 SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
63233   Vdbe *p = (Vdbe*)pStmt;
63234   return p==0 || p->expired;
63235 }
63236 #endif
63237
63238 /*
63239 ** Check on a Vdbe to make sure it has not been finalized.  Log
63240 ** an error and return true if it has been finalized (or is otherwise
63241 ** invalid).  Return false if it is ok.
63242 */
63243 static int vdbeSafety(Vdbe *p){
63244   if( p->db==0 ){
63245     sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
63246     return 1;
63247   }else{
63248     return 0;
63249   }
63250 }
63251 static int vdbeSafetyNotNull(Vdbe *p){
63252   if( p==0 ){
63253     sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
63254     return 1;
63255   }else{
63256     return vdbeSafety(p);
63257   }
63258 }
63259
63260 /*
63261 ** The following routine destroys a virtual machine that is created by
63262 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
63263 ** success/failure code that describes the result of executing the virtual
63264 ** machine.
63265 **
63266 ** This routine sets the error code and string returned by
63267 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
63268 */
63269 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
63270   int rc;
63271   if( pStmt==0 ){
63272     /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
63273     ** pointer is a harmless no-op. */
63274     rc = SQLITE_OK;
63275   }else{
63276     Vdbe *v = (Vdbe*)pStmt;
63277     sqlite3 *db = v->db;
63278     if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
63279     sqlite3_mutex_enter(db->mutex);
63280     rc = sqlite3VdbeFinalize(v);
63281     rc = sqlite3ApiExit(db, rc);
63282     sqlite3LeaveMutexAndCloseZombie(db);
63283   }
63284   return rc;
63285 }
63286
63287 /*
63288 ** Terminate the current execution of an SQL statement and reset it
63289 ** back to its starting state so that it can be reused. A success code from
63290 ** the prior execution is returned.
63291 **
63292 ** This routine sets the error code and string returned by
63293 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
63294 */
63295 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
63296   int rc;
63297   if( pStmt==0 ){
63298     rc = SQLITE_OK;
63299   }else{
63300     Vdbe *v = (Vdbe*)pStmt;
63301     sqlite3_mutex_enter(v->db->mutex);
63302     rc = sqlite3VdbeReset(v);
63303     sqlite3VdbeRewind(v);
63304     assert( (rc & (v->db->errMask))==rc );
63305     rc = sqlite3ApiExit(v->db, rc);
63306     sqlite3_mutex_leave(v->db->mutex);
63307   }
63308   return rc;
63309 }
63310
63311 /*
63312 ** Set all the parameters in the compiled SQL statement to NULL.
63313 */
63314 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
63315   int i;
63316   int rc = SQLITE_OK;
63317   Vdbe *p = (Vdbe*)pStmt;
63318 #if SQLITE_THREADSAFE
63319   sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
63320 #endif
63321   sqlite3_mutex_enter(mutex);
63322   for(i=0; i<p->nVar; i++){
63323     sqlite3VdbeMemRelease(&p->aVar[i]);
63324     p->aVar[i].flags = MEM_Null;
63325   }
63326   if( p->isPrepareV2 && p->expmask ){
63327     p->expired = 1;
63328   }
63329   sqlite3_mutex_leave(mutex);
63330   return rc;
63331 }
63332
63333
63334 /**************************** sqlite3_value_  *******************************
63335 ** The following routines extract information from a Mem or sqlite3_value
63336 ** structure.
63337 */
63338 SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
63339   Mem *p = (Mem*)pVal;
63340   if( p->flags & (MEM_Blob|MEM_Str) ){
63341     sqlite3VdbeMemExpandBlob(p);
63342     p->flags &= ~MEM_Str;
63343     p->flags |= MEM_Blob;
63344     return p->n ? p->z : 0;
63345   }else{
63346     return sqlite3_value_text(pVal);
63347   }
63348 }
63349 SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
63350   return sqlite3ValueBytes(pVal, SQLITE_UTF8);
63351 }
63352 SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
63353   return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
63354 }
63355 SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
63356   return sqlite3VdbeRealValue((Mem*)pVal);
63357 }
63358 SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
63359   return (int)sqlite3VdbeIntValue((Mem*)pVal);
63360 }
63361 SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
63362   return sqlite3VdbeIntValue((Mem*)pVal);
63363 }
63364 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
63365   return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
63366 }
63367 #ifndef SQLITE_OMIT_UTF16
63368 SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
63369   return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
63370 }
63371 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
63372   return sqlite3ValueText(pVal, SQLITE_UTF16BE);
63373 }
63374 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
63375   return sqlite3ValueText(pVal, SQLITE_UTF16LE);
63376 }
63377 #endif /* SQLITE_OMIT_UTF16 */
63378 SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
63379   return pVal->type;
63380 }
63381
63382 /**************************** sqlite3_result_  *******************************
63383 ** The following routines are used by user-defined functions to specify
63384 ** the function result.
63385 **
63386 ** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the
63387 ** result as a string or blob but if the string or blob is too large, it
63388 ** then sets the error code to SQLITE_TOOBIG
63389 */
63390 static void setResultStrOrError(
63391   sqlite3_context *pCtx,  /* Function context */
63392   const char *z,          /* String pointer */
63393   int n,                  /* Bytes in string, or negative */
63394   u8 enc,                 /* Encoding of z.  0 for BLOBs */
63395   void (*xDel)(void*)     /* Destructor function */
63396 ){
63397   if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){
63398     sqlite3_result_error_toobig(pCtx);
63399   }
63400 }
63401 SQLITE_API void sqlite3_result_blob(
63402   sqlite3_context *pCtx, 
63403   const void *z, 
63404   int n, 
63405   void (*xDel)(void *)
63406 ){
63407   assert( n>=0 );
63408   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63409   setResultStrOrError(pCtx, z, n, 0, xDel);
63410 }
63411 SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
63412   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63413   sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
63414 }
63415 SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
63416   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63417   pCtx->isError = SQLITE_ERROR;
63418   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
63419 }
63420 #ifndef SQLITE_OMIT_UTF16
63421 SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
63422   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63423   pCtx->isError = SQLITE_ERROR;
63424   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
63425 }
63426 #endif
63427 SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
63428   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63429   sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
63430 }
63431 SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
63432   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63433   sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
63434 }
63435 SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
63436   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63437   sqlite3VdbeMemSetNull(&pCtx->s);
63438 }
63439 SQLITE_API void sqlite3_result_text(
63440   sqlite3_context *pCtx, 
63441   const char *z, 
63442   int n,
63443   void (*xDel)(void *)
63444 ){
63445   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63446   setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
63447 }
63448 #ifndef SQLITE_OMIT_UTF16
63449 SQLITE_API void sqlite3_result_text16(
63450   sqlite3_context *pCtx, 
63451   const void *z, 
63452   int n, 
63453   void (*xDel)(void *)
63454 ){
63455   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63456   setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
63457 }
63458 SQLITE_API void sqlite3_result_text16be(
63459   sqlite3_context *pCtx, 
63460   const void *z, 
63461   int n, 
63462   void (*xDel)(void *)
63463 ){
63464   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63465   setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
63466 }
63467 SQLITE_API void sqlite3_result_text16le(
63468   sqlite3_context *pCtx, 
63469   const void *z, 
63470   int n, 
63471   void (*xDel)(void *)
63472 ){
63473   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63474   setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
63475 }
63476 #endif /* SQLITE_OMIT_UTF16 */
63477 SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
63478   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63479   sqlite3VdbeMemCopy(&pCtx->s, pValue);
63480 }
63481 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
63482   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63483   sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
63484 }
63485 SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
63486   pCtx->isError = errCode;
63487   if( pCtx->s.flags & MEM_Null ){
63488     sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1, 
63489                          SQLITE_UTF8, SQLITE_STATIC);
63490   }
63491 }
63492
63493 /* Force an SQLITE_TOOBIG error. */
63494 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
63495   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63496   pCtx->isError = SQLITE_TOOBIG;
63497   sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1, 
63498                        SQLITE_UTF8, SQLITE_STATIC);
63499 }
63500
63501 /* An SQLITE_NOMEM error. */
63502 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
63503   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63504   sqlite3VdbeMemSetNull(&pCtx->s);
63505   pCtx->isError = SQLITE_NOMEM;
63506   pCtx->s.db->mallocFailed = 1;
63507 }
63508
63509 /*
63510 ** This function is called after a transaction has been committed. It 
63511 ** invokes callbacks registered with sqlite3_wal_hook() as required.
63512 */
63513 static int doWalCallbacks(sqlite3 *db){
63514   int rc = SQLITE_OK;
63515 #ifndef SQLITE_OMIT_WAL
63516   int i;
63517   for(i=0; i<db->nDb; i++){
63518     Btree *pBt = db->aDb[i].pBt;
63519     if( pBt ){
63520       int nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
63521       if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
63522         rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
63523       }
63524     }
63525   }
63526 #endif
63527   return rc;
63528 }
63529
63530 /*
63531 ** Execute the statement pStmt, either until a row of data is ready, the
63532 ** statement is completely executed or an error occurs.
63533 **
63534 ** This routine implements the bulk of the logic behind the sqlite_step()
63535 ** API.  The only thing omitted is the automatic recompile if a 
63536 ** schema change has occurred.  That detail is handled by the
63537 ** outer sqlite3_step() wrapper procedure.
63538 */
63539 static int sqlite3Step(Vdbe *p){
63540   sqlite3 *db;
63541   int rc;
63542
63543   assert(p);
63544   if( p->magic!=VDBE_MAGIC_RUN ){
63545     /* We used to require that sqlite3_reset() be called before retrying
63546     ** sqlite3_step() after any error or after SQLITE_DONE.  But beginning
63547     ** with version 3.7.0, we changed this so that sqlite3_reset() would
63548     ** be called automatically instead of throwing the SQLITE_MISUSE error.
63549     ** This "automatic-reset" change is not technically an incompatibility, 
63550     ** since any application that receives an SQLITE_MISUSE is broken by
63551     ** definition.
63552     **
63553     ** Nevertheless, some published applications that were originally written
63554     ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE 
63555     ** returns, and those were broken by the automatic-reset change.  As a
63556     ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
63557     ** legacy behavior of returning SQLITE_MISUSE for cases where the 
63558     ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
63559     ** or SQLITE_BUSY error.
63560     */
63561 #ifdef SQLITE_OMIT_AUTORESET
63562     if( p->rc==SQLITE_BUSY || p->rc==SQLITE_LOCKED ){
63563       sqlite3_reset((sqlite3_stmt*)p);
63564     }else{
63565       return SQLITE_MISUSE_BKPT;
63566     }
63567 #else
63568     sqlite3_reset((sqlite3_stmt*)p);
63569 #endif
63570   }
63571
63572   /* Check that malloc() has not failed. If it has, return early. */
63573   db = p->db;
63574   if( db->mallocFailed ){
63575     p->rc = SQLITE_NOMEM;
63576     return SQLITE_NOMEM;
63577   }
63578
63579   if( p->pc<=0 && p->expired ){
63580     p->rc = SQLITE_SCHEMA;
63581     rc = SQLITE_ERROR;
63582     goto end_of_step;
63583   }
63584   if( p->pc<0 ){
63585     /* If there are no other statements currently running, then
63586     ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
63587     ** from interrupting a statement that has not yet started.
63588     */
63589     if( db->activeVdbeCnt==0 ){
63590       db->u1.isInterrupted = 0;
63591     }
63592
63593     assert( db->writeVdbeCnt>0 || db->autoCommit==0 || db->nDeferredCons==0 );
63594
63595 #ifndef SQLITE_OMIT_TRACE
63596     if( db->xProfile && !db->init.busy ){
63597       sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
63598     }
63599 #endif
63600
63601     db->activeVdbeCnt++;
63602     if( p->readOnly==0 ) db->writeVdbeCnt++;
63603     p->pc = 0;
63604   }
63605 #ifndef SQLITE_OMIT_EXPLAIN
63606   if( p->explain ){
63607     rc = sqlite3VdbeList(p);
63608   }else
63609 #endif /* SQLITE_OMIT_EXPLAIN */
63610   {
63611     db->vdbeExecCnt++;
63612     rc = sqlite3VdbeExec(p);
63613     db->vdbeExecCnt--;
63614   }
63615
63616 #ifndef SQLITE_OMIT_TRACE
63617   /* Invoke the profile callback if there is one
63618   */
63619   if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
63620     sqlite3_int64 iNow;
63621     sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
63622     db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
63623   }
63624 #endif
63625
63626   if( rc==SQLITE_DONE ){
63627     assert( p->rc==SQLITE_OK );
63628     p->rc = doWalCallbacks(db);
63629     if( p->rc!=SQLITE_OK ){
63630       rc = SQLITE_ERROR;
63631     }
63632   }
63633
63634   db->errCode = rc;
63635   if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
63636     p->rc = SQLITE_NOMEM;
63637   }
63638 end_of_step:
63639   /* At this point local variable rc holds the value that should be 
63640   ** returned if this statement was compiled using the legacy 
63641   ** sqlite3_prepare() interface. According to the docs, this can only
63642   ** be one of the values in the first assert() below. Variable p->rc 
63643   ** contains the value that would be returned if sqlite3_finalize() 
63644   ** were called on statement p.
63645   */
63646   assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR 
63647        || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
63648   );
63649   assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
63650   if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
63651     /* If this statement was prepared using sqlite3_prepare_v2(), and an
63652     ** error has occurred, then return the error code in p->rc to the
63653     ** caller. Set the error code in the database handle to the same value.
63654     */ 
63655     rc = sqlite3VdbeTransferError(p);
63656   }
63657   return (rc&db->errMask);
63658 }
63659
63660 /*
63661 ** This is the top-level implementation of sqlite3_step().  Call
63662 ** sqlite3Step() to do most of the work.  If a schema error occurs,
63663 ** call sqlite3Reprepare() and try again.
63664 */
63665 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
63666   int rc = SQLITE_OK;      /* Result from sqlite3Step() */
63667   int rc2 = SQLITE_OK;     /* Result from sqlite3Reprepare() */
63668   Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */
63669   int cnt = 0;             /* Counter to prevent infinite loop of reprepares */
63670   sqlite3 *db;             /* The database connection */
63671
63672   if( vdbeSafetyNotNull(v) ){
63673     return SQLITE_MISUSE_BKPT;
63674   }
63675   db = v->db;
63676   sqlite3_mutex_enter(db->mutex);
63677   v->doingRerun = 0;
63678   while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
63679          && cnt++ < SQLITE_MAX_SCHEMA_RETRY
63680          && (rc2 = rc = sqlite3Reprepare(v))==SQLITE_OK ){
63681     sqlite3_reset(pStmt);
63682     v->doingRerun = 1;
63683     assert( v->expired==0 );
63684   }
63685   if( rc2!=SQLITE_OK && ALWAYS(v->isPrepareV2) && ALWAYS(db->pErr) ){
63686     /* This case occurs after failing to recompile an sql statement. 
63687     ** The error message from the SQL compiler has already been loaded 
63688     ** into the database handle. This block copies the error message 
63689     ** from the database handle into the statement and sets the statement
63690     ** program counter to 0 to ensure that when the statement is 
63691     ** finalized or reset the parser error message is available via
63692     ** sqlite3_errmsg() and sqlite3_errcode().
63693     */
63694     const char *zErr = (const char *)sqlite3_value_text(db->pErr); 
63695     sqlite3DbFree(db, v->zErrMsg);
63696     if( !db->mallocFailed ){
63697       v->zErrMsg = sqlite3DbStrDup(db, zErr);
63698       v->rc = rc2;
63699     } else {
63700       v->zErrMsg = 0;
63701       v->rc = rc = SQLITE_NOMEM;
63702     }
63703   }
63704   rc = sqlite3ApiExit(db, rc);
63705   sqlite3_mutex_leave(db->mutex);
63706   return rc;
63707 }
63708
63709 /*
63710 ** Extract the user data from a sqlite3_context structure and return a
63711 ** pointer to it.
63712 */
63713 SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
63714   assert( p && p->pFunc );
63715   return p->pFunc->pUserData;
63716 }
63717
63718 /*
63719 ** Extract the user data from a sqlite3_context structure and return a
63720 ** pointer to it.
63721 **
63722 ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
63723 ** returns a copy of the pointer to the database connection (the 1st
63724 ** parameter) of the sqlite3_create_function() and
63725 ** sqlite3_create_function16() routines that originally registered the
63726 ** application defined function.
63727 */
63728 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
63729   assert( p && p->pFunc );
63730   return p->s.db;
63731 }
63732
63733 /*
63734 ** The following is the implementation of an SQL function that always
63735 ** fails with an error message stating that the function is used in the
63736 ** wrong context.  The sqlite3_overload_function() API might construct
63737 ** SQL function that use this routine so that the functions will exist
63738 ** for name resolution but are actually overloaded by the xFindFunction
63739 ** method of virtual tables.
63740 */
63741 SQLITE_PRIVATE void sqlite3InvalidFunction(
63742   sqlite3_context *context,  /* The function calling context */
63743   int NotUsed,               /* Number of arguments to the function */
63744   sqlite3_value **NotUsed2   /* Value of each argument */
63745 ){
63746   const char *zName = context->pFunc->zName;
63747   char *zErr;
63748   UNUSED_PARAMETER2(NotUsed, NotUsed2);
63749   zErr = sqlite3_mprintf(
63750       "unable to use function %s in the requested context", zName);
63751   sqlite3_result_error(context, zErr, -1);
63752   sqlite3_free(zErr);
63753 }
63754
63755 /*
63756 ** Allocate or return the aggregate context for a user function.  A new
63757 ** context is allocated on the first call.  Subsequent calls return the
63758 ** same context that was returned on prior calls.
63759 */
63760 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
63761   Mem *pMem;
63762   assert( p && p->pFunc && p->pFunc->xStep );
63763   assert( sqlite3_mutex_held(p->s.db->mutex) );
63764   pMem = p->pMem;
63765   testcase( nByte<0 );
63766   if( (pMem->flags & MEM_Agg)==0 ){
63767     if( nByte<=0 ){
63768       sqlite3VdbeMemReleaseExternal(pMem);
63769       pMem->flags = MEM_Null;
63770       pMem->z = 0;
63771     }else{
63772       sqlite3VdbeMemGrow(pMem, nByte, 0);
63773       pMem->flags = MEM_Agg;
63774       pMem->u.pDef = p->pFunc;
63775       if( pMem->z ){
63776         memset(pMem->z, 0, nByte);
63777       }
63778     }
63779   }
63780   return (void*)pMem->z;
63781 }
63782
63783 /*
63784 ** Return the auxilary data pointer, if any, for the iArg'th argument to
63785 ** the user-function defined by pCtx.
63786 */
63787 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
63788   VdbeFunc *pVdbeFunc;
63789
63790   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63791   pVdbeFunc = pCtx->pVdbeFunc;
63792   if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
63793     return 0;
63794   }
63795   return pVdbeFunc->apAux[iArg].pAux;
63796 }
63797
63798 /*
63799 ** Set the auxilary data pointer and delete function, for the iArg'th
63800 ** argument to the user-function defined by pCtx. Any previous value is
63801 ** deleted by calling the delete function specified when it was set.
63802 */
63803 SQLITE_API void sqlite3_set_auxdata(
63804   sqlite3_context *pCtx, 
63805   int iArg, 
63806   void *pAux, 
63807   void (*xDelete)(void*)
63808 ){
63809   struct AuxData *pAuxData;
63810   VdbeFunc *pVdbeFunc;
63811   if( iArg<0 ) goto failed;
63812
63813   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
63814   pVdbeFunc = pCtx->pVdbeFunc;
63815   if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
63816     int nAux = (pVdbeFunc ? pVdbeFunc->nAux : 0);
63817     int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
63818     pVdbeFunc = sqlite3DbRealloc(pCtx->s.db, pVdbeFunc, nMalloc);
63819     if( !pVdbeFunc ){
63820       goto failed;
63821     }
63822     pCtx->pVdbeFunc = pVdbeFunc;
63823     memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
63824     pVdbeFunc->nAux = iArg+1;
63825     pVdbeFunc->pFunc = pCtx->pFunc;
63826   }
63827
63828   pAuxData = &pVdbeFunc->apAux[iArg];
63829   if( pAuxData->pAux && pAuxData->xDelete ){
63830     pAuxData->xDelete(pAuxData->pAux);
63831   }
63832   pAuxData->pAux = pAux;
63833   pAuxData->xDelete = xDelete;
63834   return;
63835
63836 failed:
63837   if( xDelete ){
63838     xDelete(pAux);
63839   }
63840 }
63841
63842 #ifndef SQLITE_OMIT_DEPRECATED
63843 /*
63844 ** Return the number of times the Step function of a aggregate has been 
63845 ** called.
63846 **
63847 ** This function is deprecated.  Do not use it for new code.  It is
63848 ** provide only to avoid breaking legacy code.  New aggregate function
63849 ** implementations should keep their own counts within their aggregate
63850 ** context.
63851 */
63852 SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
63853   assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
63854   return p->pMem->n;
63855 }
63856 #endif
63857
63858 /*
63859 ** Return the number of columns in the result set for the statement pStmt.
63860 */
63861 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
63862   Vdbe *pVm = (Vdbe *)pStmt;
63863   return pVm ? pVm->nResColumn : 0;
63864 }
63865
63866 /*
63867 ** Return the number of values available from the current row of the
63868 ** currently executing statement pStmt.
63869 */
63870 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
63871   Vdbe *pVm = (Vdbe *)pStmt;
63872   if( pVm==0 || pVm->pResultSet==0 ) return 0;
63873   return pVm->nResColumn;
63874 }
63875
63876
63877 /*
63878 ** Check to see if column iCol of the given statement is valid.  If
63879 ** it is, return a pointer to the Mem for the value of that column.
63880 ** If iCol is not valid, return a pointer to a Mem which has a value
63881 ** of NULL.
63882 */
63883 static Mem *columnMem(sqlite3_stmt *pStmt, int i){
63884   Vdbe *pVm;
63885   Mem *pOut;
63886
63887   pVm = (Vdbe *)pStmt;
63888   if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
63889     sqlite3_mutex_enter(pVm->db->mutex);
63890     pOut = &pVm->pResultSet[i];
63891   }else{
63892     /* If the value passed as the second argument is out of range, return
63893     ** a pointer to the following static Mem object which contains the
63894     ** value SQL NULL. Even though the Mem structure contains an element
63895     ** of type i64, on certain architectures (x86) with certain compiler
63896     ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
63897     ** instead of an 8-byte one. This all works fine, except that when
63898     ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
63899     ** that a Mem structure is located on an 8-byte boundary. To prevent
63900     ** these assert()s from failing, when building with SQLITE_DEBUG defined
63901     ** using gcc, we force nullMem to be 8-byte aligned using the magical
63902     ** __attribute__((aligned(8))) macro.  */
63903     static const Mem nullMem 
63904 #if defined(SQLITE_DEBUG) && defined(__GNUC__)
63905       __attribute__((aligned(8))) 
63906 #endif
63907       = {0, "", (double)0, {0}, 0, MEM_Null, SQLITE_NULL, 0,
63908 #ifdef SQLITE_DEBUG
63909          0, 0,  /* pScopyFrom, pFiller */
63910 #endif
63911          0, 0 };
63912
63913     if( pVm && ALWAYS(pVm->db) ){
63914       sqlite3_mutex_enter(pVm->db->mutex);
63915       sqlite3Error(pVm->db, SQLITE_RANGE, 0);
63916     }
63917     pOut = (Mem*)&nullMem;
63918   }
63919   return pOut;
63920 }
63921
63922 /*
63923 ** This function is called after invoking an sqlite3_value_XXX function on a 
63924 ** column value (i.e. a value returned by evaluating an SQL expression in the
63925 ** select list of a SELECT statement) that may cause a malloc() failure. If 
63926 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
63927 ** code of statement pStmt set to SQLITE_NOMEM.
63928 **
63929 ** Specifically, this is called from within:
63930 **
63931 **     sqlite3_column_int()
63932 **     sqlite3_column_int64()
63933 **     sqlite3_column_text()
63934 **     sqlite3_column_text16()
63935 **     sqlite3_column_real()
63936 **     sqlite3_column_bytes()
63937 **     sqlite3_column_bytes16()
63938 **     sqiite3_column_blob()
63939 */
63940 static void columnMallocFailure(sqlite3_stmt *pStmt)
63941 {
63942   /* If malloc() failed during an encoding conversion within an
63943   ** sqlite3_column_XXX API, then set the return code of the statement to
63944   ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
63945   ** and _finalize() will return NOMEM.
63946   */
63947   Vdbe *p = (Vdbe *)pStmt;
63948   if( p ){
63949     p->rc = sqlite3ApiExit(p->db, p->rc);
63950     sqlite3_mutex_leave(p->db->mutex);
63951   }
63952 }
63953
63954 /**************************** sqlite3_column_  *******************************
63955 ** The following routines are used to access elements of the current row
63956 ** in the result set.
63957 */
63958 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
63959   const void *val;
63960   val = sqlite3_value_blob( columnMem(pStmt,i) );
63961   /* Even though there is no encoding conversion, value_blob() might
63962   ** need to call malloc() to expand the result of a zeroblob() 
63963   ** expression. 
63964   */
63965   columnMallocFailure(pStmt);
63966   return val;
63967 }
63968 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
63969   int val = sqlite3_value_bytes( columnMem(pStmt,i) );
63970   columnMallocFailure(pStmt);
63971   return val;
63972 }
63973 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
63974   int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
63975   columnMallocFailure(pStmt);
63976   return val;
63977 }
63978 SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
63979   double val = sqlite3_value_double( columnMem(pStmt,i) );
63980   columnMallocFailure(pStmt);
63981   return val;
63982 }
63983 SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
63984   int val = sqlite3_value_int( columnMem(pStmt,i) );
63985   columnMallocFailure(pStmt);
63986   return val;
63987 }
63988 SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
63989   sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
63990   columnMallocFailure(pStmt);
63991   return val;
63992 }
63993 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
63994   const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
63995   columnMallocFailure(pStmt);
63996   return val;
63997 }
63998 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
63999   Mem *pOut = columnMem(pStmt, i);
64000   if( pOut->flags&MEM_Static ){
64001     pOut->flags &= ~MEM_Static;
64002     pOut->flags |= MEM_Ephem;
64003   }
64004   columnMallocFailure(pStmt);
64005   return (sqlite3_value *)pOut;
64006 }
64007 #ifndef SQLITE_OMIT_UTF16
64008 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
64009   const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
64010   columnMallocFailure(pStmt);
64011   return val;
64012 }
64013 #endif /* SQLITE_OMIT_UTF16 */
64014 SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
64015   int iType = sqlite3_value_type( columnMem(pStmt,i) );
64016   columnMallocFailure(pStmt);
64017   return iType;
64018 }
64019
64020 /* The following function is experimental and subject to change or
64021 ** removal */
64022 /*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
64023 **  return sqlite3_value_numeric_type( columnMem(pStmt,i) );
64024 **}
64025 */
64026
64027 /*
64028 ** Convert the N-th element of pStmt->pColName[] into a string using
64029 ** xFunc() then return that string.  If N is out of range, return 0.
64030 **
64031 ** There are up to 5 names for each column.  useType determines which
64032 ** name is returned.  Here are the names:
64033 **
64034 **    0      The column name as it should be displayed for output
64035 **    1      The datatype name for the column
64036 **    2      The name of the database that the column derives from
64037 **    3      The name of the table that the column derives from
64038 **    4      The name of the table column that the result column derives from
64039 **
64040 ** If the result is not a simple column reference (if it is an expression
64041 ** or a constant) then useTypes 2, 3, and 4 return NULL.
64042 */
64043 static const void *columnName(
64044   sqlite3_stmt *pStmt,
64045   int N,
64046   const void *(*xFunc)(Mem*),
64047   int useType
64048 ){
64049   const void *ret = 0;
64050   Vdbe *p = (Vdbe *)pStmt;
64051   int n;
64052   sqlite3 *db = p->db;
64053   
64054   assert( db!=0 );
64055   n = sqlite3_column_count(pStmt);
64056   if( N<n && N>=0 ){
64057     N += useType*n;
64058     sqlite3_mutex_enter(db->mutex);
64059     assert( db->mallocFailed==0 );
64060     ret = xFunc(&p->aColName[N]);
64061      /* A malloc may have failed inside of the xFunc() call. If this
64062     ** is the case, clear the mallocFailed flag and return NULL.
64063     */
64064     if( db->mallocFailed ){
64065       db->mallocFailed = 0;
64066       ret = 0;
64067     }
64068     sqlite3_mutex_leave(db->mutex);
64069   }
64070   return ret;
64071 }
64072
64073 /*
64074 ** Return the name of the Nth column of the result set returned by SQL
64075 ** statement pStmt.
64076 */
64077 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
64078   return columnName(
64079       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
64080 }
64081 #ifndef SQLITE_OMIT_UTF16
64082 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
64083   return columnName(
64084       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
64085 }
64086 #endif
64087
64088 /*
64089 ** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
64090 ** not define OMIT_DECLTYPE.
64091 */
64092 #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
64093 # error "Must not define both SQLITE_OMIT_DECLTYPE \
64094          and SQLITE_ENABLE_COLUMN_METADATA"
64095 #endif
64096
64097 #ifndef SQLITE_OMIT_DECLTYPE
64098 /*
64099 ** Return the column declaration type (if applicable) of the 'i'th column
64100 ** of the result set of SQL statement pStmt.
64101 */
64102 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
64103   return columnName(
64104       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
64105 }
64106 #ifndef SQLITE_OMIT_UTF16
64107 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
64108   return columnName(
64109       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
64110 }
64111 #endif /* SQLITE_OMIT_UTF16 */
64112 #endif /* SQLITE_OMIT_DECLTYPE */
64113
64114 #ifdef SQLITE_ENABLE_COLUMN_METADATA
64115 /*
64116 ** Return the name of the database from which a result column derives.
64117 ** NULL is returned if the result column is an expression or constant or
64118 ** anything else which is not an unabiguous reference to a database column.
64119 */
64120 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
64121   return columnName(
64122       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
64123 }
64124 #ifndef SQLITE_OMIT_UTF16
64125 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
64126   return columnName(
64127       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
64128 }
64129 #endif /* SQLITE_OMIT_UTF16 */
64130
64131 /*
64132 ** Return the name of the table from which a result column derives.
64133 ** NULL is returned if the result column is an expression or constant or
64134 ** anything else which is not an unabiguous reference to a database column.
64135 */
64136 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
64137   return columnName(
64138       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
64139 }
64140 #ifndef SQLITE_OMIT_UTF16
64141 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
64142   return columnName(
64143       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
64144 }
64145 #endif /* SQLITE_OMIT_UTF16 */
64146
64147 /*
64148 ** Return the name of the table column from which a result column derives.
64149 ** NULL is returned if the result column is an expression or constant or
64150 ** anything else which is not an unabiguous reference to a database column.
64151 */
64152 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
64153   return columnName(
64154       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
64155 }
64156 #ifndef SQLITE_OMIT_UTF16
64157 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
64158   return columnName(
64159       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
64160 }
64161 #endif /* SQLITE_OMIT_UTF16 */
64162 #endif /* SQLITE_ENABLE_COLUMN_METADATA */
64163
64164
64165 /******************************* sqlite3_bind_  ***************************
64166 ** 
64167 ** Routines used to attach values to wildcards in a compiled SQL statement.
64168 */
64169 /*
64170 ** Unbind the value bound to variable i in virtual machine p. This is the 
64171 ** the same as binding a NULL value to the column. If the "i" parameter is
64172 ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
64173 **
64174 ** A successful evaluation of this routine acquires the mutex on p.
64175 ** the mutex is released if any kind of error occurs.
64176 **
64177 ** The error code stored in database p->db is overwritten with the return
64178 ** value in any case.
64179 */
64180 static int vdbeUnbind(Vdbe *p, int i){
64181   Mem *pVar;
64182   if( vdbeSafetyNotNull(p) ){
64183     return SQLITE_MISUSE_BKPT;
64184   }
64185   sqlite3_mutex_enter(p->db->mutex);
64186   if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
64187     sqlite3Error(p->db, SQLITE_MISUSE, 0);
64188     sqlite3_mutex_leave(p->db->mutex);
64189     sqlite3_log(SQLITE_MISUSE, 
64190         "bind on a busy prepared statement: [%s]", p->zSql);
64191     return SQLITE_MISUSE_BKPT;
64192   }
64193   if( i<1 || i>p->nVar ){
64194     sqlite3Error(p->db, SQLITE_RANGE, 0);
64195     sqlite3_mutex_leave(p->db->mutex);
64196     return SQLITE_RANGE;
64197   }
64198   i--;
64199   pVar = &p->aVar[i];
64200   sqlite3VdbeMemRelease(pVar);
64201   pVar->flags = MEM_Null;
64202   sqlite3Error(p->db, SQLITE_OK, 0);
64203
64204   /* If the bit corresponding to this variable in Vdbe.expmask is set, then 
64205   ** binding a new value to this variable invalidates the current query plan.
64206   **
64207   ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
64208   ** parameter in the WHERE clause might influence the choice of query plan
64209   ** for a statement, then the statement will be automatically recompiled,
64210   ** as if there had been a schema change, on the first sqlite3_step() call
64211   ** following any change to the bindings of that parameter.
64212   */
64213   if( p->isPrepareV2 &&
64214      ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
64215   ){
64216     p->expired = 1;
64217   }
64218   return SQLITE_OK;
64219 }
64220
64221 /*
64222 ** Bind a text or BLOB value.
64223 */
64224 static int bindText(
64225   sqlite3_stmt *pStmt,   /* The statement to bind against */
64226   int i,                 /* Index of the parameter to bind */
64227   const void *zData,     /* Pointer to the data to be bound */
64228   int nData,             /* Number of bytes of data to be bound */
64229   void (*xDel)(void*),   /* Destructor for the data */
64230   u8 encoding            /* Encoding for the data */
64231 ){
64232   Vdbe *p = (Vdbe *)pStmt;
64233   Mem *pVar;
64234   int rc;
64235
64236   rc = vdbeUnbind(p, i);
64237   if( rc==SQLITE_OK ){
64238     if( zData!=0 ){
64239       pVar = &p->aVar[i-1];
64240       rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
64241       if( rc==SQLITE_OK && encoding!=0 ){
64242         rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
64243       }
64244       sqlite3Error(p->db, rc, 0);
64245       rc = sqlite3ApiExit(p->db, rc);
64246     }
64247     sqlite3_mutex_leave(p->db->mutex);
64248   }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
64249     xDel((void*)zData);
64250   }
64251   return rc;
64252 }
64253
64254
64255 /*
64256 ** Bind a blob value to an SQL statement variable.
64257 */
64258 SQLITE_API int sqlite3_bind_blob(
64259   sqlite3_stmt *pStmt, 
64260   int i, 
64261   const void *zData, 
64262   int nData, 
64263   void (*xDel)(void*)
64264 ){
64265   return bindText(pStmt, i, zData, nData, xDel, 0);
64266 }
64267 SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
64268   int rc;
64269   Vdbe *p = (Vdbe *)pStmt;
64270   rc = vdbeUnbind(p, i);
64271   if( rc==SQLITE_OK ){
64272     sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
64273     sqlite3_mutex_leave(p->db->mutex);
64274   }
64275   return rc;
64276 }
64277 SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
64278   return sqlite3_bind_int64(p, i, (i64)iValue);
64279 }
64280 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
64281   int rc;
64282   Vdbe *p = (Vdbe *)pStmt;
64283   rc = vdbeUnbind(p, i);
64284   if( rc==SQLITE_OK ){
64285     sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
64286     sqlite3_mutex_leave(p->db->mutex);
64287   }
64288   return rc;
64289 }
64290 SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
64291   int rc;
64292   Vdbe *p = (Vdbe*)pStmt;
64293   rc = vdbeUnbind(p, i);
64294   if( rc==SQLITE_OK ){
64295     sqlite3_mutex_leave(p->db->mutex);
64296   }
64297   return rc;
64298 }
64299 SQLITE_API int sqlite3_bind_text( 
64300   sqlite3_stmt *pStmt, 
64301   int i, 
64302   const char *zData, 
64303   int nData, 
64304   void (*xDel)(void*)
64305 ){
64306   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
64307 }
64308 #ifndef SQLITE_OMIT_UTF16
64309 SQLITE_API int sqlite3_bind_text16(
64310   sqlite3_stmt *pStmt, 
64311   int i, 
64312   const void *zData, 
64313   int nData, 
64314   void (*xDel)(void*)
64315 ){
64316   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
64317 }
64318 #endif /* SQLITE_OMIT_UTF16 */
64319 SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
64320   int rc;
64321   switch( pValue->type ){
64322     case SQLITE_INTEGER: {
64323       rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
64324       break;
64325     }
64326     case SQLITE_FLOAT: {
64327       rc = sqlite3_bind_double(pStmt, i, pValue->r);
64328       break;
64329     }
64330     case SQLITE_BLOB: {
64331       if( pValue->flags & MEM_Zero ){
64332         rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
64333       }else{
64334         rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
64335       }
64336       break;
64337     }
64338     case SQLITE_TEXT: {
64339       rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
64340                               pValue->enc);
64341       break;
64342     }
64343     default: {
64344       rc = sqlite3_bind_null(pStmt, i);
64345       break;
64346     }
64347   }
64348   return rc;
64349 }
64350 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
64351   int rc;
64352   Vdbe *p = (Vdbe *)pStmt;
64353   rc = vdbeUnbind(p, i);
64354   if( rc==SQLITE_OK ){
64355     sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
64356     sqlite3_mutex_leave(p->db->mutex);
64357   }
64358   return rc;
64359 }
64360
64361 /*
64362 ** Return the number of wildcards that can be potentially bound to.
64363 ** This routine is added to support DBD::SQLite.  
64364 */
64365 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
64366   Vdbe *p = (Vdbe*)pStmt;
64367   return p ? p->nVar : 0;
64368 }
64369
64370 /*
64371 ** Return the name of a wildcard parameter.  Return NULL if the index
64372 ** is out of range or if the wildcard is unnamed.
64373 **
64374 ** The result is always UTF-8.
64375 */
64376 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
64377   Vdbe *p = (Vdbe*)pStmt;
64378   if( p==0 || i<1 || i>p->nzVar ){
64379     return 0;
64380   }
64381   return p->azVar[i-1];
64382 }
64383
64384 /*
64385 ** Given a wildcard parameter name, return the index of the variable
64386 ** with that name.  If there is no variable with the given name,
64387 ** return 0.
64388 */
64389 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
64390   int i;
64391   if( p==0 ){
64392     return 0;
64393   }
64394   if( zName ){
64395     for(i=0; i<p->nzVar; i++){
64396       const char *z = p->azVar[i];
64397       if( z && strncmp(z,zName,nName)==0 && z[nName]==0 ){
64398         return i+1;
64399       }
64400     }
64401   }
64402   return 0;
64403 }
64404 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
64405   return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
64406 }
64407
64408 /*
64409 ** Transfer all bindings from the first statement over to the second.
64410 */
64411 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
64412   Vdbe *pFrom = (Vdbe*)pFromStmt;
64413   Vdbe *pTo = (Vdbe*)pToStmt;
64414   int i;
64415   assert( pTo->db==pFrom->db );
64416   assert( pTo->nVar==pFrom->nVar );
64417   sqlite3_mutex_enter(pTo->db->mutex);
64418   for(i=0; i<pFrom->nVar; i++){
64419     sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
64420   }
64421   sqlite3_mutex_leave(pTo->db->mutex);
64422   return SQLITE_OK;
64423 }
64424
64425 #ifndef SQLITE_OMIT_DEPRECATED
64426 /*
64427 ** Deprecated external interface.  Internal/core SQLite code
64428 ** should call sqlite3TransferBindings.
64429 **
64430 ** Is is misuse to call this routine with statements from different
64431 ** database connections.  But as this is a deprecated interface, we
64432 ** will not bother to check for that condition.
64433 **
64434 ** If the two statements contain a different number of bindings, then
64435 ** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
64436 ** SQLITE_OK is returned.
64437 */
64438 SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
64439   Vdbe *pFrom = (Vdbe*)pFromStmt;
64440   Vdbe *pTo = (Vdbe*)pToStmt;
64441   if( pFrom->nVar!=pTo->nVar ){
64442     return SQLITE_ERROR;
64443   }
64444   if( pTo->isPrepareV2 && pTo->expmask ){
64445     pTo->expired = 1;
64446   }
64447   if( pFrom->isPrepareV2 && pFrom->expmask ){
64448     pFrom->expired = 1;
64449   }
64450   return sqlite3TransferBindings(pFromStmt, pToStmt);
64451 }
64452 #endif
64453
64454 /*
64455 ** Return the sqlite3* database handle to which the prepared statement given
64456 ** in the argument belongs.  This is the same database handle that was
64457 ** the first argument to the sqlite3_prepare() that was used to create
64458 ** the statement in the first place.
64459 */
64460 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
64461   return pStmt ? ((Vdbe*)pStmt)->db : 0;
64462 }
64463
64464 /*
64465 ** Return true if the prepared statement is guaranteed to not modify the
64466 ** database.
64467 */
64468 SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
64469   return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
64470 }
64471
64472 /*
64473 ** Return true if the prepared statement is in need of being reset.
64474 */
64475 SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
64476   Vdbe *v = (Vdbe*)pStmt;
64477   return v!=0 && v->pc>0 && v->magic==VDBE_MAGIC_RUN;
64478 }
64479
64480 /*
64481 ** Return a pointer to the next prepared statement after pStmt associated
64482 ** with database connection pDb.  If pStmt is NULL, return the first
64483 ** prepared statement for the database connection.  Return NULL if there
64484 ** are no more.
64485 */
64486 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
64487   sqlite3_stmt *pNext;
64488   sqlite3_mutex_enter(pDb->mutex);
64489   if( pStmt==0 ){
64490     pNext = (sqlite3_stmt*)pDb->pVdbe;
64491   }else{
64492     pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
64493   }
64494   sqlite3_mutex_leave(pDb->mutex);
64495   return pNext;
64496 }
64497
64498 /*
64499 ** Return the value of a status counter for a prepared statement
64500 */
64501 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
64502   Vdbe *pVdbe = (Vdbe*)pStmt;
64503   int v = pVdbe->aCounter[op-1];
64504   if( resetFlag ) pVdbe->aCounter[op-1] = 0;
64505   return v;
64506 }
64507
64508 /************** End of vdbeapi.c *********************************************/
64509 /************** Begin file vdbetrace.c ***************************************/
64510 /*
64511 ** 2009 November 25
64512 **
64513 ** The author disclaims copyright to this source code.  In place of
64514 ** a legal notice, here is a blessing:
64515 **
64516 **    May you do good and not evil.
64517 **    May you find forgiveness for yourself and forgive others.
64518 **    May you share freely, never taking more than you give.
64519 **
64520 *************************************************************************
64521 **
64522 ** This file contains code used to insert the values of host parameters
64523 ** (aka "wildcards") into the SQL text output by sqlite3_trace().
64524 **
64525 ** The Vdbe parse-tree explainer is also found here.
64526 */
64527
64528 #ifndef SQLITE_OMIT_TRACE
64529
64530 /*
64531 ** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of
64532 ** bytes in this text up to but excluding the first character in
64533 ** a host parameter.  If the text contains no host parameters, return
64534 ** the total number of bytes in the text.
64535 */
64536 static int findNextHostParameter(const char *zSql, int *pnToken){
64537   int tokenType;
64538   int nTotal = 0;
64539   int n;
64540
64541   *pnToken = 0;
64542   while( zSql[0] ){
64543     n = sqlite3GetToken((u8*)zSql, &tokenType);
64544     assert( n>0 && tokenType!=TK_ILLEGAL );
64545     if( tokenType==TK_VARIABLE ){
64546       *pnToken = n;
64547       break;
64548     }
64549     nTotal += n;
64550     zSql += n;
64551   }
64552   return nTotal;
64553 }
64554
64555 /*
64556 ** This function returns a pointer to a nul-terminated string in memory
64557 ** obtained from sqlite3DbMalloc(). If sqlite3.vdbeExecCnt is 1, then the
64558 ** string contains a copy of zRawSql but with host parameters expanded to 
64559 ** their current bindings. Or, if sqlite3.vdbeExecCnt is greater than 1, 
64560 ** then the returned string holds a copy of zRawSql with "-- " prepended
64561 ** to each line of text.
64562 **
64563 ** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then
64564 ** then long strings and blobs are truncated to that many bytes.  This
64565 ** can be used to prevent unreasonably large trace strings when dealing
64566 ** with large (multi-megabyte) strings and blobs.
64567 **
64568 ** The calling function is responsible for making sure the memory returned
64569 ** is eventually freed.
64570 **
64571 ** ALGORITHM:  Scan the input string looking for host parameters in any of
64572 ** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
64573 ** string literals, quoted identifier names, and comments.  For text forms,
64574 ** the host parameter index is found by scanning the perpared
64575 ** statement for the corresponding OP_Variable opcode.  Once the host
64576 ** parameter index is known, locate the value in p->aVar[].  Then render
64577 ** the value as a literal in place of the host parameter name.
64578 */
64579 SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
64580   Vdbe *p,                 /* The prepared statement being evaluated */
64581   const char *zRawSql      /* Raw text of the SQL statement */
64582 ){
64583   sqlite3 *db;             /* The database connection */
64584   int idx = 0;             /* Index of a host parameter */
64585   int nextIndex = 1;       /* Index of next ? host parameter */
64586   int n;                   /* Length of a token prefix */
64587   int nToken;              /* Length of the parameter token */
64588   int i;                   /* Loop counter */
64589   Mem *pVar;               /* Value of a host parameter */
64590   StrAccum out;            /* Accumulate the output here */
64591   char zBase[100];         /* Initial working space */
64592
64593   db = p->db;
64594   sqlite3StrAccumInit(&out, zBase, sizeof(zBase), 
64595                       db->aLimit[SQLITE_LIMIT_LENGTH]);
64596   out.db = db;
64597   if( db->vdbeExecCnt>1 ){
64598     while( *zRawSql ){
64599       const char *zStart = zRawSql;
64600       while( *(zRawSql++)!='\n' && *zRawSql );
64601       sqlite3StrAccumAppend(&out, "-- ", 3);
64602       sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
64603     }
64604   }else{
64605     while( zRawSql[0] ){
64606       n = findNextHostParameter(zRawSql, &nToken);
64607       assert( n>0 );
64608       sqlite3StrAccumAppend(&out, zRawSql, n);
64609       zRawSql += n;
64610       assert( zRawSql[0] || nToken==0 );
64611       if( nToken==0 ) break;
64612       if( zRawSql[0]=='?' ){
64613         if( nToken>1 ){
64614           assert( sqlite3Isdigit(zRawSql[1]) );
64615           sqlite3GetInt32(&zRawSql[1], &idx);
64616         }else{
64617           idx = nextIndex;
64618         }
64619       }else{
64620         assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
64621         testcase( zRawSql[0]==':' );
64622         testcase( zRawSql[0]=='$' );
64623         testcase( zRawSql[0]=='@' );
64624         idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
64625         assert( idx>0 );
64626       }
64627       zRawSql += nToken;
64628       nextIndex = idx + 1;
64629       assert( idx>0 && idx<=p->nVar );
64630       pVar = &p->aVar[idx-1];
64631       if( pVar->flags & MEM_Null ){
64632         sqlite3StrAccumAppend(&out, "NULL", 4);
64633       }else if( pVar->flags & MEM_Int ){
64634         sqlite3XPrintf(&out, "%lld", pVar->u.i);
64635       }else if( pVar->flags & MEM_Real ){
64636         sqlite3XPrintf(&out, "%!.15g", pVar->r);
64637       }else if( pVar->flags & MEM_Str ){
64638         int nOut;  /* Number of bytes of the string text to include in output */
64639 #ifndef SQLITE_OMIT_UTF16
64640         u8 enc = ENC(db);
64641         Mem utf8;
64642         if( enc!=SQLITE_UTF8 ){
64643           memset(&utf8, 0, sizeof(utf8));
64644           utf8.db = db;
64645           sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
64646           sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
64647           pVar = &utf8;
64648         }
64649 #endif
64650         nOut = pVar->n;
64651 #ifdef SQLITE_TRACE_SIZE_LIMIT
64652         if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
64653           nOut = SQLITE_TRACE_SIZE_LIMIT;
64654           while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
64655         }
64656 #endif    
64657         sqlite3XPrintf(&out, "'%.*q'", nOut, pVar->z);
64658 #ifdef SQLITE_TRACE_SIZE_LIMIT
64659         if( nOut<pVar->n ) sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
64660 #endif
64661 #ifndef SQLITE_OMIT_UTF16
64662         if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
64663 #endif
64664       }else if( pVar->flags & MEM_Zero ){
64665         sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
64666       }else{
64667         int nOut;  /* Number of bytes of the blob to include in output */
64668         assert( pVar->flags & MEM_Blob );
64669         sqlite3StrAccumAppend(&out, "x'", 2);
64670         nOut = pVar->n;
64671 #ifdef SQLITE_TRACE_SIZE_LIMIT
64672         if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;
64673 #endif
64674         for(i=0; i<nOut; i++){
64675           sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
64676         }
64677         sqlite3StrAccumAppend(&out, "'", 1);
64678 #ifdef SQLITE_TRACE_SIZE_LIMIT
64679         if( nOut<pVar->n ) sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
64680 #endif
64681       }
64682     }
64683   }
64684   return sqlite3StrAccumFinish(&out);
64685 }
64686
64687 #endif /* #ifndef SQLITE_OMIT_TRACE */
64688
64689 /*****************************************************************************
64690 ** The following code implements the data-structure explaining logic
64691 ** for the Vdbe.
64692 */
64693
64694 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
64695
64696 /*
64697 ** Allocate a new Explain object
64698 */
64699 SQLITE_PRIVATE void sqlite3ExplainBegin(Vdbe *pVdbe){
64700   if( pVdbe ){
64701     Explain *p;
64702     sqlite3BeginBenignMalloc();
64703     p = (Explain *)sqlite3MallocZero( sizeof(Explain) );
64704     if( p ){
64705       p->pVdbe = pVdbe;
64706       sqlite3_free(pVdbe->pExplain);
64707       pVdbe->pExplain = p;
64708       sqlite3StrAccumInit(&p->str, p->zBase, sizeof(p->zBase),
64709                           SQLITE_MAX_LENGTH);
64710       p->str.useMalloc = 2;
64711     }else{
64712       sqlite3EndBenignMalloc();
64713     }
64714   }
64715 }
64716
64717 /*
64718 ** Return true if the Explain ends with a new-line.
64719 */
64720 static int endsWithNL(Explain *p){
64721   return p && p->str.zText && p->str.nChar
64722            && p->str.zText[p->str.nChar-1]=='\n';
64723 }
64724     
64725 /*
64726 ** Append text to the indentation
64727 */
64728 SQLITE_PRIVATE void sqlite3ExplainPrintf(Vdbe *pVdbe, const char *zFormat, ...){
64729   Explain *p;
64730   if( pVdbe && (p = pVdbe->pExplain)!=0 ){
64731     va_list ap;
64732     if( p->nIndent && endsWithNL(p) ){
64733       int n = p->nIndent;
64734       if( n>ArraySize(p->aIndent) ) n = ArraySize(p->aIndent);
64735       sqlite3AppendSpace(&p->str, p->aIndent[n-1]);
64736     }   
64737     va_start(ap, zFormat);
64738     sqlite3VXPrintf(&p->str, 1, zFormat, ap);
64739     va_end(ap);
64740   }
64741 }
64742
64743 /*
64744 ** Append a '\n' if there is not already one.
64745 */
64746 SQLITE_PRIVATE void sqlite3ExplainNL(Vdbe *pVdbe){
64747   Explain *p;
64748   if( pVdbe && (p = pVdbe->pExplain)!=0 && !endsWithNL(p) ){
64749     sqlite3StrAccumAppend(&p->str, "\n", 1);
64750   }
64751 }
64752
64753 /*
64754 ** Push a new indentation level.  Subsequent lines will be indented
64755 ** so that they begin at the current cursor position.
64756 */
64757 SQLITE_PRIVATE void sqlite3ExplainPush(Vdbe *pVdbe){
64758   Explain *p;
64759   if( pVdbe && (p = pVdbe->pExplain)!=0 ){
64760     if( p->str.zText && p->nIndent<ArraySize(p->aIndent) ){
64761       const char *z = p->str.zText;
64762       int i = p->str.nChar-1;
64763       int x;
64764       while( i>=0 && z[i]!='\n' ){ i--; }
64765       x = (p->str.nChar - 1) - i;
64766       if( p->nIndent && x<p->aIndent[p->nIndent-1] ){
64767         x = p->aIndent[p->nIndent-1];
64768       }
64769       p->aIndent[p->nIndent] = x;
64770     }
64771     p->nIndent++;
64772   }
64773 }
64774
64775 /*
64776 ** Pop the indentation stack by one level.
64777 */
64778 SQLITE_PRIVATE void sqlite3ExplainPop(Vdbe *p){
64779   if( p && p->pExplain ) p->pExplain->nIndent--;
64780 }
64781
64782 /*
64783 ** Free the indentation structure
64784 */
64785 SQLITE_PRIVATE void sqlite3ExplainFinish(Vdbe *pVdbe){
64786   if( pVdbe && pVdbe->pExplain ){
64787     sqlite3_free(pVdbe->zExplain);
64788     sqlite3ExplainNL(pVdbe);
64789     pVdbe->zExplain = sqlite3StrAccumFinish(&pVdbe->pExplain->str);
64790     sqlite3_free(pVdbe->pExplain);
64791     pVdbe->pExplain = 0;
64792     sqlite3EndBenignMalloc();
64793   }
64794 }
64795
64796 /*
64797 ** Return the explanation of a virtual machine.
64798 */
64799 SQLITE_PRIVATE const char *sqlite3VdbeExplanation(Vdbe *pVdbe){
64800   return (pVdbe && pVdbe->zExplain) ? pVdbe->zExplain : 0;
64801 }
64802 #endif /* defined(SQLITE_DEBUG) */
64803
64804 /************** End of vdbetrace.c *******************************************/
64805 /************** Begin file vdbe.c ********************************************/
64806 /*
64807 ** 2001 September 15
64808 **
64809 ** The author disclaims copyright to this source code.  In place of
64810 ** a legal notice, here is a blessing:
64811 **
64812 **    May you do good and not evil.
64813 **    May you find forgiveness for yourself and forgive others.
64814 **    May you share freely, never taking more than you give.
64815 **
64816 *************************************************************************
64817 ** The code in this file implements execution method of the 
64818 ** Virtual Database Engine (VDBE).  A separate file ("vdbeaux.c")
64819 ** handles housekeeping details such as creating and deleting
64820 ** VDBE instances.  This file is solely interested in executing
64821 ** the VDBE program.
64822 **
64823 ** In the external interface, an "sqlite3_stmt*" is an opaque pointer
64824 ** to a VDBE.
64825 **
64826 ** The SQL parser generates a program which is then executed by
64827 ** the VDBE to do the work of the SQL statement.  VDBE programs are 
64828 ** similar in form to assembly language.  The program consists of
64829 ** a linear sequence of operations.  Each operation has an opcode 
64830 ** and 5 operands.  Operands P1, P2, and P3 are integers.  Operand P4 
64831 ** is a null-terminated string.  Operand P5 is an unsigned character.
64832 ** Few opcodes use all 5 operands.
64833 **
64834 ** Computation results are stored on a set of registers numbered beginning
64835 ** with 1 and going up to Vdbe.nMem.  Each register can store
64836 ** either an integer, a null-terminated string, a floating point
64837 ** number, or the SQL "NULL" value.  An implicit conversion from one
64838 ** type to the other occurs as necessary.
64839 ** 
64840 ** Most of the code in this file is taken up by the sqlite3VdbeExec()
64841 ** function which does the work of interpreting a VDBE program.
64842 ** But other routines are also provided to help in building up
64843 ** a program instruction by instruction.
64844 **
64845 ** Various scripts scan this source file in order to generate HTML
64846 ** documentation, headers files, or other derived files.  The formatting
64847 ** of the code in this file is, therefore, important.  See other comments
64848 ** in this file for details.  If in doubt, do not deviate from existing
64849 ** commenting and indentation practices when changing or adding code.
64850 */
64851
64852 /*
64853 ** Invoke this macro on memory cells just prior to changing the
64854 ** value of the cell.  This macro verifies that shallow copies are
64855 ** not misused.
64856 */
64857 #ifdef SQLITE_DEBUG
64858 # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
64859 #else
64860 # define memAboutToChange(P,M)
64861 #endif
64862
64863 /*
64864 ** The following global variable is incremented every time a cursor
64865 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
64866 ** procedures use this information to make sure that indices are
64867 ** working correctly.  This variable has no function other than to
64868 ** help verify the correct operation of the library.
64869 */
64870 #ifdef SQLITE_TEST
64871 SQLITE_API int sqlite3_search_count = 0;
64872 #endif
64873
64874 /*
64875 ** When this global variable is positive, it gets decremented once before
64876 ** each instruction in the VDBE.  When it reaches zero, the u1.isInterrupted
64877 ** field of the sqlite3 structure is set in order to simulate an interrupt.
64878 **
64879 ** This facility is used for testing purposes only.  It does not function
64880 ** in an ordinary build.
64881 */
64882 #ifdef SQLITE_TEST
64883 SQLITE_API int sqlite3_interrupt_count = 0;
64884 #endif
64885
64886 /*
64887 ** The next global variable is incremented each type the OP_Sort opcode
64888 ** is executed.  The test procedures use this information to make sure that
64889 ** sorting is occurring or not occurring at appropriate times.   This variable
64890 ** has no function other than to help verify the correct operation of the
64891 ** library.
64892 */
64893 #ifdef SQLITE_TEST
64894 SQLITE_API int sqlite3_sort_count = 0;
64895 #endif
64896
64897 /*
64898 ** The next global variable records the size of the largest MEM_Blob
64899 ** or MEM_Str that has been used by a VDBE opcode.  The test procedures
64900 ** use this information to make sure that the zero-blob functionality
64901 ** is working correctly.   This variable has no function other than to
64902 ** help verify the correct operation of the library.
64903 */
64904 #ifdef SQLITE_TEST
64905 SQLITE_API int sqlite3_max_blobsize = 0;
64906 static void updateMaxBlobsize(Mem *p){
64907   if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
64908     sqlite3_max_blobsize = p->n;
64909   }
64910 }
64911 #endif
64912
64913 /*
64914 ** The next global variable is incremented each type the OP_Found opcode
64915 ** is executed. This is used to test whether or not the foreign key
64916 ** operation implemented using OP_FkIsZero is working. This variable
64917 ** has no function other than to help verify the correct operation of the
64918 ** library.
64919 */
64920 #ifdef SQLITE_TEST
64921 SQLITE_API int sqlite3_found_count = 0;
64922 #endif
64923
64924 /*
64925 ** Test a register to see if it exceeds the current maximum blob size.
64926 ** If it does, record the new maximum blob size.
64927 */
64928 #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
64929 # define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
64930 #else
64931 # define UPDATE_MAX_BLOBSIZE(P)
64932 #endif
64933
64934 /*
64935 ** Convert the given register into a string if it isn't one
64936 ** already. Return non-zero if a malloc() fails.
64937 */
64938 #define Stringify(P, enc) \
64939    if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
64940      { goto no_mem; }
64941
64942 /*
64943 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
64944 ** a pointer to a dynamically allocated string where some other entity
64945 ** is responsible for deallocating that string.  Because the register
64946 ** does not control the string, it might be deleted without the register
64947 ** knowing it.
64948 **
64949 ** This routine converts an ephemeral string into a dynamically allocated
64950 ** string that the register itself controls.  In other words, it
64951 ** converts an MEM_Ephem string into an MEM_Dyn string.
64952 */
64953 #define Deephemeralize(P) \
64954    if( ((P)->flags&MEM_Ephem)!=0 \
64955        && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
64956
64957 /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
64958 # define isSorter(x) ((x)->pSorter!=0)
64959
64960 /*
64961 ** Argument pMem points at a register that will be passed to a
64962 ** user-defined function or returned to the user as the result of a query.
64963 ** This routine sets the pMem->type variable used by the sqlite3_value_*() 
64964 ** routines.
64965 */
64966 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem){
64967   int flags = pMem->flags;
64968   if( flags & MEM_Null ){
64969     pMem->type = SQLITE_NULL;
64970   }
64971   else if( flags & MEM_Int ){
64972     pMem->type = SQLITE_INTEGER;
64973   }
64974   else if( flags & MEM_Real ){
64975     pMem->type = SQLITE_FLOAT;
64976   }
64977   else if( flags & MEM_Str ){
64978     pMem->type = SQLITE_TEXT;
64979   }else{
64980     pMem->type = SQLITE_BLOB;
64981   }
64982 }
64983
64984 /*
64985 ** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
64986 ** if we run out of memory.
64987 */
64988 static VdbeCursor *allocateCursor(
64989   Vdbe *p,              /* The virtual machine */
64990   int iCur,             /* Index of the new VdbeCursor */
64991   int nField,           /* Number of fields in the table or index */
64992   int iDb,              /* Database the cursor belongs to, or -1 */
64993   int isBtreeCursor     /* True for B-Tree.  False for pseudo-table or vtab */
64994 ){
64995   /* Find the memory cell that will be used to store the blob of memory
64996   ** required for this VdbeCursor structure. It is convenient to use a 
64997   ** vdbe memory cell to manage the memory allocation required for a
64998   ** VdbeCursor structure for the following reasons:
64999   **
65000   **   * Sometimes cursor numbers are used for a couple of different
65001   **     purposes in a vdbe program. The different uses might require
65002   **     different sized allocations. Memory cells provide growable
65003   **     allocations.
65004   **
65005   **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
65006   **     be freed lazily via the sqlite3_release_memory() API. This
65007   **     minimizes the number of malloc calls made by the system.
65008   **
65009   ** Memory cells for cursors are allocated at the top of the address
65010   ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
65011   ** cursor 1 is managed by memory cell (p->nMem-1), etc.
65012   */
65013   Mem *pMem = &p->aMem[p->nMem-iCur];
65014
65015   int nByte;
65016   VdbeCursor *pCx = 0;
65017   nByte = 
65018       ROUND8(sizeof(VdbeCursor)) + 
65019       (isBtreeCursor?sqlite3BtreeCursorSize():0) + 
65020       2*nField*sizeof(u32);
65021
65022   assert( iCur<p->nCursor );
65023   if( p->apCsr[iCur] ){
65024     sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
65025     p->apCsr[iCur] = 0;
65026   }
65027   if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
65028     p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
65029     memset(pCx, 0, sizeof(VdbeCursor));
65030     pCx->iDb = iDb;
65031     pCx->nField = nField;
65032     if( nField ){
65033       pCx->aType = (u32 *)&pMem->z[ROUND8(sizeof(VdbeCursor))];
65034     }
65035     if( isBtreeCursor ){
65036       pCx->pCursor = (BtCursor*)
65037           &pMem->z[ROUND8(sizeof(VdbeCursor))+2*nField*sizeof(u32)];
65038       sqlite3BtreeCursorZero(pCx->pCursor);
65039     }
65040   }
65041   return pCx;
65042 }
65043
65044 /*
65045 ** Try to convert a value into a numeric representation if we can
65046 ** do so without loss of information.  In other words, if the string
65047 ** looks like a number, convert it into a number.  If it does not
65048 ** look like a number, leave it alone.
65049 */
65050 static void applyNumericAffinity(Mem *pRec){
65051   if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
65052     double rValue;
65053     i64 iValue;
65054     u8 enc = pRec->enc;
65055     if( (pRec->flags&MEM_Str)==0 ) return;
65056     if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
65057     if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
65058       pRec->u.i = iValue;
65059       pRec->flags |= MEM_Int;
65060     }else{
65061       pRec->r = rValue;
65062       pRec->flags |= MEM_Real;
65063     }
65064   }
65065 }
65066
65067 /*
65068 ** Processing is determine by the affinity parameter:
65069 **
65070 ** SQLITE_AFF_INTEGER:
65071 ** SQLITE_AFF_REAL:
65072 ** SQLITE_AFF_NUMERIC:
65073 **    Try to convert pRec to an integer representation or a 
65074 **    floating-point representation if an integer representation
65075 **    is not possible.  Note that the integer representation is
65076 **    always preferred, even if the affinity is REAL, because
65077 **    an integer representation is more space efficient on disk.
65078 **
65079 ** SQLITE_AFF_TEXT:
65080 **    Convert pRec to a text representation.
65081 **
65082 ** SQLITE_AFF_NONE:
65083 **    No-op.  pRec is unchanged.
65084 */
65085 static void applyAffinity(
65086   Mem *pRec,          /* The value to apply affinity to */
65087   char affinity,      /* The affinity to be applied */
65088   u8 enc              /* Use this text encoding */
65089 ){
65090   if( affinity==SQLITE_AFF_TEXT ){
65091     /* Only attempt the conversion to TEXT if there is an integer or real
65092     ** representation (blob and NULL do not get converted) but no string
65093     ** representation.
65094     */
65095     if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
65096       sqlite3VdbeMemStringify(pRec, enc);
65097     }
65098     pRec->flags &= ~(MEM_Real|MEM_Int);
65099   }else if( affinity!=SQLITE_AFF_NONE ){
65100     assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
65101              || affinity==SQLITE_AFF_NUMERIC );
65102     applyNumericAffinity(pRec);
65103     if( pRec->flags & MEM_Real ){
65104       sqlite3VdbeIntegerAffinity(pRec);
65105     }
65106   }
65107 }
65108
65109 /*
65110 ** Try to convert the type of a function argument or a result column
65111 ** into a numeric representation.  Use either INTEGER or REAL whichever
65112 ** is appropriate.  But only do the conversion if it is possible without
65113 ** loss of information and return the revised type of the argument.
65114 */
65115 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
65116   Mem *pMem = (Mem*)pVal;
65117   if( pMem->type==SQLITE_TEXT ){
65118     applyNumericAffinity(pMem);
65119     sqlite3VdbeMemStoreType(pMem);
65120   }
65121   return pMem->type;
65122 }
65123
65124 /*
65125 ** Exported version of applyAffinity(). This one works on sqlite3_value*, 
65126 ** not the internal Mem* type.
65127 */
65128 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
65129   sqlite3_value *pVal, 
65130   u8 affinity, 
65131   u8 enc
65132 ){
65133   applyAffinity((Mem *)pVal, affinity, enc);
65134 }
65135
65136 #ifdef SQLITE_DEBUG
65137 /*
65138 ** Write a nice string representation of the contents of cell pMem
65139 ** into buffer zBuf, length nBuf.
65140 */
65141 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
65142   char *zCsr = zBuf;
65143   int f = pMem->flags;
65144
65145   static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
65146
65147   if( f&MEM_Blob ){
65148     int i;
65149     char c;
65150     if( f & MEM_Dyn ){
65151       c = 'z';
65152       assert( (f & (MEM_Static|MEM_Ephem))==0 );
65153     }else if( f & MEM_Static ){
65154       c = 't';
65155       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
65156     }else if( f & MEM_Ephem ){
65157       c = 'e';
65158       assert( (f & (MEM_Static|MEM_Dyn))==0 );
65159     }else{
65160       c = 's';
65161     }
65162
65163     sqlite3_snprintf(100, zCsr, "%c", c);
65164     zCsr += sqlite3Strlen30(zCsr);
65165     sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
65166     zCsr += sqlite3Strlen30(zCsr);
65167     for(i=0; i<16 && i<pMem->n; i++){
65168       sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
65169       zCsr += sqlite3Strlen30(zCsr);
65170     }
65171     for(i=0; i<16 && i<pMem->n; i++){
65172       char z = pMem->z[i];
65173       if( z<32 || z>126 ) *zCsr++ = '.';
65174       else *zCsr++ = z;
65175     }
65176
65177     sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
65178     zCsr += sqlite3Strlen30(zCsr);
65179     if( f & MEM_Zero ){
65180       sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
65181       zCsr += sqlite3Strlen30(zCsr);
65182     }
65183     *zCsr = '\0';
65184   }else if( f & MEM_Str ){
65185     int j, k;
65186     zBuf[0] = ' ';
65187     if( f & MEM_Dyn ){
65188       zBuf[1] = 'z';
65189       assert( (f & (MEM_Static|MEM_Ephem))==0 );
65190     }else if( f & MEM_Static ){
65191       zBuf[1] = 't';
65192       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
65193     }else if( f & MEM_Ephem ){
65194       zBuf[1] = 'e';
65195       assert( (f & (MEM_Static|MEM_Dyn))==0 );
65196     }else{
65197       zBuf[1] = 's';
65198     }
65199     k = 2;
65200     sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
65201     k += sqlite3Strlen30(&zBuf[k]);
65202     zBuf[k++] = '[';
65203     for(j=0; j<15 && j<pMem->n; j++){
65204       u8 c = pMem->z[j];
65205       if( c>=0x20 && c<0x7f ){
65206         zBuf[k++] = c;
65207       }else{
65208         zBuf[k++] = '.';
65209       }
65210     }
65211     zBuf[k++] = ']';
65212     sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
65213     k += sqlite3Strlen30(&zBuf[k]);
65214     zBuf[k++] = 0;
65215   }
65216 }
65217 #endif
65218
65219 #ifdef SQLITE_DEBUG
65220 /*
65221 ** Print the value of a register for tracing purposes:
65222 */
65223 static void memTracePrint(FILE *out, Mem *p){
65224   if( p->flags & MEM_Invalid ){
65225     fprintf(out, " undefined");
65226   }else if( p->flags & MEM_Null ){
65227     fprintf(out, " NULL");
65228   }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
65229     fprintf(out, " si:%lld", p->u.i);
65230   }else if( p->flags & MEM_Int ){
65231     fprintf(out, " i:%lld", p->u.i);
65232 #ifndef SQLITE_OMIT_FLOATING_POINT
65233   }else if( p->flags & MEM_Real ){
65234     fprintf(out, " r:%g", p->r);
65235 #endif
65236   }else if( p->flags & MEM_RowSet ){
65237     fprintf(out, " (rowset)");
65238   }else{
65239     char zBuf[200];
65240     sqlite3VdbeMemPrettyPrint(p, zBuf);
65241     fprintf(out, " ");
65242     fprintf(out, "%s", zBuf);
65243   }
65244 }
65245 static void registerTrace(FILE *out, int iReg, Mem *p){
65246   fprintf(out, "REG[%d] = ", iReg);
65247   memTracePrint(out, p);
65248   fprintf(out, "\n");
65249 }
65250 #endif
65251
65252 #ifdef SQLITE_DEBUG
65253 #  define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
65254 #else
65255 #  define REGISTER_TRACE(R,M)
65256 #endif
65257
65258
65259 #ifdef VDBE_PROFILE
65260
65261 /* 
65262 ** hwtime.h contains inline assembler code for implementing 
65263 ** high-performance timing routines.
65264 */
65265 /************** Include hwtime.h in the middle of vdbe.c *********************/
65266 /************** Begin file hwtime.h ******************************************/
65267 /*
65268 ** 2008 May 27
65269 **
65270 ** The author disclaims copyright to this source code.  In place of
65271 ** a legal notice, here is a blessing:
65272 **
65273 **    May you do good and not evil.
65274 **    May you find forgiveness for yourself and forgive others.
65275 **    May you share freely, never taking more than you give.
65276 **
65277 ******************************************************************************
65278 **
65279 ** This file contains inline asm code for retrieving "high-performance"
65280 ** counters for x86 class CPUs.
65281 */
65282 #ifndef _HWTIME_H_
65283 #define _HWTIME_H_
65284
65285 /*
65286 ** The following routine only works on pentium-class (or newer) processors.
65287 ** It uses the RDTSC opcode to read the cycle count value out of the
65288 ** processor and returns that value.  This can be used for high-res
65289 ** profiling.
65290 */
65291 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
65292       (defined(i386) || defined(__i386__) || defined(_M_IX86))
65293
65294   #if defined(__GNUC__)
65295
65296   __inline__ sqlite_uint64 sqlite3Hwtime(void){
65297      unsigned int lo, hi;
65298      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
65299      return (sqlite_uint64)hi << 32 | lo;
65300   }
65301
65302   #elif defined(_MSC_VER)
65303
65304   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
65305      __asm {
65306         rdtsc
65307         ret       ; return value at EDX:EAX
65308      }
65309   }
65310
65311   #endif
65312
65313 #elif (defined(__GNUC__) && defined(__x86_64__))
65314
65315   __inline__ sqlite_uint64 sqlite3Hwtime(void){
65316       unsigned long val;
65317       __asm__ __volatile__ ("rdtsc" : "=A" (val));
65318       return val;
65319   }
65320  
65321 #elif (defined(__GNUC__) && defined(__ppc__))
65322
65323   __inline__ sqlite_uint64 sqlite3Hwtime(void){
65324       unsigned long long retval;
65325       unsigned long junk;
65326       __asm__ __volatile__ ("\n\
65327           1:      mftbu   %1\n\
65328                   mftb    %L0\n\
65329                   mftbu   %0\n\
65330                   cmpw    %0,%1\n\
65331                   bne     1b"
65332                   : "=r" (retval), "=r" (junk));
65333       return retval;
65334   }
65335
65336 #else
65337
65338   #error Need implementation of sqlite3Hwtime() for your platform.
65339
65340   /*
65341   ** To compile without implementing sqlite3Hwtime() for your platform,
65342   ** you can remove the above #error and use the following
65343   ** stub function.  You will lose timing support for many
65344   ** of the debugging and testing utilities, but it should at
65345   ** least compile and run.
65346   */
65347 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
65348
65349 #endif
65350
65351 #endif /* !defined(_HWTIME_H_) */
65352
65353 /************** End of hwtime.h **********************************************/
65354 /************** Continuing where we left off in vdbe.c ***********************/
65355
65356 #endif
65357
65358 /*
65359 ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
65360 ** sqlite3_interrupt() routine has been called.  If it has been, then
65361 ** processing of the VDBE program is interrupted.
65362 **
65363 ** This macro added to every instruction that does a jump in order to
65364 ** implement a loop.  This test used to be on every single instruction,
65365 ** but that meant we more testing than we needed.  By only testing the
65366 ** flag on jump instructions, we get a (small) speed improvement.
65367 */
65368 #define CHECK_FOR_INTERRUPT \
65369    if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
65370
65371
65372 #ifndef NDEBUG
65373 /*
65374 ** This function is only called from within an assert() expression. It
65375 ** checks that the sqlite3.nTransaction variable is correctly set to
65376 ** the number of non-transaction savepoints currently in the 
65377 ** linked list starting at sqlite3.pSavepoint.
65378 ** 
65379 ** Usage:
65380 **
65381 **     assert( checkSavepointCount(db) );
65382 */
65383 static int checkSavepointCount(sqlite3 *db){
65384   int n = 0;
65385   Savepoint *p;
65386   for(p=db->pSavepoint; p; p=p->pNext) n++;
65387   assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
65388   return 1;
65389 }
65390 #endif
65391
65392 /*
65393 ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
65394 ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
65395 ** in memory obtained from sqlite3DbMalloc).
65396 */
65397 static void importVtabErrMsg(Vdbe *p, sqlite3_vtab *pVtab){
65398   sqlite3 *db = p->db;
65399   sqlite3DbFree(db, p->zErrMsg);
65400   p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
65401   sqlite3_free(pVtab->zErrMsg);
65402   pVtab->zErrMsg = 0;
65403 }
65404
65405
65406 /*
65407 ** Execute as much of a VDBE program as we can then return.
65408 **
65409 ** sqlite3VdbeMakeReady() must be called before this routine in order to
65410 ** close the program with a final OP_Halt and to set up the callbacks
65411 ** and the error message pointer.
65412 **
65413 ** Whenever a row or result data is available, this routine will either
65414 ** invoke the result callback (if there is one) or return with
65415 ** SQLITE_ROW.
65416 **
65417 ** If an attempt is made to open a locked database, then this routine
65418 ** will either invoke the busy callback (if there is one) or it will
65419 ** return SQLITE_BUSY.
65420 **
65421 ** If an error occurs, an error message is written to memory obtained
65422 ** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
65423 ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
65424 **
65425 ** If the callback ever returns non-zero, then the program exits
65426 ** immediately.  There will be no error message but the p->rc field is
65427 ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
65428 **
65429 ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
65430 ** routine to return SQLITE_ERROR.
65431 **
65432 ** Other fatal errors return SQLITE_ERROR.
65433 **
65434 ** After this routine has finished, sqlite3VdbeFinalize() should be
65435 ** used to clean up the mess that was left behind.
65436 */
65437 SQLITE_PRIVATE int sqlite3VdbeExec(
65438   Vdbe *p                    /* The VDBE */
65439 ){
65440   int pc=0;                  /* The program counter */
65441   Op *aOp = p->aOp;          /* Copy of p->aOp */
65442   Op *pOp;                   /* Current operation */
65443   int rc = SQLITE_OK;        /* Value to return */
65444   sqlite3 *db = p->db;       /* The database */
65445   u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
65446   u8 encoding = ENC(db);     /* The database encoding */
65447 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
65448   int checkProgress;         /* True if progress callbacks are enabled */
65449   int nProgressOps = 0;      /* Opcodes executed since progress callback. */
65450 #endif
65451   Mem *aMem = p->aMem;       /* Copy of p->aMem */
65452   Mem *pIn1 = 0;             /* 1st input operand */
65453   Mem *pIn2 = 0;             /* 2nd input operand */
65454   Mem *pIn3 = 0;             /* 3rd input operand */
65455   Mem *pOut = 0;             /* Output operand */
65456   int iCompare = 0;          /* Result of last OP_Compare operation */
65457   int *aPermute = 0;         /* Permutation of columns for OP_Compare */
65458   i64 lastRowid = db->lastRowid;  /* Saved value of the last insert ROWID */
65459 #ifdef VDBE_PROFILE
65460   u64 start;                 /* CPU clock count at start of opcode */
65461   int origPc;                /* Program counter at start of opcode */
65462 #endif
65463   /********************************************************************
65464   ** Automatically generated code
65465   **
65466   ** The following union is automatically generated by the
65467   ** vdbe-compress.tcl script.  The purpose of this union is to
65468   ** reduce the amount of stack space required by this function.
65469   ** See comments in the vdbe-compress.tcl script for details.
65470   */
65471   union vdbeExecUnion {
65472     struct OP_Yield_stack_vars {
65473       int pcDest;
65474     } aa;
65475     struct OP_Null_stack_vars {
65476       int cnt;
65477       u16 nullFlag;
65478     } ab;
65479     struct OP_Variable_stack_vars {
65480       Mem *pVar;       /* Value being transferred */
65481     } ac;
65482     struct OP_Move_stack_vars {
65483       char *zMalloc;   /* Holding variable for allocated memory */
65484       int n;           /* Number of registers left to copy */
65485       int p1;          /* Register to copy from */
65486       int p2;          /* Register to copy to */
65487     } ad;
65488     struct OP_Copy_stack_vars {
65489       int n;
65490     } ae;
65491     struct OP_ResultRow_stack_vars {
65492       Mem *pMem;
65493       int i;
65494     } af;
65495     struct OP_Concat_stack_vars {
65496       i64 nByte;
65497     } ag;
65498     struct OP_Remainder_stack_vars {
65499       char bIntint;   /* Started out as two integer operands */
65500       int flags;      /* Combined MEM_* flags from both inputs */
65501       i64 iA;         /* Integer value of left operand */
65502       i64 iB;         /* Integer value of right operand */
65503       double rA;      /* Real value of left operand */
65504       double rB;      /* Real value of right operand */
65505     } ah;
65506     struct OP_Function_stack_vars {
65507       int i;
65508       Mem *pArg;
65509       sqlite3_context ctx;
65510       sqlite3_value **apVal;
65511       int n;
65512     } ai;
65513     struct OP_ShiftRight_stack_vars {
65514       i64 iA;
65515       u64 uA;
65516       i64 iB;
65517       u8 op;
65518     } aj;
65519     struct OP_Ge_stack_vars {
65520       int res;            /* Result of the comparison of pIn1 against pIn3 */
65521       char affinity;      /* Affinity to use for comparison */
65522       u16 flags1;         /* Copy of initial value of pIn1->flags */
65523       u16 flags3;         /* Copy of initial value of pIn3->flags */
65524     } ak;
65525     struct OP_Compare_stack_vars {
65526       int n;
65527       int i;
65528       int p1;
65529       int p2;
65530       const KeyInfo *pKeyInfo;
65531       int idx;
65532       CollSeq *pColl;    /* Collating sequence to use on this term */
65533       int bRev;          /* True for DESCENDING sort order */
65534     } al;
65535     struct OP_Or_stack_vars {
65536       int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
65537       int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
65538     } am;
65539     struct OP_IfNot_stack_vars {
65540       int c;
65541     } an;
65542     struct OP_Column_stack_vars {
65543       u32 payloadSize;   /* Number of bytes in the record */
65544       i64 payloadSize64; /* Number of bytes in the record */
65545       int p1;            /* P1 value of the opcode */
65546       int p2;            /* column number to retrieve */
65547       VdbeCursor *pC;    /* The VDBE cursor */
65548       char *zRec;        /* Pointer to complete record-data */
65549       BtCursor *pCrsr;   /* The BTree cursor */
65550       u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
65551       u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
65552       int nField;        /* number of fields in the record */
65553       int len;           /* The length of the serialized data for the column */
65554       int i;             /* Loop counter */
65555       char *zData;       /* Part of the record being decoded */
65556       Mem *pDest;        /* Where to write the extracted value */
65557       Mem sMem;          /* For storing the record being decoded */
65558       u8 *zIdx;          /* Index into header */
65559       u8 *zEndHdr;       /* Pointer to first byte after the header */
65560       u32 offset;        /* Offset into the data */
65561       u32 szField;       /* Number of bytes in the content of a field */
65562       int szHdr;         /* Size of the header size field at start of record */
65563       int avail;         /* Number of bytes of available data */
65564       u32 t;             /* A type code from the record header */
65565       Mem *pReg;         /* PseudoTable input register */
65566     } ao;
65567     struct OP_Affinity_stack_vars {
65568       const char *zAffinity;   /* The affinity to be applied */
65569       char cAff;               /* A single character of affinity */
65570     } ap;
65571     struct OP_MakeRecord_stack_vars {
65572       u8 *zNewRecord;        /* A buffer to hold the data for the new record */
65573       Mem *pRec;             /* The new record */
65574       u64 nData;             /* Number of bytes of data space */
65575       int nHdr;              /* Number of bytes of header space */
65576       i64 nByte;             /* Data space required for this record */
65577       int nZero;             /* Number of zero bytes at the end of the record */
65578       int nVarint;           /* Number of bytes in a varint */
65579       u32 serial_type;       /* Type field */
65580       Mem *pData0;           /* First field to be combined into the record */
65581       Mem *pLast;            /* Last field of the record */
65582       int nField;            /* Number of fields in the record */
65583       char *zAffinity;       /* The affinity string for the record */
65584       int file_format;       /* File format to use for encoding */
65585       int i;                 /* Space used in zNewRecord[] */
65586       int len;               /* Length of a field */
65587     } aq;
65588     struct OP_Count_stack_vars {
65589       i64 nEntry;
65590       BtCursor *pCrsr;
65591     } ar;
65592     struct OP_Savepoint_stack_vars {
65593       int p1;                         /* Value of P1 operand */
65594       char *zName;                    /* Name of savepoint */
65595       int nName;
65596       Savepoint *pNew;
65597       Savepoint *pSavepoint;
65598       Savepoint *pTmp;
65599       int iSavepoint;
65600       int ii;
65601     } as;
65602     struct OP_AutoCommit_stack_vars {
65603       int desiredAutoCommit;
65604       int iRollback;
65605       int turnOnAC;
65606     } at;
65607     struct OP_Transaction_stack_vars {
65608       Btree *pBt;
65609     } au;
65610     struct OP_ReadCookie_stack_vars {
65611       int iMeta;
65612       int iDb;
65613       int iCookie;
65614     } av;
65615     struct OP_SetCookie_stack_vars {
65616       Db *pDb;
65617     } aw;
65618     struct OP_VerifyCookie_stack_vars {
65619       int iMeta;
65620       int iGen;
65621       Btree *pBt;
65622     } ax;
65623     struct OP_OpenWrite_stack_vars {
65624       int nField;
65625       KeyInfo *pKeyInfo;
65626       int p2;
65627       int iDb;
65628       int wrFlag;
65629       Btree *pX;
65630       VdbeCursor *pCur;
65631       Db *pDb;
65632     } ay;
65633     struct OP_OpenEphemeral_stack_vars {
65634       VdbeCursor *pCx;
65635     } az;
65636     struct OP_SorterOpen_stack_vars {
65637       VdbeCursor *pCx;
65638     } ba;
65639     struct OP_OpenPseudo_stack_vars {
65640       VdbeCursor *pCx;
65641     } bb;
65642     struct OP_SeekGt_stack_vars {
65643       int res;
65644       int oc;
65645       VdbeCursor *pC;
65646       UnpackedRecord r;
65647       int nField;
65648       i64 iKey;      /* The rowid we are to seek to */
65649     } bc;
65650     struct OP_Seek_stack_vars {
65651       VdbeCursor *pC;
65652     } bd;
65653     struct OP_Found_stack_vars {
65654       int alreadyExists;
65655       VdbeCursor *pC;
65656       int res;
65657       char *pFree;
65658       UnpackedRecord *pIdxKey;
65659       UnpackedRecord r;
65660       char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
65661     } be;
65662     struct OP_IsUnique_stack_vars {
65663       u16 ii;
65664       VdbeCursor *pCx;
65665       BtCursor *pCrsr;
65666       u16 nField;
65667       Mem *aMx;
65668       UnpackedRecord r;                  /* B-Tree index search key */
65669       i64 R;                             /* Rowid stored in register P3 */
65670     } bf;
65671     struct OP_NotExists_stack_vars {
65672       VdbeCursor *pC;
65673       BtCursor *pCrsr;
65674       int res;
65675       u64 iKey;
65676     } bg;
65677     struct OP_NewRowid_stack_vars {
65678       i64 v;                 /* The new rowid */
65679       VdbeCursor *pC;        /* Cursor of table to get the new rowid */
65680       int res;               /* Result of an sqlite3BtreeLast() */
65681       int cnt;               /* Counter to limit the number of searches */
65682       Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
65683       VdbeFrame *pFrame;     /* Root frame of VDBE */
65684     } bh;
65685     struct OP_InsertInt_stack_vars {
65686       Mem *pData;       /* MEM cell holding data for the record to be inserted */
65687       Mem *pKey;        /* MEM cell holding key  for the record */
65688       i64 iKey;         /* The integer ROWID or key for the record to be inserted */
65689       VdbeCursor *pC;   /* Cursor to table into which insert is written */
65690       int nZero;        /* Number of zero-bytes to append */
65691       int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
65692       const char *zDb;  /* database name - used by the update hook */
65693       const char *zTbl; /* Table name - used by the opdate hook */
65694       int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
65695     } bi;
65696     struct OP_Delete_stack_vars {
65697       i64 iKey;
65698       VdbeCursor *pC;
65699     } bj;
65700     struct OP_SorterCompare_stack_vars {
65701       VdbeCursor *pC;
65702       int res;
65703     } bk;
65704     struct OP_SorterData_stack_vars {
65705       VdbeCursor *pC;
65706     } bl;
65707     struct OP_RowData_stack_vars {
65708       VdbeCursor *pC;
65709       BtCursor *pCrsr;
65710       u32 n;
65711       i64 n64;
65712     } bm;
65713     struct OP_Rowid_stack_vars {
65714       VdbeCursor *pC;
65715       i64 v;
65716       sqlite3_vtab *pVtab;
65717       const sqlite3_module *pModule;
65718     } bn;
65719     struct OP_NullRow_stack_vars {
65720       VdbeCursor *pC;
65721     } bo;
65722     struct OP_Last_stack_vars {
65723       VdbeCursor *pC;
65724       BtCursor *pCrsr;
65725       int res;
65726     } bp;
65727     struct OP_Rewind_stack_vars {
65728       VdbeCursor *pC;
65729       BtCursor *pCrsr;
65730       int res;
65731     } bq;
65732     struct OP_Next_stack_vars {
65733       VdbeCursor *pC;
65734       int res;
65735     } br;
65736     struct OP_IdxInsert_stack_vars {
65737       VdbeCursor *pC;
65738       BtCursor *pCrsr;
65739       int nKey;
65740       const char *zKey;
65741     } bs;
65742     struct OP_IdxDelete_stack_vars {
65743       VdbeCursor *pC;
65744       BtCursor *pCrsr;
65745       int res;
65746       UnpackedRecord r;
65747     } bt;
65748     struct OP_IdxRowid_stack_vars {
65749       BtCursor *pCrsr;
65750       VdbeCursor *pC;
65751       i64 rowid;
65752     } bu;
65753     struct OP_IdxGE_stack_vars {
65754       VdbeCursor *pC;
65755       int res;
65756       UnpackedRecord r;
65757     } bv;
65758     struct OP_Destroy_stack_vars {
65759       int iMoved;
65760       int iCnt;
65761       Vdbe *pVdbe;
65762       int iDb;
65763     } bw;
65764     struct OP_Clear_stack_vars {
65765       int nChange;
65766     } bx;
65767     struct OP_CreateTable_stack_vars {
65768       int pgno;
65769       int flags;
65770       Db *pDb;
65771     } by;
65772     struct OP_ParseSchema_stack_vars {
65773       int iDb;
65774       const char *zMaster;
65775       char *zSql;
65776       InitData initData;
65777     } bz;
65778     struct OP_IntegrityCk_stack_vars {
65779       int nRoot;      /* Number of tables to check.  (Number of root pages.) */
65780       int *aRoot;     /* Array of rootpage numbers for tables to be checked */
65781       int j;          /* Loop counter */
65782       int nErr;       /* Number of errors reported */
65783       char *z;        /* Text of the error report */
65784       Mem *pnErr;     /* Register keeping track of errors remaining */
65785     } ca;
65786     struct OP_RowSetRead_stack_vars {
65787       i64 val;
65788     } cb;
65789     struct OP_RowSetTest_stack_vars {
65790       int iSet;
65791       int exists;
65792     } cc;
65793     struct OP_Program_stack_vars {
65794       int nMem;               /* Number of memory registers for sub-program */
65795       int nByte;              /* Bytes of runtime space required for sub-program */
65796       Mem *pRt;               /* Register to allocate runtime space */
65797       Mem *pMem;              /* Used to iterate through memory cells */
65798       Mem *pEnd;              /* Last memory cell in new array */
65799       VdbeFrame *pFrame;      /* New vdbe frame to execute in */
65800       SubProgram *pProgram;   /* Sub-program to execute */
65801       void *t;                /* Token identifying trigger */
65802     } cd;
65803     struct OP_Param_stack_vars {
65804       VdbeFrame *pFrame;
65805       Mem *pIn;
65806     } ce;
65807     struct OP_MemMax_stack_vars {
65808       Mem *pIn1;
65809       VdbeFrame *pFrame;
65810     } cf;
65811     struct OP_AggStep_stack_vars {
65812       int n;
65813       int i;
65814       Mem *pMem;
65815       Mem *pRec;
65816       sqlite3_context ctx;
65817       sqlite3_value **apVal;
65818     } cg;
65819     struct OP_AggFinal_stack_vars {
65820       Mem *pMem;
65821     } ch;
65822     struct OP_Checkpoint_stack_vars {
65823       int i;                          /* Loop counter */
65824       int aRes[3];                    /* Results */
65825       Mem *pMem;                      /* Write results here */
65826     } ci;
65827     struct OP_JournalMode_stack_vars {
65828       Btree *pBt;                     /* Btree to change journal mode of */
65829       Pager *pPager;                  /* Pager associated with pBt */
65830       int eNew;                       /* New journal mode */
65831       int eOld;                       /* The old journal mode */
65832 #ifndef SQLITE_OMIT_WAL
65833       const char *zFilename;          /* Name of database file for pPager */
65834 #endif
65835     } cj;
65836     struct OP_IncrVacuum_stack_vars {
65837       Btree *pBt;
65838     } ck;
65839     struct OP_VBegin_stack_vars {
65840       VTable *pVTab;
65841     } cl;
65842     struct OP_VOpen_stack_vars {
65843       VdbeCursor *pCur;
65844       sqlite3_vtab_cursor *pVtabCursor;
65845       sqlite3_vtab *pVtab;
65846       sqlite3_module *pModule;
65847     } cm;
65848     struct OP_VFilter_stack_vars {
65849       int nArg;
65850       int iQuery;
65851       const sqlite3_module *pModule;
65852       Mem *pQuery;
65853       Mem *pArgc;
65854       sqlite3_vtab_cursor *pVtabCursor;
65855       sqlite3_vtab *pVtab;
65856       VdbeCursor *pCur;
65857       int res;
65858       int i;
65859       Mem **apArg;
65860     } cn;
65861     struct OP_VColumn_stack_vars {
65862       sqlite3_vtab *pVtab;
65863       const sqlite3_module *pModule;
65864       Mem *pDest;
65865       sqlite3_context sContext;
65866     } co;
65867     struct OP_VNext_stack_vars {
65868       sqlite3_vtab *pVtab;
65869       const sqlite3_module *pModule;
65870       int res;
65871       VdbeCursor *pCur;
65872     } cp;
65873     struct OP_VRename_stack_vars {
65874       sqlite3_vtab *pVtab;
65875       Mem *pName;
65876     } cq;
65877     struct OP_VUpdate_stack_vars {
65878       sqlite3_vtab *pVtab;
65879       sqlite3_module *pModule;
65880       int nArg;
65881       int i;
65882       sqlite_int64 rowid;
65883       Mem **apArg;
65884       Mem *pX;
65885     } cr;
65886     struct OP_Trace_stack_vars {
65887       char *zTrace;
65888       char *z;
65889     } cs;
65890   } u;
65891   /* End automatically generated code
65892   ********************************************************************/
65893
65894   assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
65895   sqlite3VdbeEnter(p);
65896   if( p->rc==SQLITE_NOMEM ){
65897     /* This happens if a malloc() inside a call to sqlite3_column_text() or
65898     ** sqlite3_column_text16() failed.  */
65899     goto no_mem;
65900   }
65901   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
65902   p->rc = SQLITE_OK;
65903   assert( p->explain==0 );
65904   p->pResultSet = 0;
65905   db->busyHandler.nBusy = 0;
65906   CHECK_FOR_INTERRUPT;
65907   sqlite3VdbeIOTraceSql(p);
65908 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
65909   checkProgress = db->xProgress!=0;
65910 #endif
65911 #ifdef SQLITE_DEBUG
65912   sqlite3BeginBenignMalloc();
65913   if( p->pc==0  && (p->db->flags & SQLITE_VdbeListing)!=0 ){
65914     int i;
65915     printf("VDBE Program Listing:\n");
65916     sqlite3VdbePrintSql(p);
65917     for(i=0; i<p->nOp; i++){
65918       sqlite3VdbePrintOp(stdout, i, &aOp[i]);
65919     }
65920   }
65921   sqlite3EndBenignMalloc();
65922 #endif
65923   for(pc=p->pc; rc==SQLITE_OK; pc++){
65924     assert( pc>=0 && pc<p->nOp );
65925     if( db->mallocFailed ) goto no_mem;
65926 #ifdef VDBE_PROFILE
65927     origPc = pc;
65928     start = sqlite3Hwtime();
65929 #endif
65930     pOp = &aOp[pc];
65931
65932     /* Only allow tracing if SQLITE_DEBUG is defined.
65933     */
65934 #ifdef SQLITE_DEBUG
65935     if( p->trace ){
65936       if( pc==0 ){
65937         printf("VDBE Execution Trace:\n");
65938         sqlite3VdbePrintSql(p);
65939       }
65940       sqlite3VdbePrintOp(p->trace, pc, pOp);
65941     }
65942 #endif
65943       
65944
65945     /* Check to see if we need to simulate an interrupt.  This only happens
65946     ** if we have a special test build.
65947     */
65948 #ifdef SQLITE_TEST
65949     if( sqlite3_interrupt_count>0 ){
65950       sqlite3_interrupt_count--;
65951       if( sqlite3_interrupt_count==0 ){
65952         sqlite3_interrupt(db);
65953       }
65954     }
65955 #endif
65956
65957 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
65958     /* Call the progress callback if it is configured and the required number
65959     ** of VDBE ops have been executed (either since this invocation of
65960     ** sqlite3VdbeExec() or since last time the progress callback was called).
65961     ** If the progress callback returns non-zero, exit the virtual machine with
65962     ** a return code SQLITE_ABORT.
65963     */
65964     if( checkProgress ){
65965       if( db->nProgressOps==nProgressOps ){
65966         int prc;
65967         prc = db->xProgress(db->pProgressArg);
65968         if( prc!=0 ){
65969           rc = SQLITE_INTERRUPT;
65970           goto vdbe_error_halt;
65971         }
65972         nProgressOps = 0;
65973       }
65974       nProgressOps++;
65975     }
65976 #endif
65977
65978     /* On any opcode with the "out2-prerelease" tag, free any
65979     ** external allocations out of mem[p2] and set mem[p2] to be
65980     ** an undefined integer.  Opcodes will either fill in the integer
65981     ** value or convert mem[p2] to a different type.
65982     */
65983     assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
65984     if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
65985       assert( pOp->p2>0 );
65986       assert( pOp->p2<=p->nMem );
65987       pOut = &aMem[pOp->p2];
65988       memAboutToChange(p, pOut);
65989       VdbeMemRelease(pOut);
65990       pOut->flags = MEM_Int;
65991     }
65992
65993     /* Sanity checking on other operands */
65994 #ifdef SQLITE_DEBUG
65995     if( (pOp->opflags & OPFLG_IN1)!=0 ){
65996       assert( pOp->p1>0 );
65997       assert( pOp->p1<=p->nMem );
65998       assert( memIsValid(&aMem[pOp->p1]) );
65999       REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
66000     }
66001     if( (pOp->opflags & OPFLG_IN2)!=0 ){
66002       assert( pOp->p2>0 );
66003       assert( pOp->p2<=p->nMem );
66004       assert( memIsValid(&aMem[pOp->p2]) );
66005       REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
66006     }
66007     if( (pOp->opflags & OPFLG_IN3)!=0 ){
66008       assert( pOp->p3>0 );
66009       assert( pOp->p3<=p->nMem );
66010       assert( memIsValid(&aMem[pOp->p3]) );
66011       REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
66012     }
66013     if( (pOp->opflags & OPFLG_OUT2)!=0 ){
66014       assert( pOp->p2>0 );
66015       assert( pOp->p2<=p->nMem );
66016       memAboutToChange(p, &aMem[pOp->p2]);
66017     }
66018     if( (pOp->opflags & OPFLG_OUT3)!=0 ){
66019       assert( pOp->p3>0 );
66020       assert( pOp->p3<=p->nMem );
66021       memAboutToChange(p, &aMem[pOp->p3]);
66022     }
66023 #endif
66024   
66025     switch( pOp->opcode ){
66026
66027 /*****************************************************************************
66028 ** What follows is a massive switch statement where each case implements a
66029 ** separate instruction in the virtual machine.  If we follow the usual
66030 ** indentation conventions, each case should be indented by 6 spaces.  But
66031 ** that is a lot of wasted space on the left margin.  So the code within
66032 ** the switch statement will break with convention and be flush-left. Another
66033 ** big comment (similar to this one) will mark the point in the code where
66034 ** we transition back to normal indentation.
66035 **
66036 ** The formatting of each case is important.  The makefile for SQLite
66037 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
66038 ** file looking for lines that begin with "case OP_".  The opcodes.h files
66039 ** will be filled with #defines that give unique integer values to each
66040 ** opcode and the opcodes.c file is filled with an array of strings where
66041 ** each string is the symbolic name for the corresponding opcode.  If the
66042 ** case statement is followed by a comment of the form "/# same as ... #/"
66043 ** that comment is used to determine the particular value of the opcode.
66044 **
66045 ** Other keywords in the comment that follows each case are used to
66046 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
66047 ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3.  See
66048 ** the mkopcodeh.awk script for additional information.
66049 **
66050 ** Documentation about VDBE opcodes is generated by scanning this file
66051 ** for lines of that contain "Opcode:".  That line and all subsequent
66052 ** comment lines are used in the generation of the opcode.html documentation
66053 ** file.
66054 **
66055 ** SUMMARY:
66056 **
66057 **     Formatting is important to scripts that scan this file.
66058 **     Do not deviate from the formatting style currently in use.
66059 **
66060 *****************************************************************************/
66061
66062 /* Opcode:  Goto * P2 * * *
66063 **
66064 ** An unconditional jump to address P2.
66065 ** The next instruction executed will be 
66066 ** the one at index P2 from the beginning of
66067 ** the program.
66068 */
66069 case OP_Goto: {             /* jump */
66070   CHECK_FOR_INTERRUPT;
66071   pc = pOp->p2 - 1;
66072   break;
66073 }
66074
66075 /* Opcode:  Gosub P1 P2 * * *
66076 **
66077 ** Write the current address onto register P1
66078 ** and then jump to address P2.
66079 */
66080 case OP_Gosub: {            /* jump */
66081   assert( pOp->p1>0 && pOp->p1<=p->nMem );
66082   pIn1 = &aMem[pOp->p1];
66083   assert( (pIn1->flags & MEM_Dyn)==0 );
66084   memAboutToChange(p, pIn1);
66085   pIn1->flags = MEM_Int;
66086   pIn1->u.i = pc;
66087   REGISTER_TRACE(pOp->p1, pIn1);
66088   pc = pOp->p2 - 1;
66089   break;
66090 }
66091
66092 /* Opcode:  Return P1 * * * *
66093 **
66094 ** Jump to the next instruction after the address in register P1.
66095 */
66096 case OP_Return: {           /* in1 */
66097   pIn1 = &aMem[pOp->p1];
66098   assert( pIn1->flags & MEM_Int );
66099   pc = (int)pIn1->u.i;
66100   break;
66101 }
66102
66103 /* Opcode:  Yield P1 * * * *
66104 **
66105 ** Swap the program counter with the value in register P1.
66106 */
66107 case OP_Yield: {            /* in1 */
66108 #if 0  /* local variables moved into u.aa */
66109   int pcDest;
66110 #endif /* local variables moved into u.aa */
66111   pIn1 = &aMem[pOp->p1];
66112   assert( (pIn1->flags & MEM_Dyn)==0 );
66113   pIn1->flags = MEM_Int;
66114   u.aa.pcDest = (int)pIn1->u.i;
66115   pIn1->u.i = pc;
66116   REGISTER_TRACE(pOp->p1, pIn1);
66117   pc = u.aa.pcDest;
66118   break;
66119 }
66120
66121 /* Opcode:  HaltIfNull  P1 P2 P3 P4 *
66122 **
66123 ** Check the value in register P3.  If it is NULL then Halt using
66124 ** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
66125 ** value in register P3 is not NULL, then this routine is a no-op.
66126 */
66127 case OP_HaltIfNull: {      /* in3 */
66128   pIn3 = &aMem[pOp->p3];
66129   if( (pIn3->flags & MEM_Null)==0 ) break;
66130   /* Fall through into OP_Halt */
66131 }
66132
66133 /* Opcode:  Halt P1 P2 * P4 *
66134 **
66135 ** Exit immediately.  All open cursors, etc are closed
66136 ** automatically.
66137 **
66138 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
66139 ** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
66140 ** For errors, it can be some other value.  If P1!=0 then P2 will determine
66141 ** whether or not to rollback the current transaction.  Do not rollback
66142 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
66143 ** then back out all changes that have occurred during this execution of the
66144 ** VDBE, but do not rollback the transaction. 
66145 **
66146 ** If P4 is not null then it is an error message string.
66147 **
66148 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
66149 ** every program.  So a jump past the last instruction of the program
66150 ** is the same as executing Halt.
66151 */
66152 case OP_Halt: {
66153   if( pOp->p1==SQLITE_OK && p->pFrame ){
66154     /* Halt the sub-program. Return control to the parent frame. */
66155     VdbeFrame *pFrame = p->pFrame;
66156     p->pFrame = pFrame->pParent;
66157     p->nFrame--;
66158     sqlite3VdbeSetChanges(db, p->nChange);
66159     pc = sqlite3VdbeFrameRestore(pFrame);
66160     lastRowid = db->lastRowid;
66161     if( pOp->p2==OE_Ignore ){
66162       /* Instruction pc is the OP_Program that invoked the sub-program 
66163       ** currently being halted. If the p2 instruction of this OP_Halt
66164       ** instruction is set to OE_Ignore, then the sub-program is throwing
66165       ** an IGNORE exception. In this case jump to the address specified
66166       ** as the p2 of the calling OP_Program.  */
66167       pc = p->aOp[pc].p2-1;
66168     }
66169     aOp = p->aOp;
66170     aMem = p->aMem;
66171     break;
66172   }
66173
66174   p->rc = pOp->p1;
66175   p->errorAction = (u8)pOp->p2;
66176   p->pc = pc;
66177   if( pOp->p4.z ){
66178     assert( p->rc!=SQLITE_OK );
66179     sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
66180     testcase( sqlite3GlobalConfig.xLog!=0 );
66181     sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pc, p->zSql, pOp->p4.z);
66182   }else if( p->rc ){
66183     testcase( sqlite3GlobalConfig.xLog!=0 );
66184     sqlite3_log(pOp->p1, "constraint failed at %d in [%s]", pc, p->zSql);
66185   }
66186   rc = sqlite3VdbeHalt(p);
66187   assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
66188   if( rc==SQLITE_BUSY ){
66189     p->rc = rc = SQLITE_BUSY;
66190   }else{
66191     assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
66192     assert( rc==SQLITE_OK || db->nDeferredCons>0 );
66193     rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
66194   }
66195   goto vdbe_return;
66196 }
66197
66198 /* Opcode: Integer P1 P2 * * *
66199 **
66200 ** The 32-bit integer value P1 is written into register P2.
66201 */
66202 case OP_Integer: {         /* out2-prerelease */
66203   pOut->u.i = pOp->p1;
66204   break;
66205 }
66206
66207 /* Opcode: Int64 * P2 * P4 *
66208 **
66209 ** P4 is a pointer to a 64-bit integer value.
66210 ** Write that value into register P2.
66211 */
66212 case OP_Int64: {           /* out2-prerelease */
66213   assert( pOp->p4.pI64!=0 );
66214   pOut->u.i = *pOp->p4.pI64;
66215   break;
66216 }
66217
66218 #ifndef SQLITE_OMIT_FLOATING_POINT
66219 /* Opcode: Real * P2 * P4 *
66220 **
66221 ** P4 is a pointer to a 64-bit floating point value.
66222 ** Write that value into register P2.
66223 */
66224 case OP_Real: {            /* same as TK_FLOAT, out2-prerelease */
66225   pOut->flags = MEM_Real;
66226   assert( !sqlite3IsNaN(*pOp->p4.pReal) );
66227   pOut->r = *pOp->p4.pReal;
66228   break;
66229 }
66230 #endif
66231
66232 /* Opcode: String8 * P2 * P4 *
66233 **
66234 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed 
66235 ** into an OP_String before it is executed for the first time.
66236 */
66237 case OP_String8: {         /* same as TK_STRING, out2-prerelease */
66238   assert( pOp->p4.z!=0 );
66239   pOp->opcode = OP_String;
66240   pOp->p1 = sqlite3Strlen30(pOp->p4.z);
66241
66242 #ifndef SQLITE_OMIT_UTF16
66243   if( encoding!=SQLITE_UTF8 ){
66244     rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
66245     if( rc==SQLITE_TOOBIG ) goto too_big;
66246     if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
66247     assert( pOut->zMalloc==pOut->z );
66248     assert( pOut->flags & MEM_Dyn );
66249     pOut->zMalloc = 0;
66250     pOut->flags |= MEM_Static;
66251     pOut->flags &= ~MEM_Dyn;
66252     if( pOp->p4type==P4_DYNAMIC ){
66253       sqlite3DbFree(db, pOp->p4.z);
66254     }
66255     pOp->p4type = P4_DYNAMIC;
66256     pOp->p4.z = pOut->z;
66257     pOp->p1 = pOut->n;
66258   }
66259 #endif
66260   if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
66261     goto too_big;
66262   }
66263   /* Fall through to the next case, OP_String */
66264 }
66265   
66266 /* Opcode: String P1 P2 * P4 *
66267 **
66268 ** The string value P4 of length P1 (bytes) is stored in register P2.
66269 */
66270 case OP_String: {          /* out2-prerelease */
66271   assert( pOp->p4.z!=0 );
66272   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
66273   pOut->z = pOp->p4.z;
66274   pOut->n = pOp->p1;
66275   pOut->enc = encoding;
66276   UPDATE_MAX_BLOBSIZE(pOut);
66277   break;
66278 }
66279
66280 /* Opcode: Null P1 P2 P3 * *
66281 **
66282 ** Write a NULL into registers P2.  If P3 greater than P2, then also write
66283 ** NULL into register P3 and every register in between P2 and P3.  If P3
66284 ** is less than P2 (typically P3 is zero) then only register P2 is
66285 ** set to NULL.
66286 **
66287 ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
66288 ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
66289 ** OP_Ne or OP_Eq.
66290 */
66291 case OP_Null: {           /* out2-prerelease */
66292 #if 0  /* local variables moved into u.ab */
66293   int cnt;
66294   u16 nullFlag;
66295 #endif /* local variables moved into u.ab */
66296   u.ab.cnt = pOp->p3-pOp->p2;
66297   assert( pOp->p3<=p->nMem );
66298   pOut->flags = u.ab.nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
66299   while( u.ab.cnt>0 ){
66300     pOut++;
66301     memAboutToChange(p, pOut);
66302     VdbeMemRelease(pOut);
66303     pOut->flags = u.ab.nullFlag;
66304     u.ab.cnt--;
66305   }
66306   break;
66307 }
66308
66309
66310 /* Opcode: Blob P1 P2 * P4
66311 **
66312 ** P4 points to a blob of data P1 bytes long.  Store this
66313 ** blob in register P2.
66314 */
66315 case OP_Blob: {                /* out2-prerelease */
66316   assert( pOp->p1 <= SQLITE_MAX_LENGTH );
66317   sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
66318   pOut->enc = encoding;
66319   UPDATE_MAX_BLOBSIZE(pOut);
66320   break;
66321 }
66322
66323 /* Opcode: Variable P1 P2 * P4 *
66324 **
66325 ** Transfer the values of bound parameter P1 into register P2
66326 **
66327 ** If the parameter is named, then its name appears in P4 and P3==1.
66328 ** The P4 value is used by sqlite3_bind_parameter_name().
66329 */
66330 case OP_Variable: {            /* out2-prerelease */
66331 #if 0  /* local variables moved into u.ac */
66332   Mem *pVar;       /* Value being transferred */
66333 #endif /* local variables moved into u.ac */
66334
66335   assert( pOp->p1>0 && pOp->p1<=p->nVar );
66336   assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );
66337   u.ac.pVar = &p->aVar[pOp->p1 - 1];
66338   if( sqlite3VdbeMemTooBig(u.ac.pVar) ){
66339     goto too_big;
66340   }
66341   sqlite3VdbeMemShallowCopy(pOut, u.ac.pVar, MEM_Static);
66342   UPDATE_MAX_BLOBSIZE(pOut);
66343   break;
66344 }
66345
66346 /* Opcode: Move P1 P2 P3 * *
66347 **
66348 ** Move the values in register P1..P1+P3 over into
66349 ** registers P2..P2+P3.  Registers P1..P1+P3 are
66350 ** left holding a NULL.  It is an error for register ranges
66351 ** P1..P1+P3 and P2..P2+P3 to overlap.
66352 */
66353 case OP_Move: {
66354 #if 0  /* local variables moved into u.ad */
66355   char *zMalloc;   /* Holding variable for allocated memory */
66356   int n;           /* Number of registers left to copy */
66357   int p1;          /* Register to copy from */
66358   int p2;          /* Register to copy to */
66359 #endif /* local variables moved into u.ad */
66360
66361   u.ad.n = pOp->p3 + 1;
66362   u.ad.p1 = pOp->p1;
66363   u.ad.p2 = pOp->p2;
66364   assert( u.ad.n>0 && u.ad.p1>0 && u.ad.p2>0 );
66365   assert( u.ad.p1+u.ad.n<=u.ad.p2 || u.ad.p2+u.ad.n<=u.ad.p1 );
66366
66367   pIn1 = &aMem[u.ad.p1];
66368   pOut = &aMem[u.ad.p2];
66369   while( u.ad.n-- ){
66370     assert( pOut<=&aMem[p->nMem] );
66371     assert( pIn1<=&aMem[p->nMem] );
66372     assert( memIsValid(pIn1) );
66373     memAboutToChange(p, pOut);
66374     u.ad.zMalloc = pOut->zMalloc;
66375     pOut->zMalloc = 0;
66376     sqlite3VdbeMemMove(pOut, pIn1);
66377 #ifdef SQLITE_DEBUG
66378     if( pOut->pScopyFrom>=&aMem[u.ad.p1] && pOut->pScopyFrom<&aMem[u.ad.p1+pOp->p3] ){
66379       pOut->pScopyFrom += u.ad.p1 - pOp->p2;
66380     }
66381 #endif
66382     pIn1->zMalloc = u.ad.zMalloc;
66383     REGISTER_TRACE(u.ad.p2++, pOut);
66384     pIn1++;
66385     pOut++;
66386   }
66387   break;
66388 }
66389
66390 /* Opcode: Copy P1 P2 P3 * *
66391 **
66392 ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
66393 **
66394 ** This instruction makes a deep copy of the value.  A duplicate
66395 ** is made of any string or blob constant.  See also OP_SCopy.
66396 */
66397 case OP_Copy: {
66398 #if 0  /* local variables moved into u.ae */
66399   int n;
66400 #endif /* local variables moved into u.ae */
66401
66402   u.ae.n = pOp->p3;
66403   pIn1 = &aMem[pOp->p1];
66404   pOut = &aMem[pOp->p2];
66405   assert( pOut!=pIn1 );
66406   while( 1 ){
66407     sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
66408     Deephemeralize(pOut);
66409 #ifdef SQLITE_DEBUG
66410     pOut->pScopyFrom = 0;
66411 #endif
66412     REGISTER_TRACE(pOp->p2+pOp->p3-u.ae.n, pOut);
66413     if( (u.ae.n--)==0 ) break;
66414     pOut++;
66415     pIn1++;
66416   }
66417   break;
66418 }
66419
66420 /* Opcode: SCopy P1 P2 * * *
66421 **
66422 ** Make a shallow copy of register P1 into register P2.
66423 **
66424 ** This instruction makes a shallow copy of the value.  If the value
66425 ** is a string or blob, then the copy is only a pointer to the
66426 ** original and hence if the original changes so will the copy.
66427 ** Worse, if the original is deallocated, the copy becomes invalid.
66428 ** Thus the program must guarantee that the original will not change
66429 ** during the lifetime of the copy.  Use OP_Copy to make a complete
66430 ** copy.
66431 */
66432 case OP_SCopy: {            /* in1, out2 */
66433   pIn1 = &aMem[pOp->p1];
66434   pOut = &aMem[pOp->p2];
66435   assert( pOut!=pIn1 );
66436   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
66437 #ifdef SQLITE_DEBUG
66438   if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
66439 #endif
66440   REGISTER_TRACE(pOp->p2, pOut);
66441   break;
66442 }
66443
66444 /* Opcode: ResultRow P1 P2 * * *
66445 **
66446 ** The registers P1 through P1+P2-1 contain a single row of
66447 ** results. This opcode causes the sqlite3_step() call to terminate
66448 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
66449 ** structure to provide access to the top P1 values as the result
66450 ** row.
66451 */
66452 case OP_ResultRow: {
66453 #if 0  /* local variables moved into u.af */
66454   Mem *pMem;
66455   int i;
66456 #endif /* local variables moved into u.af */
66457   assert( p->nResColumn==pOp->p2 );
66458   assert( pOp->p1>0 );
66459   assert( pOp->p1+pOp->p2<=p->nMem+1 );
66460
66461   /* If this statement has violated immediate foreign key constraints, do
66462   ** not return the number of rows modified. And do not RELEASE the statement
66463   ** transaction. It needs to be rolled back.  */
66464   if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
66465     assert( db->flags&SQLITE_CountRows );
66466     assert( p->usesStmtJournal );
66467     break;
66468   }
66469
66470   /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
66471   ** DML statements invoke this opcode to return the number of rows
66472   ** modified to the user. This is the only way that a VM that
66473   ** opens a statement transaction may invoke this opcode.
66474   **
66475   ** In case this is such a statement, close any statement transaction
66476   ** opened by this VM before returning control to the user. This is to
66477   ** ensure that statement-transactions are always nested, not overlapping.
66478   ** If the open statement-transaction is not closed here, then the user
66479   ** may step another VM that opens its own statement transaction. This
66480   ** may lead to overlapping statement transactions.
66481   **
66482   ** The statement transaction is never a top-level transaction.  Hence
66483   ** the RELEASE call below can never fail.
66484   */
66485   assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
66486   rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
66487   if( NEVER(rc!=SQLITE_OK) ){
66488     break;
66489   }
66490
66491   /* Invalidate all ephemeral cursor row caches */
66492   p->cacheCtr = (p->cacheCtr + 2)|1;
66493
66494   /* Make sure the results of the current row are \000 terminated
66495   ** and have an assigned type.  The results are de-ephemeralized as
66496   ** a side effect.
66497   */
66498   u.af.pMem = p->pResultSet = &aMem[pOp->p1];
66499   for(u.af.i=0; u.af.i<pOp->p2; u.af.i++){
66500     assert( memIsValid(&u.af.pMem[u.af.i]) );
66501     Deephemeralize(&u.af.pMem[u.af.i]);
66502     assert( (u.af.pMem[u.af.i].flags & MEM_Ephem)==0
66503             || (u.af.pMem[u.af.i].flags & (MEM_Str|MEM_Blob))==0 );
66504     sqlite3VdbeMemNulTerminate(&u.af.pMem[u.af.i]);
66505     sqlite3VdbeMemStoreType(&u.af.pMem[u.af.i]);
66506     REGISTER_TRACE(pOp->p1+u.af.i, &u.af.pMem[u.af.i]);
66507   }
66508   if( db->mallocFailed ) goto no_mem;
66509
66510   /* Return SQLITE_ROW
66511   */
66512   p->pc = pc + 1;
66513   rc = SQLITE_ROW;
66514   goto vdbe_return;
66515 }
66516
66517 /* Opcode: Concat P1 P2 P3 * *
66518 **
66519 ** Add the text in register P1 onto the end of the text in
66520 ** register P2 and store the result in register P3.
66521 ** If either the P1 or P2 text are NULL then store NULL in P3.
66522 **
66523 **   P3 = P2 || P1
66524 **
66525 ** It is illegal for P1 and P3 to be the same register. Sometimes,
66526 ** if P3 is the same register as P2, the implementation is able
66527 ** to avoid a memcpy().
66528 */
66529 case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
66530 #if 0  /* local variables moved into u.ag */
66531   i64 nByte;
66532 #endif /* local variables moved into u.ag */
66533
66534   pIn1 = &aMem[pOp->p1];
66535   pIn2 = &aMem[pOp->p2];
66536   pOut = &aMem[pOp->p3];
66537   assert( pIn1!=pOut );
66538   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
66539     sqlite3VdbeMemSetNull(pOut);
66540     break;
66541   }
66542   if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
66543   Stringify(pIn1, encoding);
66544   Stringify(pIn2, encoding);
66545   u.ag.nByte = pIn1->n + pIn2->n;
66546   if( u.ag.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
66547     goto too_big;
66548   }
66549   MemSetTypeFlag(pOut, MEM_Str);
66550   if( sqlite3VdbeMemGrow(pOut, (int)u.ag.nByte+2, pOut==pIn2) ){
66551     goto no_mem;
66552   }
66553   if( pOut!=pIn2 ){
66554     memcpy(pOut->z, pIn2->z, pIn2->n);
66555   }
66556   memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
66557   pOut->z[u.ag.nByte] = 0;
66558   pOut->z[u.ag.nByte+1] = 0;
66559   pOut->flags |= MEM_Term;
66560   pOut->n = (int)u.ag.nByte;
66561   pOut->enc = encoding;
66562   UPDATE_MAX_BLOBSIZE(pOut);
66563   break;
66564 }
66565
66566 /* Opcode: Add P1 P2 P3 * *
66567 **
66568 ** Add the value in register P1 to the value in register P2
66569 ** and store the result in register P3.
66570 ** If either input is NULL, the result is NULL.
66571 */
66572 /* Opcode: Multiply P1 P2 P3 * *
66573 **
66574 **
66575 ** Multiply the value in register P1 by the value in register P2
66576 ** and store the result in register P3.
66577 ** If either input is NULL, the result is NULL.
66578 */
66579 /* Opcode: Subtract P1 P2 P3 * *
66580 **
66581 ** Subtract the value in register P1 from the value in register P2
66582 ** and store the result in register P3.
66583 ** If either input is NULL, the result is NULL.
66584 */
66585 /* Opcode: Divide P1 P2 P3 * *
66586 **
66587 ** Divide the value in register P1 by the value in register P2
66588 ** and store the result in register P3 (P3=P2/P1). If the value in 
66589 ** register P1 is zero, then the result is NULL. If either input is 
66590 ** NULL, the result is NULL.
66591 */
66592 /* Opcode: Remainder P1 P2 P3 * *
66593 **
66594 ** Compute the remainder after integer division of the value in
66595 ** register P1 by the value in register P2 and store the result in P3. 
66596 ** If the value in register P2 is zero the result is NULL.
66597 ** If either operand is NULL, the result is NULL.
66598 */
66599 case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
66600 case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
66601 case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
66602 case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
66603 case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
66604 #if 0  /* local variables moved into u.ah */
66605   char bIntint;   /* Started out as two integer operands */
66606   int flags;      /* Combined MEM_* flags from both inputs */
66607   i64 iA;         /* Integer value of left operand */
66608   i64 iB;         /* Integer value of right operand */
66609   double rA;      /* Real value of left operand */
66610   double rB;      /* Real value of right operand */
66611 #endif /* local variables moved into u.ah */
66612
66613   pIn1 = &aMem[pOp->p1];
66614   applyNumericAffinity(pIn1);
66615   pIn2 = &aMem[pOp->p2];
66616   applyNumericAffinity(pIn2);
66617   pOut = &aMem[pOp->p3];
66618   u.ah.flags = pIn1->flags | pIn2->flags;
66619   if( (u.ah.flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
66620   if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
66621     u.ah.iA = pIn1->u.i;
66622     u.ah.iB = pIn2->u.i;
66623     u.ah.bIntint = 1;
66624     switch( pOp->opcode ){
66625       case OP_Add:       if( sqlite3AddInt64(&u.ah.iB,u.ah.iA) ) goto fp_math;  break;
66626       case OP_Subtract:  if( sqlite3SubInt64(&u.ah.iB,u.ah.iA) ) goto fp_math;  break;
66627       case OP_Multiply:  if( sqlite3MulInt64(&u.ah.iB,u.ah.iA) ) goto fp_math;  break;
66628       case OP_Divide: {
66629         if( u.ah.iA==0 ) goto arithmetic_result_is_null;
66630         if( u.ah.iA==-1 && u.ah.iB==SMALLEST_INT64 ) goto fp_math;
66631         u.ah.iB /= u.ah.iA;
66632         break;
66633       }
66634       default: {
66635         if( u.ah.iA==0 ) goto arithmetic_result_is_null;
66636         if( u.ah.iA==-1 ) u.ah.iA = 1;
66637         u.ah.iB %= u.ah.iA;
66638         break;
66639       }
66640     }
66641     pOut->u.i = u.ah.iB;
66642     MemSetTypeFlag(pOut, MEM_Int);
66643   }else{
66644     u.ah.bIntint = 0;
66645 fp_math:
66646     u.ah.rA = sqlite3VdbeRealValue(pIn1);
66647     u.ah.rB = sqlite3VdbeRealValue(pIn2);
66648     switch( pOp->opcode ){
66649       case OP_Add:         u.ah.rB += u.ah.rA;       break;
66650       case OP_Subtract:    u.ah.rB -= u.ah.rA;       break;
66651       case OP_Multiply:    u.ah.rB *= u.ah.rA;       break;
66652       case OP_Divide: {
66653         /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
66654         if( u.ah.rA==(double)0 ) goto arithmetic_result_is_null;
66655         u.ah.rB /= u.ah.rA;
66656         break;
66657       }
66658       default: {
66659         u.ah.iA = (i64)u.ah.rA;
66660         u.ah.iB = (i64)u.ah.rB;
66661         if( u.ah.iA==0 ) goto arithmetic_result_is_null;
66662         if( u.ah.iA==-1 ) u.ah.iA = 1;
66663         u.ah.rB = (double)(u.ah.iB % u.ah.iA);
66664         break;
66665       }
66666     }
66667 #ifdef SQLITE_OMIT_FLOATING_POINT
66668     pOut->u.i = u.ah.rB;
66669     MemSetTypeFlag(pOut, MEM_Int);
66670 #else
66671     if( sqlite3IsNaN(u.ah.rB) ){
66672       goto arithmetic_result_is_null;
66673     }
66674     pOut->r = u.ah.rB;
66675     MemSetTypeFlag(pOut, MEM_Real);
66676     if( (u.ah.flags & MEM_Real)==0 && !u.ah.bIntint ){
66677       sqlite3VdbeIntegerAffinity(pOut);
66678     }
66679 #endif
66680   }
66681   break;
66682
66683 arithmetic_result_is_null:
66684   sqlite3VdbeMemSetNull(pOut);
66685   break;
66686 }
66687
66688 /* Opcode: CollSeq P1 * * P4
66689 **
66690 ** P4 is a pointer to a CollSeq struct. If the next call to a user function
66691 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
66692 ** be returned. This is used by the built-in min(), max() and nullif()
66693 ** functions.
66694 **
66695 ** If P1 is not zero, then it is a register that a subsequent min() or
66696 ** max() aggregate will set to 1 if the current row is not the minimum or
66697 ** maximum.  The P1 register is initialized to 0 by this instruction.
66698 **
66699 ** The interface used by the implementation of the aforementioned functions
66700 ** to retrieve the collation sequence set by this opcode is not available
66701 ** publicly, only to user functions defined in func.c.
66702 */
66703 case OP_CollSeq: {
66704   assert( pOp->p4type==P4_COLLSEQ );
66705   if( pOp->p1 ){
66706     sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
66707   }
66708   break;
66709 }
66710
66711 /* Opcode: Function P1 P2 P3 P4 P5
66712 **
66713 ** Invoke a user function (P4 is a pointer to a Function structure that
66714 ** defines the function) with P5 arguments taken from register P2 and
66715 ** successors.  The result of the function is stored in register P3.
66716 ** Register P3 must not be one of the function inputs.
66717 **
66718 ** P1 is a 32-bit bitmask indicating whether or not each argument to the 
66719 ** function was determined to be constant at compile time. If the first
66720 ** argument was constant then bit 0 of P1 is set. This is used to determine
66721 ** whether meta data associated with a user function argument using the
66722 ** sqlite3_set_auxdata() API may be safely retained until the next
66723 ** invocation of this opcode.
66724 **
66725 ** See also: AggStep and AggFinal
66726 */
66727 case OP_Function: {
66728 #if 0  /* local variables moved into u.ai */
66729   int i;
66730   Mem *pArg;
66731   sqlite3_context ctx;
66732   sqlite3_value **apVal;
66733   int n;
66734 #endif /* local variables moved into u.ai */
66735
66736   u.ai.n = pOp->p5;
66737   u.ai.apVal = p->apArg;
66738   assert( u.ai.apVal || u.ai.n==0 );
66739   assert( pOp->p3>0 && pOp->p3<=p->nMem );
66740   pOut = &aMem[pOp->p3];
66741   memAboutToChange(p, pOut);
66742
66743   assert( u.ai.n==0 || (pOp->p2>0 && pOp->p2+u.ai.n<=p->nMem+1) );
66744   assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+u.ai.n );
66745   u.ai.pArg = &aMem[pOp->p2];
66746   for(u.ai.i=0; u.ai.i<u.ai.n; u.ai.i++, u.ai.pArg++){
66747     assert( memIsValid(u.ai.pArg) );
66748     u.ai.apVal[u.ai.i] = u.ai.pArg;
66749     Deephemeralize(u.ai.pArg);
66750     sqlite3VdbeMemStoreType(u.ai.pArg);
66751     REGISTER_TRACE(pOp->p2+u.ai.i, u.ai.pArg);
66752   }
66753
66754   assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
66755   if( pOp->p4type==P4_FUNCDEF ){
66756     u.ai.ctx.pFunc = pOp->p4.pFunc;
66757     u.ai.ctx.pVdbeFunc = 0;
66758   }else{
66759     u.ai.ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
66760     u.ai.ctx.pFunc = u.ai.ctx.pVdbeFunc->pFunc;
66761   }
66762
66763   u.ai.ctx.s.flags = MEM_Null;
66764   u.ai.ctx.s.db = db;
66765   u.ai.ctx.s.xDel = 0;
66766   u.ai.ctx.s.zMalloc = 0;
66767
66768   /* The output cell may already have a buffer allocated. Move
66769   ** the pointer to u.ai.ctx.s so in case the user-function can use
66770   ** the already allocated buffer instead of allocating a new one.
66771   */
66772   sqlite3VdbeMemMove(&u.ai.ctx.s, pOut);
66773   MemSetTypeFlag(&u.ai.ctx.s, MEM_Null);
66774
66775   u.ai.ctx.isError = 0;
66776   if( u.ai.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
66777     assert( pOp>aOp );
66778     assert( pOp[-1].p4type==P4_COLLSEQ );
66779     assert( pOp[-1].opcode==OP_CollSeq );
66780     u.ai.ctx.pColl = pOp[-1].p4.pColl;
66781   }
66782   db->lastRowid = lastRowid;
66783   (*u.ai.ctx.pFunc->xFunc)(&u.ai.ctx, u.ai.n, u.ai.apVal); /* IMP: R-24505-23230 */
66784   lastRowid = db->lastRowid;
66785
66786   /* If any auxiliary data functions have been called by this user function,
66787   ** immediately call the destructor for any non-static values.
66788   */
66789   if( u.ai.ctx.pVdbeFunc ){
66790     sqlite3VdbeDeleteAuxData(u.ai.ctx.pVdbeFunc, pOp->p1);
66791     pOp->p4.pVdbeFunc = u.ai.ctx.pVdbeFunc;
66792     pOp->p4type = P4_VDBEFUNC;
66793   }
66794
66795   if( db->mallocFailed ){
66796     /* Even though a malloc() has failed, the implementation of the
66797     ** user function may have called an sqlite3_result_XXX() function
66798     ** to return a value. The following call releases any resources
66799     ** associated with such a value.
66800     */
66801     sqlite3VdbeMemRelease(&u.ai.ctx.s);
66802     goto no_mem;
66803   }
66804
66805   /* If the function returned an error, throw an exception */
66806   if( u.ai.ctx.isError ){
66807     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.ai.ctx.s));
66808     rc = u.ai.ctx.isError;
66809   }
66810
66811   /* Copy the result of the function into register P3 */
66812   sqlite3VdbeChangeEncoding(&u.ai.ctx.s, encoding);
66813   sqlite3VdbeMemMove(pOut, &u.ai.ctx.s);
66814   if( sqlite3VdbeMemTooBig(pOut) ){
66815     goto too_big;
66816   }
66817
66818 #if 0
66819   /* The app-defined function has done something that as caused this
66820   ** statement to expire.  (Perhaps the function called sqlite3_exec()
66821   ** with a CREATE TABLE statement.)
66822   */
66823   if( p->expired ) rc = SQLITE_ABORT;
66824 #endif
66825
66826   REGISTER_TRACE(pOp->p3, pOut);
66827   UPDATE_MAX_BLOBSIZE(pOut);
66828   break;
66829 }
66830
66831 /* Opcode: BitAnd P1 P2 P3 * *
66832 **
66833 ** Take the bit-wise AND of the values in register P1 and P2 and
66834 ** store the result in register P3.
66835 ** If either input is NULL, the result is NULL.
66836 */
66837 /* Opcode: BitOr P1 P2 P3 * *
66838 **
66839 ** Take the bit-wise OR of the values in register P1 and P2 and
66840 ** store the result in register P3.
66841 ** If either input is NULL, the result is NULL.
66842 */
66843 /* Opcode: ShiftLeft P1 P2 P3 * *
66844 **
66845 ** Shift the integer value in register P2 to the left by the
66846 ** number of bits specified by the integer in register P1.
66847 ** Store the result in register P3.
66848 ** If either input is NULL, the result is NULL.
66849 */
66850 /* Opcode: ShiftRight P1 P2 P3 * *
66851 **
66852 ** Shift the integer value in register P2 to the right by the
66853 ** number of bits specified by the integer in register P1.
66854 ** Store the result in register P3.
66855 ** If either input is NULL, the result is NULL.
66856 */
66857 case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
66858 case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
66859 case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
66860 case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
66861 #if 0  /* local variables moved into u.aj */
66862   i64 iA;
66863   u64 uA;
66864   i64 iB;
66865   u8 op;
66866 #endif /* local variables moved into u.aj */
66867
66868   pIn1 = &aMem[pOp->p1];
66869   pIn2 = &aMem[pOp->p2];
66870   pOut = &aMem[pOp->p3];
66871   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
66872     sqlite3VdbeMemSetNull(pOut);
66873     break;
66874   }
66875   u.aj.iA = sqlite3VdbeIntValue(pIn2);
66876   u.aj.iB = sqlite3VdbeIntValue(pIn1);
66877   u.aj.op = pOp->opcode;
66878   if( u.aj.op==OP_BitAnd ){
66879     u.aj.iA &= u.aj.iB;
66880   }else if( u.aj.op==OP_BitOr ){
66881     u.aj.iA |= u.aj.iB;
66882   }else if( u.aj.iB!=0 ){
66883     assert( u.aj.op==OP_ShiftRight || u.aj.op==OP_ShiftLeft );
66884
66885     /* If shifting by a negative amount, shift in the other direction */
66886     if( u.aj.iB<0 ){
66887       assert( OP_ShiftRight==OP_ShiftLeft+1 );
66888       u.aj.op = 2*OP_ShiftLeft + 1 - u.aj.op;
66889       u.aj.iB = u.aj.iB>(-64) ? -u.aj.iB : 64;
66890     }
66891
66892     if( u.aj.iB>=64 ){
66893       u.aj.iA = (u.aj.iA>=0 || u.aj.op==OP_ShiftLeft) ? 0 : -1;
66894     }else{
66895       memcpy(&u.aj.uA, &u.aj.iA, sizeof(u.aj.uA));
66896       if( u.aj.op==OP_ShiftLeft ){
66897         u.aj.uA <<= u.aj.iB;
66898       }else{
66899         u.aj.uA >>= u.aj.iB;
66900         /* Sign-extend on a right shift of a negative number */
66901         if( u.aj.iA<0 ) u.aj.uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-u.aj.iB);
66902       }
66903       memcpy(&u.aj.iA, &u.aj.uA, sizeof(u.aj.iA));
66904     }
66905   }
66906   pOut->u.i = u.aj.iA;
66907   MemSetTypeFlag(pOut, MEM_Int);
66908   break;
66909 }
66910
66911 /* Opcode: AddImm  P1 P2 * * *
66912 ** 
66913 ** Add the constant P2 to the value in register P1.
66914 ** The result is always an integer.
66915 **
66916 ** To force any register to be an integer, just add 0.
66917 */
66918 case OP_AddImm: {            /* in1 */
66919   pIn1 = &aMem[pOp->p1];
66920   memAboutToChange(p, pIn1);
66921   sqlite3VdbeMemIntegerify(pIn1);
66922   pIn1->u.i += pOp->p2;
66923   break;
66924 }
66925
66926 /* Opcode: MustBeInt P1 P2 * * *
66927 ** 
66928 ** Force the value in register P1 to be an integer.  If the value
66929 ** in P1 is not an integer and cannot be converted into an integer
66930 ** without data loss, then jump immediately to P2, or if P2==0
66931 ** raise an SQLITE_MISMATCH exception.
66932 */
66933 case OP_MustBeInt: {            /* jump, in1 */
66934   pIn1 = &aMem[pOp->p1];
66935   applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
66936   if( (pIn1->flags & MEM_Int)==0 ){
66937     if( pOp->p2==0 ){
66938       rc = SQLITE_MISMATCH;
66939       goto abort_due_to_error;
66940     }else{
66941       pc = pOp->p2 - 1;
66942     }
66943   }else{
66944     MemSetTypeFlag(pIn1, MEM_Int);
66945   }
66946   break;
66947 }
66948
66949 #ifndef SQLITE_OMIT_FLOATING_POINT
66950 /* Opcode: RealAffinity P1 * * * *
66951 **
66952 ** If register P1 holds an integer convert it to a real value.
66953 **
66954 ** This opcode is used when extracting information from a column that
66955 ** has REAL affinity.  Such column values may still be stored as
66956 ** integers, for space efficiency, but after extraction we want them
66957 ** to have only a real value.
66958 */
66959 case OP_RealAffinity: {                  /* in1 */
66960   pIn1 = &aMem[pOp->p1];
66961   if( pIn1->flags & MEM_Int ){
66962     sqlite3VdbeMemRealify(pIn1);
66963   }
66964   break;
66965 }
66966 #endif
66967
66968 #ifndef SQLITE_OMIT_CAST
66969 /* Opcode: ToText P1 * * * *
66970 **
66971 ** Force the value in register P1 to be text.
66972 ** If the value is numeric, convert it to a string using the
66973 ** equivalent of printf().  Blob values are unchanged and
66974 ** are afterwards simply interpreted as text.
66975 **
66976 ** A NULL value is not changed by this routine.  It remains NULL.
66977 */
66978 case OP_ToText: {                  /* same as TK_TO_TEXT, in1 */
66979   pIn1 = &aMem[pOp->p1];
66980   memAboutToChange(p, pIn1);
66981   if( pIn1->flags & MEM_Null ) break;
66982   assert( MEM_Str==(MEM_Blob>>3) );
66983   pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
66984   applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
66985   rc = ExpandBlob(pIn1);
66986   assert( pIn1->flags & MEM_Str || db->mallocFailed );
66987   pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
66988   UPDATE_MAX_BLOBSIZE(pIn1);
66989   break;
66990 }
66991
66992 /* Opcode: ToBlob P1 * * * *
66993 **
66994 ** Force the value in register P1 to be a BLOB.
66995 ** If the value is numeric, convert it to a string first.
66996 ** Strings are simply reinterpreted as blobs with no change
66997 ** to the underlying data.
66998 **
66999 ** A NULL value is not changed by this routine.  It remains NULL.
67000 */
67001 case OP_ToBlob: {                  /* same as TK_TO_BLOB, in1 */
67002   pIn1 = &aMem[pOp->p1];
67003   if( pIn1->flags & MEM_Null ) break;
67004   if( (pIn1->flags & MEM_Blob)==0 ){
67005     applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
67006     assert( pIn1->flags & MEM_Str || db->mallocFailed );
67007     MemSetTypeFlag(pIn1, MEM_Blob);
67008   }else{
67009     pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
67010   }
67011   UPDATE_MAX_BLOBSIZE(pIn1);
67012   break;
67013 }
67014
67015 /* Opcode: ToNumeric P1 * * * *
67016 **
67017 ** Force the value in register P1 to be numeric (either an
67018 ** integer or a floating-point number.)
67019 ** If the value is text or blob, try to convert it to an using the
67020 ** equivalent of atoi() or atof() and store 0 if no such conversion 
67021 ** is possible.
67022 **
67023 ** A NULL value is not changed by this routine.  It remains NULL.
67024 */
67025 case OP_ToNumeric: {                  /* same as TK_TO_NUMERIC, in1 */
67026   pIn1 = &aMem[pOp->p1];
67027   sqlite3VdbeMemNumerify(pIn1);
67028   break;
67029 }
67030 #endif /* SQLITE_OMIT_CAST */
67031
67032 /* Opcode: ToInt P1 * * * *
67033 **
67034 ** Force the value in register P1 to be an integer.  If
67035 ** The value is currently a real number, drop its fractional part.
67036 ** If the value is text or blob, try to convert it to an integer using the
67037 ** equivalent of atoi() and store 0 if no such conversion is possible.
67038 **
67039 ** A NULL value is not changed by this routine.  It remains NULL.
67040 */
67041 case OP_ToInt: {                  /* same as TK_TO_INT, in1 */
67042   pIn1 = &aMem[pOp->p1];
67043   if( (pIn1->flags & MEM_Null)==0 ){
67044     sqlite3VdbeMemIntegerify(pIn1);
67045   }
67046   break;
67047 }
67048
67049 #if !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT)
67050 /* Opcode: ToReal P1 * * * *
67051 **
67052 ** Force the value in register P1 to be a floating point number.
67053 ** If The value is currently an integer, convert it.
67054 ** If the value is text or blob, try to convert it to an integer using the
67055 ** equivalent of atoi() and store 0.0 if no such conversion is possible.
67056 **
67057 ** A NULL value is not changed by this routine.  It remains NULL.
67058 */
67059 case OP_ToReal: {                  /* same as TK_TO_REAL, in1 */
67060   pIn1 = &aMem[pOp->p1];
67061   memAboutToChange(p, pIn1);
67062   if( (pIn1->flags & MEM_Null)==0 ){
67063     sqlite3VdbeMemRealify(pIn1);
67064   }
67065   break;
67066 }
67067 #endif /* !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) */
67068
67069 /* Opcode: Lt P1 P2 P3 P4 P5
67070 **
67071 ** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
67072 ** jump to address P2.  
67073 **
67074 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
67075 ** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL 
67076 ** bit is clear then fall through if either operand is NULL.
67077 **
67078 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
67079 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made 
67080 ** to coerce both inputs according to this affinity before the
67081 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
67082 ** affinity is used. Note that the affinity conversions are stored
67083 ** back into the input registers P1 and P3.  So this opcode can cause
67084 ** persistent changes to registers P1 and P3.
67085 **
67086 ** Once any conversions have taken place, and neither value is NULL, 
67087 ** the values are compared. If both values are blobs then memcmp() is
67088 ** used to determine the results of the comparison.  If both values
67089 ** are text, then the appropriate collating function specified in
67090 ** P4 is  used to do the comparison.  If P4 is not specified then
67091 ** memcmp() is used to compare text string.  If both values are
67092 ** numeric, then a numeric comparison is used. If the two values
67093 ** are of different types, then numbers are considered less than
67094 ** strings and strings are considered less than blobs.
67095 **
67096 ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
67097 ** store a boolean result (either 0, or 1, or NULL) in register P2.
67098 **
67099 ** If the SQLITE_NULLEQ bit is set in P5, then NULL values are considered
67100 ** equal to one another, provided that they do not have their MEM_Cleared
67101 ** bit set.
67102 */
67103 /* Opcode: Ne P1 P2 P3 P4 P5
67104 **
67105 ** This works just like the Lt opcode except that the jump is taken if
67106 ** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
67107 ** additional information.
67108 **
67109 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
67110 ** true or false and is never NULL.  If both operands are NULL then the result
67111 ** of comparison is false.  If either operand is NULL then the result is true.
67112 ** If neither operand is NULL the result is the same as it would be if
67113 ** the SQLITE_NULLEQ flag were omitted from P5.
67114 */
67115 /* Opcode: Eq P1 P2 P3 P4 P5
67116 **
67117 ** This works just like the Lt opcode except that the jump is taken if
67118 ** the operands in registers P1 and P3 are equal.
67119 ** See the Lt opcode for additional information.
67120 **
67121 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
67122 ** true or false and is never NULL.  If both operands are NULL then the result
67123 ** of comparison is true.  If either operand is NULL then the result is false.
67124 ** If neither operand is NULL the result is the same as it would be if
67125 ** the SQLITE_NULLEQ flag were omitted from P5.
67126 */
67127 /* Opcode: Le P1 P2 P3 P4 P5
67128 **
67129 ** This works just like the Lt opcode except that the jump is taken if
67130 ** the content of register P3 is less than or equal to the content of
67131 ** register P1.  See the Lt opcode for additional information.
67132 */
67133 /* Opcode: Gt P1 P2 P3 P4 P5
67134 **
67135 ** This works just like the Lt opcode except that the jump is taken if
67136 ** the content of register P3 is greater than the content of
67137 ** register P1.  See the Lt opcode for additional information.
67138 */
67139 /* Opcode: Ge P1 P2 P3 P4 P5
67140 **
67141 ** This works just like the Lt opcode except that the jump is taken if
67142 ** the content of register P3 is greater than or equal to the content of
67143 ** register P1.  See the Lt opcode for additional information.
67144 */
67145 case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
67146 case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
67147 case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
67148 case OP_Le:               /* same as TK_LE, jump, in1, in3 */
67149 case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
67150 case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
67151 #if 0  /* local variables moved into u.ak */
67152   int res;            /* Result of the comparison of pIn1 against pIn3 */
67153   char affinity;      /* Affinity to use for comparison */
67154   u16 flags1;         /* Copy of initial value of pIn1->flags */
67155   u16 flags3;         /* Copy of initial value of pIn3->flags */
67156 #endif /* local variables moved into u.ak */
67157
67158   pIn1 = &aMem[pOp->p1];
67159   pIn3 = &aMem[pOp->p3];
67160   u.ak.flags1 = pIn1->flags;
67161   u.ak.flags3 = pIn3->flags;
67162   if( (u.ak.flags1 | u.ak.flags3)&MEM_Null ){
67163     /* One or both operands are NULL */
67164     if( pOp->p5 & SQLITE_NULLEQ ){
67165       /* If SQLITE_NULLEQ is set (which will only happen if the operator is
67166       ** OP_Eq or OP_Ne) then take the jump or not depending on whether
67167       ** or not both operands are null.
67168       */
67169       assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
67170       assert( (u.ak.flags1 & MEM_Cleared)==0 );
67171       if( (u.ak.flags1&MEM_Null)!=0
67172        && (u.ak.flags3&MEM_Null)!=0
67173        && (u.ak.flags3&MEM_Cleared)==0
67174       ){
67175         u.ak.res = 0;  /* Results are equal */
67176       }else{
67177         u.ak.res = 1;  /* Results are not equal */
67178       }
67179     }else{
67180       /* SQLITE_NULLEQ is clear and at least one operand is NULL,
67181       ** then the result is always NULL.
67182       ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
67183       */
67184       if( pOp->p5 & SQLITE_STOREP2 ){
67185         pOut = &aMem[pOp->p2];
67186         MemSetTypeFlag(pOut, MEM_Null);
67187         REGISTER_TRACE(pOp->p2, pOut);
67188       }else if( pOp->p5 & SQLITE_JUMPIFNULL ){
67189         pc = pOp->p2-1;
67190       }
67191       break;
67192     }
67193   }else{
67194     /* Neither operand is NULL.  Do a comparison. */
67195     u.ak.affinity = pOp->p5 & SQLITE_AFF_MASK;
67196     if( u.ak.affinity ){
67197       applyAffinity(pIn1, u.ak.affinity, encoding);
67198       applyAffinity(pIn3, u.ak.affinity, encoding);
67199       if( db->mallocFailed ) goto no_mem;
67200     }
67201
67202     assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
67203     ExpandBlob(pIn1);
67204     ExpandBlob(pIn3);
67205     u.ak.res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
67206   }
67207   switch( pOp->opcode ){
67208     case OP_Eq:    u.ak.res = u.ak.res==0;     break;
67209     case OP_Ne:    u.ak.res = u.ak.res!=0;     break;
67210     case OP_Lt:    u.ak.res = u.ak.res<0;      break;
67211     case OP_Le:    u.ak.res = u.ak.res<=0;     break;
67212     case OP_Gt:    u.ak.res = u.ak.res>0;      break;
67213     default:       u.ak.res = u.ak.res>=0;     break;
67214   }
67215
67216   if( pOp->p5 & SQLITE_STOREP2 ){
67217     pOut = &aMem[pOp->p2];
67218     memAboutToChange(p, pOut);
67219     MemSetTypeFlag(pOut, MEM_Int);
67220     pOut->u.i = u.ak.res;
67221     REGISTER_TRACE(pOp->p2, pOut);
67222   }else if( u.ak.res ){
67223     pc = pOp->p2-1;
67224   }
67225
67226   /* Undo any changes made by applyAffinity() to the input registers. */
67227   pIn1->flags = (pIn1->flags&~MEM_TypeMask) | (u.ak.flags1&MEM_TypeMask);
67228   pIn3->flags = (pIn3->flags&~MEM_TypeMask) | (u.ak.flags3&MEM_TypeMask);
67229   break;
67230 }
67231
67232 /* Opcode: Permutation * * * P4 *
67233 **
67234 ** Set the permutation used by the OP_Compare operator to be the array
67235 ** of integers in P4.
67236 **
67237 ** The permutation is only valid until the next OP_Compare that has
67238 ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should 
67239 ** occur immediately prior to the OP_Compare.
67240 */
67241 case OP_Permutation: {
67242   assert( pOp->p4type==P4_INTARRAY );
67243   assert( pOp->p4.ai );
67244   aPermute = pOp->p4.ai;
67245   break;
67246 }
67247
67248 /* Opcode: Compare P1 P2 P3 P4 P5
67249 **
67250 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
67251 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
67252 ** the comparison for use by the next OP_Jump instruct.
67253 **
67254 ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
67255 ** determined by the most recent OP_Permutation operator.  If the
67256 ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
67257 ** order.
67258 **
67259 ** P4 is a KeyInfo structure that defines collating sequences and sort
67260 ** orders for the comparison.  The permutation applies to registers
67261 ** only.  The KeyInfo elements are used sequentially.
67262 **
67263 ** The comparison is a sort comparison, so NULLs compare equal,
67264 ** NULLs are less than numbers, numbers are less than strings,
67265 ** and strings are less than blobs.
67266 */
67267 case OP_Compare: {
67268 #if 0  /* local variables moved into u.al */
67269   int n;
67270   int i;
67271   int p1;
67272   int p2;
67273   const KeyInfo *pKeyInfo;
67274   int idx;
67275   CollSeq *pColl;    /* Collating sequence to use on this term */
67276   int bRev;          /* True for DESCENDING sort order */
67277 #endif /* local variables moved into u.al */
67278
67279   if( (pOp->p5 & OPFLAG_PERMUTE)==0 ) aPermute = 0;
67280   u.al.n = pOp->p3;
67281   u.al.pKeyInfo = pOp->p4.pKeyInfo;
67282   assert( u.al.n>0 );
67283   assert( u.al.pKeyInfo!=0 );
67284   u.al.p1 = pOp->p1;
67285   u.al.p2 = pOp->p2;
67286 #if SQLITE_DEBUG
67287   if( aPermute ){
67288     int k, mx = 0;
67289     for(k=0; k<u.al.n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
67290     assert( u.al.p1>0 && u.al.p1+mx<=p->nMem+1 );
67291     assert( u.al.p2>0 && u.al.p2+mx<=p->nMem+1 );
67292   }else{
67293     assert( u.al.p1>0 && u.al.p1+u.al.n<=p->nMem+1 );
67294     assert( u.al.p2>0 && u.al.p2+u.al.n<=p->nMem+1 );
67295   }
67296 #endif /* SQLITE_DEBUG */
67297   for(u.al.i=0; u.al.i<u.al.n; u.al.i++){
67298     u.al.idx = aPermute ? aPermute[u.al.i] : u.al.i;
67299     assert( memIsValid(&aMem[u.al.p1+u.al.idx]) );
67300     assert( memIsValid(&aMem[u.al.p2+u.al.idx]) );
67301     REGISTER_TRACE(u.al.p1+u.al.idx, &aMem[u.al.p1+u.al.idx]);
67302     REGISTER_TRACE(u.al.p2+u.al.idx, &aMem[u.al.p2+u.al.idx]);
67303     assert( u.al.i<u.al.pKeyInfo->nField );
67304     u.al.pColl = u.al.pKeyInfo->aColl[u.al.i];
67305     u.al.bRev = u.al.pKeyInfo->aSortOrder[u.al.i];
67306     iCompare = sqlite3MemCompare(&aMem[u.al.p1+u.al.idx], &aMem[u.al.p2+u.al.idx], u.al.pColl);
67307     if( iCompare ){
67308       if( u.al.bRev ) iCompare = -iCompare;
67309       break;
67310     }
67311   }
67312   aPermute = 0;
67313   break;
67314 }
67315
67316 /* Opcode: Jump P1 P2 P3 * *
67317 **
67318 ** Jump to the instruction at address P1, P2, or P3 depending on whether
67319 ** in the most recent OP_Compare instruction the P1 vector was less than
67320 ** equal to, or greater than the P2 vector, respectively.
67321 */
67322 case OP_Jump: {             /* jump */
67323   if( iCompare<0 ){
67324     pc = pOp->p1 - 1;
67325   }else if( iCompare==0 ){
67326     pc = pOp->p2 - 1;
67327   }else{
67328     pc = pOp->p3 - 1;
67329   }
67330   break;
67331 }
67332
67333 /* Opcode: And P1 P2 P3 * *
67334 **
67335 ** Take the logical AND of the values in registers P1 and P2 and
67336 ** write the result into register P3.
67337 **
67338 ** If either P1 or P2 is 0 (false) then the result is 0 even if
67339 ** the other input is NULL.  A NULL and true or two NULLs give
67340 ** a NULL output.
67341 */
67342 /* Opcode: Or P1 P2 P3 * *
67343 **
67344 ** Take the logical OR of the values in register P1 and P2 and
67345 ** store the answer in register P3.
67346 **
67347 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
67348 ** even if the other input is NULL.  A NULL and false or two NULLs
67349 ** give a NULL output.
67350 */
67351 case OP_And:              /* same as TK_AND, in1, in2, out3 */
67352 case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
67353 #if 0  /* local variables moved into u.am */
67354   int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
67355   int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
67356 #endif /* local variables moved into u.am */
67357
67358   pIn1 = &aMem[pOp->p1];
67359   if( pIn1->flags & MEM_Null ){
67360     u.am.v1 = 2;
67361   }else{
67362     u.am.v1 = sqlite3VdbeIntValue(pIn1)!=0;
67363   }
67364   pIn2 = &aMem[pOp->p2];
67365   if( pIn2->flags & MEM_Null ){
67366     u.am.v2 = 2;
67367   }else{
67368     u.am.v2 = sqlite3VdbeIntValue(pIn2)!=0;
67369   }
67370   if( pOp->opcode==OP_And ){
67371     static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
67372     u.am.v1 = and_logic[u.am.v1*3+u.am.v2];
67373   }else{
67374     static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
67375     u.am.v1 = or_logic[u.am.v1*3+u.am.v2];
67376   }
67377   pOut = &aMem[pOp->p3];
67378   if( u.am.v1==2 ){
67379     MemSetTypeFlag(pOut, MEM_Null);
67380   }else{
67381     pOut->u.i = u.am.v1;
67382     MemSetTypeFlag(pOut, MEM_Int);
67383   }
67384   break;
67385 }
67386
67387 /* Opcode: Not P1 P2 * * *
67388 **
67389 ** Interpret the value in register P1 as a boolean value.  Store the
67390 ** boolean complement in register P2.  If the value in register P1 is 
67391 ** NULL, then a NULL is stored in P2.
67392 */
67393 case OP_Not: {                /* same as TK_NOT, in1, out2 */
67394   pIn1 = &aMem[pOp->p1];
67395   pOut = &aMem[pOp->p2];
67396   if( pIn1->flags & MEM_Null ){
67397     sqlite3VdbeMemSetNull(pOut);
67398   }else{
67399     sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
67400   }
67401   break;
67402 }
67403
67404 /* Opcode: BitNot P1 P2 * * *
67405 **
67406 ** Interpret the content of register P1 as an integer.  Store the
67407 ** ones-complement of the P1 value into register P2.  If P1 holds
67408 ** a NULL then store a NULL in P2.
67409 */
67410 case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
67411   pIn1 = &aMem[pOp->p1];
67412   pOut = &aMem[pOp->p2];
67413   if( pIn1->flags & MEM_Null ){
67414     sqlite3VdbeMemSetNull(pOut);
67415   }else{
67416     sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
67417   }
67418   break;
67419 }
67420
67421 /* Opcode: Once P1 P2 * * *
67422 **
67423 ** Check if OP_Once flag P1 is set. If so, jump to instruction P2. Otherwise,
67424 ** set the flag and fall through to the next instruction.
67425 */
67426 case OP_Once: {             /* jump */
67427   assert( pOp->p1<p->nOnceFlag );
67428   if( p->aOnceFlag[pOp->p1] ){
67429     pc = pOp->p2-1;
67430   }else{
67431     p->aOnceFlag[pOp->p1] = 1;
67432   }
67433   break;
67434 }
67435
67436 /* Opcode: If P1 P2 P3 * *
67437 **
67438 ** Jump to P2 if the value in register P1 is true.  The value
67439 ** is considered true if it is numeric and non-zero.  If the value
67440 ** in P1 is NULL then take the jump if P3 is non-zero.
67441 */
67442 /* Opcode: IfNot P1 P2 P3 * *
67443 **
67444 ** Jump to P2 if the value in register P1 is False.  The value
67445 ** is considered false if it has a numeric value of zero.  If the value
67446 ** in P1 is NULL then take the jump if P3 is zero.
67447 */
67448 case OP_If:                 /* jump, in1 */
67449 case OP_IfNot: {            /* jump, in1 */
67450 #if 0  /* local variables moved into u.an */
67451   int c;
67452 #endif /* local variables moved into u.an */
67453   pIn1 = &aMem[pOp->p1];
67454   if( pIn1->flags & MEM_Null ){
67455     u.an.c = pOp->p3;
67456   }else{
67457 #ifdef SQLITE_OMIT_FLOATING_POINT
67458     u.an.c = sqlite3VdbeIntValue(pIn1)!=0;
67459 #else
67460     u.an.c = sqlite3VdbeRealValue(pIn1)!=0.0;
67461 #endif
67462     if( pOp->opcode==OP_IfNot ) u.an.c = !u.an.c;
67463   }
67464   if( u.an.c ){
67465     pc = pOp->p2-1;
67466   }
67467   break;
67468 }
67469
67470 /* Opcode: IsNull P1 P2 * * *
67471 **
67472 ** Jump to P2 if the value in register P1 is NULL.
67473 */
67474 case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
67475   pIn1 = &aMem[pOp->p1];
67476   if( (pIn1->flags & MEM_Null)!=0 ){
67477     pc = pOp->p2 - 1;
67478   }
67479   break;
67480 }
67481
67482 /* Opcode: NotNull P1 P2 * * *
67483 **
67484 ** Jump to P2 if the value in register P1 is not NULL.  
67485 */
67486 case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
67487   pIn1 = &aMem[pOp->p1];
67488   if( (pIn1->flags & MEM_Null)==0 ){
67489     pc = pOp->p2 - 1;
67490   }
67491   break;
67492 }
67493
67494 /* Opcode: Column P1 P2 P3 P4 P5
67495 **
67496 ** Interpret the data that cursor P1 points to as a structure built using
67497 ** the MakeRecord instruction.  (See the MakeRecord opcode for additional
67498 ** information about the format of the data.)  Extract the P2-th column
67499 ** from this record.  If there are less that (P2+1) 
67500 ** values in the record, extract a NULL.
67501 **
67502 ** The value extracted is stored in register P3.
67503 **
67504 ** If the column contains fewer than P2 fields, then extract a NULL.  Or,
67505 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
67506 ** the result.
67507 **
67508 ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
67509 ** then the cache of the cursor is reset prior to extracting the column.
67510 ** The first OP_Column against a pseudo-table after the value of the content
67511 ** register has changed should have this bit set.
67512 **
67513 ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 when
67514 ** the result is guaranteed to only be used as the argument of a length()
67515 ** or typeof() function, respectively.  The loading of large blobs can be
67516 ** skipped for length() and all content loading can be skipped for typeof().
67517 */
67518 case OP_Column: {
67519 #if 0  /* local variables moved into u.ao */
67520   u32 payloadSize;   /* Number of bytes in the record */
67521   i64 payloadSize64; /* Number of bytes in the record */
67522   int p1;            /* P1 value of the opcode */
67523   int p2;            /* column number to retrieve */
67524   VdbeCursor *pC;    /* The VDBE cursor */
67525   char *zRec;        /* Pointer to complete record-data */
67526   BtCursor *pCrsr;   /* The BTree cursor */
67527   u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
67528   u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
67529   int nField;        /* number of fields in the record */
67530   int len;           /* The length of the serialized data for the column */
67531   int i;             /* Loop counter */
67532   char *zData;       /* Part of the record being decoded */
67533   Mem *pDest;        /* Where to write the extracted value */
67534   Mem sMem;          /* For storing the record being decoded */
67535   u8 *zIdx;          /* Index into header */
67536   u8 *zEndHdr;       /* Pointer to first byte after the header */
67537   u32 offset;        /* Offset into the data */
67538   u32 szField;       /* Number of bytes in the content of a field */
67539   int szHdr;         /* Size of the header size field at start of record */
67540   int avail;         /* Number of bytes of available data */
67541   u32 t;             /* A type code from the record header */
67542   Mem *pReg;         /* PseudoTable input register */
67543 #endif /* local variables moved into u.ao */
67544
67545
67546   u.ao.p1 = pOp->p1;
67547   u.ao.p2 = pOp->p2;
67548   u.ao.pC = 0;
67549   memset(&u.ao.sMem, 0, sizeof(u.ao.sMem));
67550   assert( u.ao.p1<p->nCursor );
67551   assert( pOp->p3>0 && pOp->p3<=p->nMem );
67552   u.ao.pDest = &aMem[pOp->p3];
67553   memAboutToChange(p, u.ao.pDest);
67554   u.ao.zRec = 0;
67555
67556   /* This block sets the variable u.ao.payloadSize to be the total number of
67557   ** bytes in the record.
67558   **
67559   ** u.ao.zRec is set to be the complete text of the record if it is available.
67560   ** The complete record text is always available for pseudo-tables
67561   ** If the record is stored in a cursor, the complete record text
67562   ** might be available in the  u.ao.pC->aRow cache.  Or it might not be.
67563   ** If the data is unavailable,  u.ao.zRec is set to NULL.
67564   **
67565   ** We also compute the number of columns in the record.  For cursors,
67566   ** the number of columns is stored in the VdbeCursor.nField element.
67567   */
67568   u.ao.pC = p->apCsr[u.ao.p1];
67569   assert( u.ao.pC!=0 );
67570 #ifndef SQLITE_OMIT_VIRTUALTABLE
67571   assert( u.ao.pC->pVtabCursor==0 );
67572 #endif
67573   u.ao.pCrsr = u.ao.pC->pCursor;
67574   if( u.ao.pCrsr!=0 ){
67575     /* The record is stored in a B-Tree */
67576     rc = sqlite3VdbeCursorMoveto(u.ao.pC);
67577     if( rc ) goto abort_due_to_error;
67578     if( u.ao.pC->nullRow ){
67579       u.ao.payloadSize = 0;
67580     }else if( u.ao.pC->cacheStatus==p->cacheCtr ){
67581       u.ao.payloadSize = u.ao.pC->payloadSize;
67582       u.ao.zRec = (char*)u.ao.pC->aRow;
67583     }else if( u.ao.pC->isIndex ){
67584       assert( sqlite3BtreeCursorIsValid(u.ao.pCrsr) );
67585       VVA_ONLY(rc =) sqlite3BtreeKeySize(u.ao.pCrsr, &u.ao.payloadSize64);
67586       assert( rc==SQLITE_OK );   /* True because of CursorMoveto() call above */
67587       /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
67588       ** payload size, so it is impossible for u.ao.payloadSize64 to be
67589       ** larger than 32 bits. */
67590       assert( (u.ao.payloadSize64 & SQLITE_MAX_U32)==(u64)u.ao.payloadSize64 );
67591       u.ao.payloadSize = (u32)u.ao.payloadSize64;
67592     }else{
67593       assert( sqlite3BtreeCursorIsValid(u.ao.pCrsr) );
67594       VVA_ONLY(rc =) sqlite3BtreeDataSize(u.ao.pCrsr, &u.ao.payloadSize);
67595       assert( rc==SQLITE_OK );   /* DataSize() cannot fail */
67596     }
67597   }else if( ALWAYS(u.ao.pC->pseudoTableReg>0) ){
67598     u.ao.pReg = &aMem[u.ao.pC->pseudoTableReg];
67599     if( u.ao.pC->multiPseudo ){
67600       sqlite3VdbeMemShallowCopy(u.ao.pDest, u.ao.pReg+u.ao.p2, MEM_Ephem);
67601       Deephemeralize(u.ao.pDest);
67602       goto op_column_out;
67603     }
67604     assert( u.ao.pReg->flags & MEM_Blob );
67605     assert( memIsValid(u.ao.pReg) );
67606     u.ao.payloadSize = u.ao.pReg->n;
67607     u.ao.zRec = u.ao.pReg->z;
67608     u.ao.pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr;
67609     assert( u.ao.payloadSize==0 || u.ao.zRec!=0 );
67610   }else{
67611     /* Consider the row to be NULL */
67612     u.ao.payloadSize = 0;
67613   }
67614
67615   /* If u.ao.payloadSize is 0, then just store a NULL.  This can happen because of
67616   ** nullRow or because of a corrupt database. */
67617   if( u.ao.payloadSize==0 ){
67618     MemSetTypeFlag(u.ao.pDest, MEM_Null);
67619     goto op_column_out;
67620   }
67621   assert( db->aLimit[SQLITE_LIMIT_LENGTH]>=0 );
67622   if( u.ao.payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
67623     goto too_big;
67624   }
67625
67626   u.ao.nField = u.ao.pC->nField;
67627   assert( u.ao.p2<u.ao.nField );
67628
67629   /* Read and parse the table header.  Store the results of the parse
67630   ** into the record header cache fields of the cursor.
67631   */
67632   u.ao.aType = u.ao.pC->aType;
67633   if( u.ao.pC->cacheStatus==p->cacheCtr ){
67634     u.ao.aOffset = u.ao.pC->aOffset;
67635   }else{
67636     assert(u.ao.aType);
67637     u.ao.avail = 0;
67638     u.ao.pC->aOffset = u.ao.aOffset = &u.ao.aType[u.ao.nField];
67639     u.ao.pC->payloadSize = u.ao.payloadSize;
67640     u.ao.pC->cacheStatus = p->cacheCtr;
67641
67642     /* Figure out how many bytes are in the header */
67643     if( u.ao.zRec ){
67644       u.ao.zData = u.ao.zRec;
67645     }else{
67646       if( u.ao.pC->isIndex ){
67647         u.ao.zData = (char*)sqlite3BtreeKeyFetch(u.ao.pCrsr, &u.ao.avail);
67648       }else{
67649         u.ao.zData = (char*)sqlite3BtreeDataFetch(u.ao.pCrsr, &u.ao.avail);
67650       }
67651       /* If KeyFetch()/DataFetch() managed to get the entire payload,
67652       ** save the payload in the u.ao.pC->aRow cache.  That will save us from
67653       ** having to make additional calls to fetch the content portion of
67654       ** the record.
67655       */
67656       assert( u.ao.avail>=0 );
67657       if( u.ao.payloadSize <= (u32)u.ao.avail ){
67658         u.ao.zRec = u.ao.zData;
67659         u.ao.pC->aRow = (u8*)u.ao.zData;
67660       }else{
67661         u.ao.pC->aRow = 0;
67662       }
67663     }
67664     /* The following assert is true in all cases except when
67665     ** the database file has been corrupted externally.
67666     **    assert( u.ao.zRec!=0 || u.ao.avail>=u.ao.payloadSize || u.ao.avail>=9 ); */
67667     u.ao.szHdr = getVarint32((u8*)u.ao.zData, u.ao.offset);
67668
67669     /* Make sure a corrupt database has not given us an oversize header.
67670     ** Do this now to avoid an oversize memory allocation.
67671     **
67672     ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
67673     ** types use so much data space that there can only be 4096 and 32 of
67674     ** them, respectively.  So the maximum header length results from a
67675     ** 3-byte type for each of the maximum of 32768 columns plus three
67676     ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
67677     */
67678     if( u.ao.offset > 98307 ){
67679       rc = SQLITE_CORRUPT_BKPT;
67680       goto op_column_out;
67681     }
67682
67683     /* Compute in u.ao.len the number of bytes of data we need to read in order
67684     ** to get u.ao.nField type values.  u.ao.offset is an upper bound on this.  But
67685     ** u.ao.nField might be significantly less than the true number of columns
67686     ** in the table, and in that case, 5*u.ao.nField+3 might be smaller than u.ao.offset.
67687     ** We want to minimize u.ao.len in order to limit the size of the memory
67688     ** allocation, especially if a corrupt database file has caused u.ao.offset
67689     ** to be oversized. Offset is limited to 98307 above.  But 98307 might
67690     ** still exceed Robson memory allocation limits on some configurations.
67691     ** On systems that cannot tolerate large memory allocations, u.ao.nField*5+3
67692     ** will likely be much smaller since u.ao.nField will likely be less than
67693     ** 20 or so.  This insures that Robson memory allocation limits are
67694     ** not exceeded even for corrupt database files.
67695     */
67696     u.ao.len = u.ao.nField*5 + 3;
67697     if( u.ao.len > (int)u.ao.offset ) u.ao.len = (int)u.ao.offset;
67698
67699     /* The KeyFetch() or DataFetch() above are fast and will get the entire
67700     ** record header in most cases.  But they will fail to get the complete
67701     ** record header if the record header does not fit on a single page
67702     ** in the B-Tree.  When that happens, use sqlite3VdbeMemFromBtree() to
67703     ** acquire the complete header text.
67704     */
67705     if( !u.ao.zRec && u.ao.avail<u.ao.len ){
67706       u.ao.sMem.flags = 0;
67707       u.ao.sMem.db = 0;
67708       rc = sqlite3VdbeMemFromBtree(u.ao.pCrsr, 0, u.ao.len, u.ao.pC->isIndex, &u.ao.sMem);
67709       if( rc!=SQLITE_OK ){
67710         goto op_column_out;
67711       }
67712       u.ao.zData = u.ao.sMem.z;
67713     }
67714     u.ao.zEndHdr = (u8 *)&u.ao.zData[u.ao.len];
67715     u.ao.zIdx = (u8 *)&u.ao.zData[u.ao.szHdr];
67716
67717     /* Scan the header and use it to fill in the u.ao.aType[] and u.ao.aOffset[]
67718     ** arrays.  u.ao.aType[u.ao.i] will contain the type integer for the u.ao.i-th
67719     ** column and u.ao.aOffset[u.ao.i] will contain the u.ao.offset from the beginning
67720     ** of the record to the start of the data for the u.ao.i-th column
67721     */
67722     for(u.ao.i=0; u.ao.i<u.ao.nField; u.ao.i++){
67723       if( u.ao.zIdx<u.ao.zEndHdr ){
67724         u.ao.aOffset[u.ao.i] = u.ao.offset;
67725         if( u.ao.zIdx[0]<0x80 ){
67726           u.ao.t = u.ao.zIdx[0];
67727           u.ao.zIdx++;
67728         }else{
67729           u.ao.zIdx += sqlite3GetVarint32(u.ao.zIdx, &u.ao.t);
67730         }
67731         u.ao.aType[u.ao.i] = u.ao.t;
67732         u.ao.szField = sqlite3VdbeSerialTypeLen(u.ao.t);
67733         u.ao.offset += u.ao.szField;
67734         if( u.ao.offset<u.ao.szField ){  /* True if u.ao.offset overflows */
67735           u.ao.zIdx = &u.ao.zEndHdr[1];  /* Forces SQLITE_CORRUPT return below */
67736           break;
67737         }
67738       }else{
67739         /* If u.ao.i is less that u.ao.nField, then there are fewer fields in this
67740         ** record than SetNumColumns indicated there are columns in the
67741         ** table. Set the u.ao.offset for any extra columns not present in
67742         ** the record to 0. This tells code below to store the default value
67743         ** for the column instead of deserializing a value from the record.
67744         */
67745         u.ao.aOffset[u.ao.i] = 0;
67746       }
67747     }
67748     sqlite3VdbeMemRelease(&u.ao.sMem);
67749     u.ao.sMem.flags = MEM_Null;
67750
67751     /* If we have read more header data than was contained in the header,
67752     ** or if the end of the last field appears to be past the end of the
67753     ** record, or if the end of the last field appears to be before the end
67754     ** of the record (when all fields present), then we must be dealing
67755     ** with a corrupt database.
67756     */
67757     if( (u.ao.zIdx > u.ao.zEndHdr) || (u.ao.offset > u.ao.payloadSize)
67758          || (u.ao.zIdx==u.ao.zEndHdr && u.ao.offset!=u.ao.payloadSize) ){
67759       rc = SQLITE_CORRUPT_BKPT;
67760       goto op_column_out;
67761     }
67762   }
67763
67764   /* Get the column information. If u.ao.aOffset[u.ao.p2] is non-zero, then
67765   ** deserialize the value from the record. If u.ao.aOffset[u.ao.p2] is zero,
67766   ** then there are not enough fields in the record to satisfy the
67767   ** request.  In this case, set the value NULL or to P4 if P4 is
67768   ** a pointer to a Mem object.
67769   */
67770   if( u.ao.aOffset[u.ao.p2] ){
67771     assert( rc==SQLITE_OK );
67772     if( u.ao.zRec ){
67773       /* This is the common case where the whole row fits on a single page */
67774       VdbeMemRelease(u.ao.pDest);
67775       sqlite3VdbeSerialGet((u8 *)&u.ao.zRec[u.ao.aOffset[u.ao.p2]], u.ao.aType[u.ao.p2], u.ao.pDest);
67776     }else{
67777       /* This branch happens only when the row overflows onto multiple pages */
67778       u.ao.t = u.ao.aType[u.ao.p2];
67779       if( (pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
67780        && ((u.ao.t>=12 && (u.ao.t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0)
67781       ){
67782         /* Content is irrelevant for the typeof() function and for
67783         ** the length(X) function if X is a blob.  So we might as well use
67784         ** bogus content rather than reading content from disk.  NULL works
67785         ** for text and blob and whatever is in the u.ao.payloadSize64 variable
67786         ** will work for everything else. */
67787         u.ao.zData = u.ao.t<12 ? (char*)&u.ao.payloadSize64 : 0;
67788       }else{
67789         u.ao.len = sqlite3VdbeSerialTypeLen(u.ao.t);
67790         sqlite3VdbeMemMove(&u.ao.sMem, u.ao.pDest);
67791         rc = sqlite3VdbeMemFromBtree(u.ao.pCrsr, u.ao.aOffset[u.ao.p2], u.ao.len,  u.ao.pC->isIndex,
67792                                      &u.ao.sMem);
67793         if( rc!=SQLITE_OK ){
67794           goto op_column_out;
67795         }
67796         u.ao.zData = u.ao.sMem.z;
67797       }
67798       sqlite3VdbeSerialGet((u8*)u.ao.zData, u.ao.t, u.ao.pDest);
67799     }
67800     u.ao.pDest->enc = encoding;
67801   }else{
67802     if( pOp->p4type==P4_MEM ){
67803       sqlite3VdbeMemShallowCopy(u.ao.pDest, pOp->p4.pMem, MEM_Static);
67804     }else{
67805       MemSetTypeFlag(u.ao.pDest, MEM_Null);
67806     }
67807   }
67808
67809   /* If we dynamically allocated space to hold the data (in the
67810   ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
67811   ** dynamically allocated space over to the u.ao.pDest structure.
67812   ** This prevents a memory copy.
67813   */
67814   if( u.ao.sMem.zMalloc ){
67815     assert( u.ao.sMem.z==u.ao.sMem.zMalloc );
67816     assert( !(u.ao.pDest->flags & MEM_Dyn) );
67817     assert( !(u.ao.pDest->flags & (MEM_Blob|MEM_Str)) || u.ao.pDest->z==u.ao.sMem.z );
67818     u.ao.pDest->flags &= ~(MEM_Ephem|MEM_Static);
67819     u.ao.pDest->flags |= MEM_Term;
67820     u.ao.pDest->z = u.ao.sMem.z;
67821     u.ao.pDest->zMalloc = u.ao.sMem.zMalloc;
67822   }
67823
67824   rc = sqlite3VdbeMemMakeWriteable(u.ao.pDest);
67825
67826 op_column_out:
67827   UPDATE_MAX_BLOBSIZE(u.ao.pDest);
67828   REGISTER_TRACE(pOp->p3, u.ao.pDest);
67829   break;
67830 }
67831
67832 /* Opcode: Affinity P1 P2 * P4 *
67833 **
67834 ** Apply affinities to a range of P2 registers starting with P1.
67835 **
67836 ** P4 is a string that is P2 characters long. The nth character of the
67837 ** string indicates the column affinity that should be used for the nth
67838 ** memory cell in the range.
67839 */
67840 case OP_Affinity: {
67841 #if 0  /* local variables moved into u.ap */
67842   const char *zAffinity;   /* The affinity to be applied */
67843   char cAff;               /* A single character of affinity */
67844 #endif /* local variables moved into u.ap */
67845
67846   u.ap.zAffinity = pOp->p4.z;
67847   assert( u.ap.zAffinity!=0 );
67848   assert( u.ap.zAffinity[pOp->p2]==0 );
67849   pIn1 = &aMem[pOp->p1];
67850   while( (u.ap.cAff = *(u.ap.zAffinity++))!=0 ){
67851     assert( pIn1 <= &p->aMem[p->nMem] );
67852     assert( memIsValid(pIn1) );
67853     ExpandBlob(pIn1);
67854     applyAffinity(pIn1, u.ap.cAff, encoding);
67855     pIn1++;
67856   }
67857   break;
67858 }
67859
67860 /* Opcode: MakeRecord P1 P2 P3 P4 *
67861 **
67862 ** Convert P2 registers beginning with P1 into the [record format]
67863 ** use as a data record in a database table or as a key
67864 ** in an index.  The OP_Column opcode can decode the record later.
67865 **
67866 ** P4 may be a string that is P2 characters long.  The nth character of the
67867 ** string indicates the column affinity that should be used for the nth
67868 ** field of the index key.
67869 **
67870 ** The mapping from character to affinity is given by the SQLITE_AFF_
67871 ** macros defined in sqliteInt.h.
67872 **
67873 ** If P4 is NULL then all index fields have the affinity NONE.
67874 */
67875 case OP_MakeRecord: {
67876 #if 0  /* local variables moved into u.aq */
67877   u8 *zNewRecord;        /* A buffer to hold the data for the new record */
67878   Mem *pRec;             /* The new record */
67879   u64 nData;             /* Number of bytes of data space */
67880   int nHdr;              /* Number of bytes of header space */
67881   i64 nByte;             /* Data space required for this record */
67882   int nZero;             /* Number of zero bytes at the end of the record */
67883   int nVarint;           /* Number of bytes in a varint */
67884   u32 serial_type;       /* Type field */
67885   Mem *pData0;           /* First field to be combined into the record */
67886   Mem *pLast;            /* Last field of the record */
67887   int nField;            /* Number of fields in the record */
67888   char *zAffinity;       /* The affinity string for the record */
67889   int file_format;       /* File format to use for encoding */
67890   int i;                 /* Space used in zNewRecord[] */
67891   int len;               /* Length of a field */
67892 #endif /* local variables moved into u.aq */
67893
67894   /* Assuming the record contains N fields, the record format looks
67895   ** like this:
67896   **
67897   ** ------------------------------------------------------------------------
67898   ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
67899   ** ------------------------------------------------------------------------
67900   **
67901   ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
67902   ** and so froth.
67903   **
67904   ** Each type field is a varint representing the serial type of the
67905   ** corresponding data element (see sqlite3VdbeSerialType()). The
67906   ** hdr-size field is also a varint which is the offset from the beginning
67907   ** of the record to data0.
67908   */
67909   u.aq.nData = 0;         /* Number of bytes of data space */
67910   u.aq.nHdr = 0;          /* Number of bytes of header space */
67911   u.aq.nZero = 0;         /* Number of zero bytes at the end of the record */
67912   u.aq.nField = pOp->p1;
67913   u.aq.zAffinity = pOp->p4.z;
67914   assert( u.aq.nField>0 && pOp->p2>0 && pOp->p2+u.aq.nField<=p->nMem+1 );
67915   u.aq.pData0 = &aMem[u.aq.nField];
67916   u.aq.nField = pOp->p2;
67917   u.aq.pLast = &u.aq.pData0[u.aq.nField-1];
67918   u.aq.file_format = p->minWriteFileFormat;
67919
67920   /* Identify the output register */
67921   assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
67922   pOut = &aMem[pOp->p3];
67923   memAboutToChange(p, pOut);
67924
67925   /* Loop through the elements that will make up the record to figure
67926   ** out how much space is required for the new record.
67927   */
67928   for(u.aq.pRec=u.aq.pData0; u.aq.pRec<=u.aq.pLast; u.aq.pRec++){
67929     assert( memIsValid(u.aq.pRec) );
67930     if( u.aq.zAffinity ){
67931       applyAffinity(u.aq.pRec, u.aq.zAffinity[u.aq.pRec-u.aq.pData0], encoding);
67932     }
67933     if( u.aq.pRec->flags&MEM_Zero && u.aq.pRec->n>0 ){
67934       sqlite3VdbeMemExpandBlob(u.aq.pRec);
67935     }
67936     u.aq.serial_type = sqlite3VdbeSerialType(u.aq.pRec, u.aq.file_format);
67937     u.aq.len = sqlite3VdbeSerialTypeLen(u.aq.serial_type);
67938     u.aq.nData += u.aq.len;
67939     u.aq.nHdr += sqlite3VarintLen(u.aq.serial_type);
67940     if( u.aq.pRec->flags & MEM_Zero ){
67941       /* Only pure zero-filled BLOBs can be input to this Opcode.
67942       ** We do not allow blobs with a prefix and a zero-filled tail. */
67943       u.aq.nZero += u.aq.pRec->u.nZero;
67944     }else if( u.aq.len ){
67945       u.aq.nZero = 0;
67946     }
67947   }
67948
67949   /* Add the initial header varint and total the size */
67950   u.aq.nHdr += u.aq.nVarint = sqlite3VarintLen(u.aq.nHdr);
67951   if( u.aq.nVarint<sqlite3VarintLen(u.aq.nHdr) ){
67952     u.aq.nHdr++;
67953   }
67954   u.aq.nByte = u.aq.nHdr+u.aq.nData-u.aq.nZero;
67955   if( u.aq.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
67956     goto too_big;
67957   }
67958
67959   /* Make sure the output register has a buffer large enough to store
67960   ** the new record. The output register (pOp->p3) is not allowed to
67961   ** be one of the input registers (because the following call to
67962   ** sqlite3VdbeMemGrow() could clobber the value before it is used).
67963   */
67964   if( sqlite3VdbeMemGrow(pOut, (int)u.aq.nByte, 0) ){
67965     goto no_mem;
67966   }
67967   u.aq.zNewRecord = (u8 *)pOut->z;
67968
67969   /* Write the record */
67970   u.aq.i = putVarint32(u.aq.zNewRecord, u.aq.nHdr);
67971   for(u.aq.pRec=u.aq.pData0; u.aq.pRec<=u.aq.pLast; u.aq.pRec++){
67972     u.aq.serial_type = sqlite3VdbeSerialType(u.aq.pRec, u.aq.file_format);
67973     u.aq.i += putVarint32(&u.aq.zNewRecord[u.aq.i], u.aq.serial_type);      /* serial type */
67974   }
67975   for(u.aq.pRec=u.aq.pData0; u.aq.pRec<=u.aq.pLast; u.aq.pRec++){  /* serial data */
67976     u.aq.i += sqlite3VdbeSerialPut(&u.aq.zNewRecord[u.aq.i], (int)(u.aq.nByte-u.aq.i), u.aq.pRec,u.aq.file_format);
67977   }
67978   assert( u.aq.i==u.aq.nByte );
67979
67980   assert( pOp->p3>0 && pOp->p3<=p->nMem );
67981   pOut->n = (int)u.aq.nByte;
67982   pOut->flags = MEM_Blob | MEM_Dyn;
67983   pOut->xDel = 0;
67984   if( u.aq.nZero ){
67985     pOut->u.nZero = u.aq.nZero;
67986     pOut->flags |= MEM_Zero;
67987   }
67988   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
67989   REGISTER_TRACE(pOp->p3, pOut);
67990   UPDATE_MAX_BLOBSIZE(pOut);
67991   break;
67992 }
67993
67994 /* Opcode: Count P1 P2 * * *
67995 **
67996 ** Store the number of entries (an integer value) in the table or index 
67997 ** opened by cursor P1 in register P2
67998 */
67999 #ifndef SQLITE_OMIT_BTREECOUNT
68000 case OP_Count: {         /* out2-prerelease */
68001 #if 0  /* local variables moved into u.ar */
68002   i64 nEntry;
68003   BtCursor *pCrsr;
68004 #endif /* local variables moved into u.ar */
68005
68006   u.ar.pCrsr = p->apCsr[pOp->p1]->pCursor;
68007   if( ALWAYS(u.ar.pCrsr) ){
68008     rc = sqlite3BtreeCount(u.ar.pCrsr, &u.ar.nEntry);
68009   }else{
68010     u.ar.nEntry = 0;
68011   }
68012   pOut->u.i = u.ar.nEntry;
68013   break;
68014 }
68015 #endif
68016
68017 /* Opcode: Savepoint P1 * * P4 *
68018 **
68019 ** Open, release or rollback the savepoint named by parameter P4, depending
68020 ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
68021 ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
68022 */
68023 case OP_Savepoint: {
68024 #if 0  /* local variables moved into u.as */
68025   int p1;                         /* Value of P1 operand */
68026   char *zName;                    /* Name of savepoint */
68027   int nName;
68028   Savepoint *pNew;
68029   Savepoint *pSavepoint;
68030   Savepoint *pTmp;
68031   int iSavepoint;
68032   int ii;
68033 #endif /* local variables moved into u.as */
68034
68035   u.as.p1 = pOp->p1;
68036   u.as.zName = pOp->p4.z;
68037
68038   /* Assert that the u.as.p1 parameter is valid. Also that if there is no open
68039   ** transaction, then there cannot be any savepoints.
68040   */
68041   assert( db->pSavepoint==0 || db->autoCommit==0 );
68042   assert( u.as.p1==SAVEPOINT_BEGIN||u.as.p1==SAVEPOINT_RELEASE||u.as.p1==SAVEPOINT_ROLLBACK );
68043   assert( db->pSavepoint || db->isTransactionSavepoint==0 );
68044   assert( checkSavepointCount(db) );
68045
68046   if( u.as.p1==SAVEPOINT_BEGIN ){
68047     if( db->writeVdbeCnt>0 ){
68048       /* A new savepoint cannot be created if there are active write
68049       ** statements (i.e. open read/write incremental blob handles).
68050       */
68051       sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
68052         "SQL statements in progress");
68053       rc = SQLITE_BUSY;
68054     }else{
68055       u.as.nName = sqlite3Strlen30(u.as.zName);
68056
68057 #ifndef SQLITE_OMIT_VIRTUALTABLE
68058       /* This call is Ok even if this savepoint is actually a transaction
68059       ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
68060       ** If this is a transaction savepoint being opened, it is guaranteed
68061       ** that the db->aVTrans[] array is empty.  */
68062       assert( db->autoCommit==0 || db->nVTrans==0 );
68063       rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
68064                                 db->nStatement+db->nSavepoint);
68065       if( rc!=SQLITE_OK ) goto abort_due_to_error;
68066 #endif
68067
68068       /* Create a new savepoint structure. */
68069       u.as.pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+u.as.nName+1);
68070       if( u.as.pNew ){
68071         u.as.pNew->zName = (char *)&u.as.pNew[1];
68072         memcpy(u.as.pNew->zName, u.as.zName, u.as.nName+1);
68073
68074         /* If there is no open transaction, then mark this as a special
68075         ** "transaction savepoint". */
68076         if( db->autoCommit ){
68077           db->autoCommit = 0;
68078           db->isTransactionSavepoint = 1;
68079         }else{
68080           db->nSavepoint++;
68081         }
68082
68083         /* Link the new savepoint into the database handle's list. */
68084         u.as.pNew->pNext = db->pSavepoint;
68085         db->pSavepoint = u.as.pNew;
68086         u.as.pNew->nDeferredCons = db->nDeferredCons;
68087       }
68088     }
68089   }else{
68090     u.as.iSavepoint = 0;
68091
68092     /* Find the named savepoint. If there is no such savepoint, then an
68093     ** an error is returned to the user.  */
68094     for(
68095       u.as.pSavepoint = db->pSavepoint;
68096       u.as.pSavepoint && sqlite3StrICmp(u.as.pSavepoint->zName, u.as.zName);
68097       u.as.pSavepoint = u.as.pSavepoint->pNext
68098     ){
68099       u.as.iSavepoint++;
68100     }
68101     if( !u.as.pSavepoint ){
68102       sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", u.as.zName);
68103       rc = SQLITE_ERROR;
68104     }else if( db->writeVdbeCnt>0 && u.as.p1==SAVEPOINT_RELEASE ){
68105       /* It is not possible to release (commit) a savepoint if there are
68106       ** active write statements.
68107       */
68108       sqlite3SetString(&p->zErrMsg, db,
68109         "cannot release savepoint - SQL statements in progress"
68110       );
68111       rc = SQLITE_BUSY;
68112     }else{
68113
68114       /* Determine whether or not this is a transaction savepoint. If so,
68115       ** and this is a RELEASE command, then the current transaction
68116       ** is committed.
68117       */
68118       int isTransaction = u.as.pSavepoint->pNext==0 && db->isTransactionSavepoint;
68119       if( isTransaction && u.as.p1==SAVEPOINT_RELEASE ){
68120         if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
68121           goto vdbe_return;
68122         }
68123         db->autoCommit = 1;
68124         if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
68125           p->pc = pc;
68126           db->autoCommit = 0;
68127           p->rc = rc = SQLITE_BUSY;
68128           goto vdbe_return;
68129         }
68130         db->isTransactionSavepoint = 0;
68131         rc = p->rc;
68132       }else{
68133         u.as.iSavepoint = db->nSavepoint - u.as.iSavepoint - 1;
68134         if( u.as.p1==SAVEPOINT_ROLLBACK ){
68135           for(u.as.ii=0; u.as.ii<db->nDb; u.as.ii++){
68136             sqlite3BtreeTripAllCursors(db->aDb[u.as.ii].pBt, SQLITE_ABORT);
68137           }
68138         }
68139         for(u.as.ii=0; u.as.ii<db->nDb; u.as.ii++){
68140           rc = sqlite3BtreeSavepoint(db->aDb[u.as.ii].pBt, u.as.p1, u.as.iSavepoint);
68141           if( rc!=SQLITE_OK ){
68142             goto abort_due_to_error;
68143           }
68144         }
68145         if( u.as.p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
68146           sqlite3ExpirePreparedStatements(db);
68147           sqlite3ResetAllSchemasOfConnection(db);
68148           db->flags = (db->flags | SQLITE_InternChanges);
68149         }
68150       }
68151
68152       /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
68153       ** savepoints nested inside of the savepoint being operated on. */
68154       while( db->pSavepoint!=u.as.pSavepoint ){
68155         u.as.pTmp = db->pSavepoint;
68156         db->pSavepoint = u.as.pTmp->pNext;
68157         sqlite3DbFree(db, u.as.pTmp);
68158         db->nSavepoint--;
68159       }
68160
68161       /* If it is a RELEASE, then destroy the savepoint being operated on
68162       ** too. If it is a ROLLBACK TO, then set the number of deferred
68163       ** constraint violations present in the database to the value stored
68164       ** when the savepoint was created.  */
68165       if( u.as.p1==SAVEPOINT_RELEASE ){
68166         assert( u.as.pSavepoint==db->pSavepoint );
68167         db->pSavepoint = u.as.pSavepoint->pNext;
68168         sqlite3DbFree(db, u.as.pSavepoint);
68169         if( !isTransaction ){
68170           db->nSavepoint--;
68171         }
68172       }else{
68173         db->nDeferredCons = u.as.pSavepoint->nDeferredCons;
68174       }
68175
68176       if( !isTransaction ){
68177         rc = sqlite3VtabSavepoint(db, u.as.p1, u.as.iSavepoint);
68178         if( rc!=SQLITE_OK ) goto abort_due_to_error;
68179       }
68180     }
68181   }
68182
68183   break;
68184 }
68185
68186 /* Opcode: AutoCommit P1 P2 * * *
68187 **
68188 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
68189 ** back any currently active btree transactions. If there are any active
68190 ** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
68191 ** there are active writing VMs or active VMs that use shared cache.
68192 **
68193 ** This instruction causes the VM to halt.
68194 */
68195 case OP_AutoCommit: {
68196 #if 0  /* local variables moved into u.at */
68197   int desiredAutoCommit;
68198   int iRollback;
68199   int turnOnAC;
68200 #endif /* local variables moved into u.at */
68201
68202   u.at.desiredAutoCommit = pOp->p1;
68203   u.at.iRollback = pOp->p2;
68204   u.at.turnOnAC = u.at.desiredAutoCommit && !db->autoCommit;
68205   assert( u.at.desiredAutoCommit==1 || u.at.desiredAutoCommit==0 );
68206   assert( u.at.desiredAutoCommit==1 || u.at.iRollback==0 );
68207   assert( db->activeVdbeCnt>0 );  /* At least this one VM is active */
68208
68209 #if 0
68210   if( u.at.turnOnAC && u.at.iRollback && db->activeVdbeCnt>1 ){
68211     /* If this instruction implements a ROLLBACK and other VMs are
68212     ** still running, and a transaction is active, return an error indicating
68213     ** that the other VMs must complete first.
68214     */
68215     sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
68216         "SQL statements in progress");
68217     rc = SQLITE_BUSY;
68218   }else
68219 #endif
68220   if( u.at.turnOnAC && !u.at.iRollback && db->writeVdbeCnt>0 ){
68221     /* If this instruction implements a COMMIT and other VMs are writing
68222     ** return an error indicating that the other VMs must complete first.
68223     */
68224     sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
68225         "SQL statements in progress");
68226     rc = SQLITE_BUSY;
68227   }else if( u.at.desiredAutoCommit!=db->autoCommit ){
68228     if( u.at.iRollback ){
68229       assert( u.at.desiredAutoCommit==1 );
68230       sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
68231       db->autoCommit = 1;
68232     }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
68233       goto vdbe_return;
68234     }else{
68235       db->autoCommit = (u8)u.at.desiredAutoCommit;
68236       if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
68237         p->pc = pc;
68238         db->autoCommit = (u8)(1-u.at.desiredAutoCommit);
68239         p->rc = rc = SQLITE_BUSY;
68240         goto vdbe_return;
68241       }
68242     }
68243     assert( db->nStatement==0 );
68244     sqlite3CloseSavepoints(db);
68245     if( p->rc==SQLITE_OK ){
68246       rc = SQLITE_DONE;
68247     }else{
68248       rc = SQLITE_ERROR;
68249     }
68250     goto vdbe_return;
68251   }else{
68252     sqlite3SetString(&p->zErrMsg, db,
68253         (!u.at.desiredAutoCommit)?"cannot start a transaction within a transaction":(
68254         (u.at.iRollback)?"cannot rollback - no transaction is active":
68255                    "cannot commit - no transaction is active"));
68256
68257     rc = SQLITE_ERROR;
68258   }
68259   break;
68260 }
68261
68262 /* Opcode: Transaction P1 P2 * * *
68263 **
68264 ** Begin a transaction.  The transaction ends when a Commit or Rollback
68265 ** opcode is encountered.  Depending on the ON CONFLICT setting, the
68266 ** transaction might also be rolled back if an error is encountered.
68267 **
68268 ** P1 is the index of the database file on which the transaction is
68269 ** started.  Index 0 is the main database file and index 1 is the
68270 ** file used for temporary tables.  Indices of 2 or more are used for
68271 ** attached databases.
68272 **
68273 ** If P2 is non-zero, then a write-transaction is started.  A RESERVED lock is
68274 ** obtained on the database file when a write-transaction is started.  No
68275 ** other process can start another write transaction while this transaction is
68276 ** underway.  Starting a write transaction also creates a rollback journal. A
68277 ** write transaction must be started before any changes can be made to the
68278 ** database.  If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
68279 ** on the file.
68280 **
68281 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
68282 ** true (this flag is set if the Vdbe may modify more than one row and may
68283 ** throw an ABORT exception), a statement transaction may also be opened.
68284 ** More specifically, a statement transaction is opened iff the database
68285 ** connection is currently not in autocommit mode, or if there are other
68286 ** active statements. A statement transaction allows the changes made by this
68287 ** VDBE to be rolled back after an error without having to roll back the
68288 ** entire transaction. If no error is encountered, the statement transaction
68289 ** will automatically commit when the VDBE halts.
68290 **
68291 ** If P2 is zero, then a read-lock is obtained on the database file.
68292 */
68293 case OP_Transaction: {
68294 #if 0  /* local variables moved into u.au */
68295   Btree *pBt;
68296 #endif /* local variables moved into u.au */
68297
68298   assert( pOp->p1>=0 && pOp->p1<db->nDb );
68299   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
68300   u.au.pBt = db->aDb[pOp->p1].pBt;
68301
68302   if( u.au.pBt ){
68303     rc = sqlite3BtreeBeginTrans(u.au.pBt, pOp->p2);
68304     if( rc==SQLITE_BUSY ){
68305       p->pc = pc;
68306       p->rc = rc = SQLITE_BUSY;
68307       goto vdbe_return;
68308     }
68309     if( rc!=SQLITE_OK ){
68310       goto abort_due_to_error;
68311     }
68312
68313     if( pOp->p2 && p->usesStmtJournal
68314      && (db->autoCommit==0 || db->activeVdbeCnt>1)
68315     ){
68316       assert( sqlite3BtreeIsInTrans(u.au.pBt) );
68317       if( p->iStatement==0 ){
68318         assert( db->nStatement>=0 && db->nSavepoint>=0 );
68319         db->nStatement++;
68320         p->iStatement = db->nSavepoint + db->nStatement;
68321       }
68322
68323       rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
68324       if( rc==SQLITE_OK ){
68325         rc = sqlite3BtreeBeginStmt(u.au.pBt, p->iStatement);
68326       }
68327
68328       /* Store the current value of the database handles deferred constraint
68329       ** counter. If the statement transaction needs to be rolled back,
68330       ** the value of this counter needs to be restored too.  */
68331       p->nStmtDefCons = db->nDeferredCons;
68332     }
68333   }
68334   break;
68335 }
68336
68337 /* Opcode: ReadCookie P1 P2 P3 * *
68338 **
68339 ** Read cookie number P3 from database P1 and write it into register P2.
68340 ** P3==1 is the schema version.  P3==2 is the database format.
68341 ** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
68342 ** the main database file and P1==1 is the database file used to store
68343 ** temporary tables.
68344 **
68345 ** There must be a read-lock on the database (either a transaction
68346 ** must be started or there must be an open cursor) before
68347 ** executing this instruction.
68348 */
68349 case OP_ReadCookie: {               /* out2-prerelease */
68350 #if 0  /* local variables moved into u.av */
68351   int iMeta;
68352   int iDb;
68353   int iCookie;
68354 #endif /* local variables moved into u.av */
68355
68356   u.av.iDb = pOp->p1;
68357   u.av.iCookie = pOp->p3;
68358   assert( pOp->p3<SQLITE_N_BTREE_META );
68359   assert( u.av.iDb>=0 && u.av.iDb<db->nDb );
68360   assert( db->aDb[u.av.iDb].pBt!=0 );
68361   assert( (p->btreeMask & (((yDbMask)1)<<u.av.iDb))!=0 );
68362
68363   sqlite3BtreeGetMeta(db->aDb[u.av.iDb].pBt, u.av.iCookie, (u32 *)&u.av.iMeta);
68364   pOut->u.i = u.av.iMeta;
68365   break;
68366 }
68367
68368 /* Opcode: SetCookie P1 P2 P3 * *
68369 **
68370 ** Write the content of register P3 (interpreted as an integer)
68371 ** into cookie number P2 of database P1.  P2==1 is the schema version.  
68372 ** P2==2 is the database format. P2==3 is the recommended pager cache 
68373 ** size, and so forth.  P1==0 is the main database file and P1==1 is the 
68374 ** database file used to store temporary tables.
68375 **
68376 ** A transaction must be started before executing this opcode.
68377 */
68378 case OP_SetCookie: {       /* in3 */
68379 #if 0  /* local variables moved into u.aw */
68380   Db *pDb;
68381 #endif /* local variables moved into u.aw */
68382   assert( pOp->p2<SQLITE_N_BTREE_META );
68383   assert( pOp->p1>=0 && pOp->p1<db->nDb );
68384   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
68385   u.aw.pDb = &db->aDb[pOp->p1];
68386   assert( u.aw.pDb->pBt!=0 );
68387   assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
68388   pIn3 = &aMem[pOp->p3];
68389   sqlite3VdbeMemIntegerify(pIn3);
68390   /* See note about index shifting on OP_ReadCookie */
68391   rc = sqlite3BtreeUpdateMeta(u.aw.pDb->pBt, pOp->p2, (int)pIn3->u.i);
68392   if( pOp->p2==BTREE_SCHEMA_VERSION ){
68393     /* When the schema cookie changes, record the new cookie internally */
68394     u.aw.pDb->pSchema->schema_cookie = (int)pIn3->u.i;
68395     db->flags |= SQLITE_InternChanges;
68396   }else if( pOp->p2==BTREE_FILE_FORMAT ){
68397     /* Record changes in the file format */
68398     u.aw.pDb->pSchema->file_format = (u8)pIn3->u.i;
68399   }
68400   if( pOp->p1==1 ){
68401     /* Invalidate all prepared statements whenever the TEMP database
68402     ** schema is changed.  Ticket #1644 */
68403     sqlite3ExpirePreparedStatements(db);
68404     p->expired = 0;
68405   }
68406   break;
68407 }
68408
68409 /* Opcode: VerifyCookie P1 P2 P3 * *
68410 **
68411 ** Check the value of global database parameter number 0 (the
68412 ** schema version) and make sure it is equal to P2 and that the
68413 ** generation counter on the local schema parse equals P3.
68414 **
68415 ** P1 is the database number which is 0 for the main database file
68416 ** and 1 for the file holding temporary tables and some higher number
68417 ** for auxiliary databases.
68418 **
68419 ** The cookie changes its value whenever the database schema changes.
68420 ** This operation is used to detect when that the cookie has changed
68421 ** and that the current process needs to reread the schema.
68422 **
68423 ** Either a transaction needs to have been started or an OP_Open needs
68424 ** to be executed (to establish a read lock) before this opcode is
68425 ** invoked.
68426 */
68427 case OP_VerifyCookie: {
68428 #if 0  /* local variables moved into u.ax */
68429   int iMeta;
68430   int iGen;
68431   Btree *pBt;
68432 #endif /* local variables moved into u.ax */
68433
68434   assert( pOp->p1>=0 && pOp->p1<db->nDb );
68435   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
68436   assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
68437   u.ax.pBt = db->aDb[pOp->p1].pBt;
68438   if( u.ax.pBt ){
68439     sqlite3BtreeGetMeta(u.ax.pBt, BTREE_SCHEMA_VERSION, (u32 *)&u.ax.iMeta);
68440     u.ax.iGen = db->aDb[pOp->p1].pSchema->iGeneration;
68441   }else{
68442     u.ax.iGen = u.ax.iMeta = 0;
68443   }
68444   if( u.ax.iMeta!=pOp->p2 || u.ax.iGen!=pOp->p3 ){
68445     sqlite3DbFree(db, p->zErrMsg);
68446     p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
68447     /* If the schema-cookie from the database file matches the cookie
68448     ** stored with the in-memory representation of the schema, do
68449     ** not reload the schema from the database file.
68450     **
68451     ** If virtual-tables are in use, this is not just an optimization.
68452     ** Often, v-tables store their data in other SQLite tables, which
68453     ** are queried from within xNext() and other v-table methods using
68454     ** prepared queries. If such a query is out-of-date, we do not want to
68455     ** discard the database schema, as the user code implementing the
68456     ** v-table would have to be ready for the sqlite3_vtab structure itself
68457     ** to be invalidated whenever sqlite3_step() is called from within
68458     ** a v-table method.
68459     */
68460     if( db->aDb[pOp->p1].pSchema->schema_cookie!=u.ax.iMeta ){
68461       sqlite3ResetOneSchema(db, pOp->p1);
68462     }
68463
68464     p->expired = 1;
68465     rc = SQLITE_SCHEMA;
68466   }
68467   break;
68468 }
68469
68470 /* Opcode: OpenRead P1 P2 P3 P4 P5
68471 **
68472 ** Open a read-only cursor for the database table whose root page is
68473 ** P2 in a database file.  The database file is determined by P3. 
68474 ** P3==0 means the main database, P3==1 means the database used for 
68475 ** temporary tables, and P3>1 means used the corresponding attached
68476 ** database.  Give the new cursor an identifier of P1.  The P1
68477 ** values need not be contiguous but all P1 values should be small integers.
68478 ** It is an error for P1 to be negative.
68479 **
68480 ** If P5!=0 then use the content of register P2 as the root page, not
68481 ** the value of P2 itself.
68482 **
68483 ** There will be a read lock on the database whenever there is an
68484 ** open cursor.  If the database was unlocked prior to this instruction
68485 ** then a read lock is acquired as part of this instruction.  A read
68486 ** lock allows other processes to read the database but prohibits
68487 ** any other process from modifying the database.  The read lock is
68488 ** released when all cursors are closed.  If this instruction attempts
68489 ** to get a read lock but fails, the script terminates with an
68490 ** SQLITE_BUSY error code.
68491 **
68492 ** The P4 value may be either an integer (P4_INT32) or a pointer to
68493 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 
68494 ** structure, then said structure defines the content and collating 
68495 ** sequence of the index being opened. Otherwise, if P4 is an integer 
68496 ** value, it is set to the number of columns in the table.
68497 **
68498 ** See also OpenWrite.
68499 */
68500 /* Opcode: OpenWrite P1 P2 P3 P4 P5
68501 **
68502 ** Open a read/write cursor named P1 on the table or index whose root
68503 ** page is P2.  Or if P5!=0 use the content of register P2 to find the
68504 ** root page.
68505 **
68506 ** The P4 value may be either an integer (P4_INT32) or a pointer to
68507 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 
68508 ** structure, then said structure defines the content and collating 
68509 ** sequence of the index being opened. Otherwise, if P4 is an integer 
68510 ** value, it is set to the number of columns in the table, or to the
68511 ** largest index of any column of the table that is actually used.
68512 **
68513 ** This instruction works just like OpenRead except that it opens the cursor
68514 ** in read/write mode.  For a given table, there can be one or more read-only
68515 ** cursors or a single read/write cursor but not both.
68516 **
68517 ** See also OpenRead.
68518 */
68519 case OP_OpenRead:
68520 case OP_OpenWrite: {
68521 #if 0  /* local variables moved into u.ay */
68522   int nField;
68523   KeyInfo *pKeyInfo;
68524   int p2;
68525   int iDb;
68526   int wrFlag;
68527   Btree *pX;
68528   VdbeCursor *pCur;
68529   Db *pDb;
68530 #endif /* local variables moved into u.ay */
68531
68532   assert( (pOp->p5&(OPFLAG_P2ISREG|OPFLAG_BULKCSR))==pOp->p5 );
68533   assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 );
68534
68535   if( p->expired ){
68536     rc = SQLITE_ABORT;
68537     break;
68538   }
68539
68540   u.ay.nField = 0;
68541   u.ay.pKeyInfo = 0;
68542   u.ay.p2 = pOp->p2;
68543   u.ay.iDb = pOp->p3;
68544   assert( u.ay.iDb>=0 && u.ay.iDb<db->nDb );
68545   assert( (p->btreeMask & (((yDbMask)1)<<u.ay.iDb))!=0 );
68546   u.ay.pDb = &db->aDb[u.ay.iDb];
68547   u.ay.pX = u.ay.pDb->pBt;
68548   assert( u.ay.pX!=0 );
68549   if( pOp->opcode==OP_OpenWrite ){
68550     u.ay.wrFlag = 1;
68551     assert( sqlite3SchemaMutexHeld(db, u.ay.iDb, 0) );
68552     if( u.ay.pDb->pSchema->file_format < p->minWriteFileFormat ){
68553       p->minWriteFileFormat = u.ay.pDb->pSchema->file_format;
68554     }
68555   }else{
68556     u.ay.wrFlag = 0;
68557   }
68558   if( pOp->p5 & OPFLAG_P2ISREG ){
68559     assert( u.ay.p2>0 );
68560     assert( u.ay.p2<=p->nMem );
68561     pIn2 = &aMem[u.ay.p2];
68562     assert( memIsValid(pIn2) );
68563     assert( (pIn2->flags & MEM_Int)!=0 );
68564     sqlite3VdbeMemIntegerify(pIn2);
68565     u.ay.p2 = (int)pIn2->u.i;
68566     /* The u.ay.p2 value always comes from a prior OP_CreateTable opcode and
68567     ** that opcode will always set the u.ay.p2 value to 2 or more or else fail.
68568     ** If there were a failure, the prepared statement would have halted
68569     ** before reaching this instruction. */
68570     if( NEVER(u.ay.p2<2) ) {
68571       rc = SQLITE_CORRUPT_BKPT;
68572       goto abort_due_to_error;
68573     }
68574   }
68575   if( pOp->p4type==P4_KEYINFO ){
68576     u.ay.pKeyInfo = pOp->p4.pKeyInfo;
68577     u.ay.pKeyInfo->enc = ENC(p->db);
68578     u.ay.nField = u.ay.pKeyInfo->nField+1;
68579   }else if( pOp->p4type==P4_INT32 ){
68580     u.ay.nField = pOp->p4.i;
68581   }
68582   assert( pOp->p1>=0 );
68583   u.ay.pCur = allocateCursor(p, pOp->p1, u.ay.nField, u.ay.iDb, 1);
68584   if( u.ay.pCur==0 ) goto no_mem;
68585   u.ay.pCur->nullRow = 1;
68586   u.ay.pCur->isOrdered = 1;
68587   rc = sqlite3BtreeCursor(u.ay.pX, u.ay.p2, u.ay.wrFlag, u.ay.pKeyInfo, u.ay.pCur->pCursor);
68588   u.ay.pCur->pKeyInfo = u.ay.pKeyInfo;
68589   assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
68590   sqlite3BtreeCursorHints(u.ay.pCur->pCursor, (pOp->p5 & OPFLAG_BULKCSR));
68591
68592   /* Since it performs no memory allocation or IO, the only value that
68593   ** sqlite3BtreeCursor() may return is SQLITE_OK. */
68594   assert( rc==SQLITE_OK );
68595
68596   /* Set the VdbeCursor.isTable and isIndex variables. Previous versions of
68597   ** SQLite used to check if the root-page flags were sane at this point
68598   ** and report database corruption if they were not, but this check has
68599   ** since moved into the btree layer.  */
68600   u.ay.pCur->isTable = pOp->p4type!=P4_KEYINFO;
68601   u.ay.pCur->isIndex = !u.ay.pCur->isTable;
68602   break;
68603 }
68604
68605 /* Opcode: OpenEphemeral P1 P2 * P4 P5
68606 **
68607 ** Open a new cursor P1 to a transient table.
68608 ** The cursor is always opened read/write even if 
68609 ** the main database is read-only.  The ephemeral
68610 ** table is deleted automatically when the cursor is closed.
68611 **
68612 ** P2 is the number of columns in the ephemeral table.
68613 ** The cursor points to a BTree table if P4==0 and to a BTree index
68614 ** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
68615 ** that defines the format of keys in the index.
68616 **
68617 ** This opcode was once called OpenTemp.  But that created
68618 ** confusion because the term "temp table", might refer either
68619 ** to a TEMP table at the SQL level, or to a table opened by
68620 ** this opcode.  Then this opcode was call OpenVirtual.  But
68621 ** that created confusion with the whole virtual-table idea.
68622 **
68623 ** The P5 parameter can be a mask of the BTREE_* flags defined
68624 ** in btree.h.  These flags control aspects of the operation of
68625 ** the btree.  The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
68626 ** added automatically.
68627 */
68628 /* Opcode: OpenAutoindex P1 P2 * P4 *
68629 **
68630 ** This opcode works the same as OP_OpenEphemeral.  It has a
68631 ** different name to distinguish its use.  Tables created using
68632 ** by this opcode will be used for automatically created transient
68633 ** indices in joins.
68634 */
68635 case OP_OpenAutoindex: 
68636 case OP_OpenEphemeral: {
68637 #if 0  /* local variables moved into u.az */
68638   VdbeCursor *pCx;
68639 #endif /* local variables moved into u.az */
68640   static const int vfsFlags =
68641       SQLITE_OPEN_READWRITE |
68642       SQLITE_OPEN_CREATE |
68643       SQLITE_OPEN_EXCLUSIVE |
68644       SQLITE_OPEN_DELETEONCLOSE |
68645       SQLITE_OPEN_TRANSIENT_DB;
68646
68647   assert( pOp->p1>=0 );
68648   u.az.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
68649   if( u.az.pCx==0 ) goto no_mem;
68650   u.az.pCx->nullRow = 1;
68651   rc = sqlite3BtreeOpen(db->pVfs, 0, db, &u.az.pCx->pBt,
68652                         BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
68653   if( rc==SQLITE_OK ){
68654     rc = sqlite3BtreeBeginTrans(u.az.pCx->pBt, 1);
68655   }
68656   if( rc==SQLITE_OK ){
68657     /* If a transient index is required, create it by calling
68658     ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
68659     ** opening it. If a transient table is required, just use the
68660     ** automatically created table with root-page 1 (an BLOB_INTKEY table).
68661     */
68662     if( pOp->p4.pKeyInfo ){
68663       int pgno;
68664       assert( pOp->p4type==P4_KEYINFO );
68665       rc = sqlite3BtreeCreateTable(u.az.pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5);
68666       if( rc==SQLITE_OK ){
68667         assert( pgno==MASTER_ROOT+1 );
68668         rc = sqlite3BtreeCursor(u.az.pCx->pBt, pgno, 1,
68669                                 (KeyInfo*)pOp->p4.z, u.az.pCx->pCursor);
68670         u.az.pCx->pKeyInfo = pOp->p4.pKeyInfo;
68671         u.az.pCx->pKeyInfo->enc = ENC(p->db);
68672       }
68673       u.az.pCx->isTable = 0;
68674     }else{
68675       rc = sqlite3BtreeCursor(u.az.pCx->pBt, MASTER_ROOT, 1, 0, u.az.pCx->pCursor);
68676       u.az.pCx->isTable = 1;
68677     }
68678   }
68679   u.az.pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
68680   u.az.pCx->isIndex = !u.az.pCx->isTable;
68681   break;
68682 }
68683
68684 /* Opcode: SorterOpen P1 P2 * P4 *
68685 **
68686 ** This opcode works like OP_OpenEphemeral except that it opens
68687 ** a transient index that is specifically designed to sort large
68688 ** tables using an external merge-sort algorithm.
68689 */
68690 case OP_SorterOpen: {
68691 #if 0  /* local variables moved into u.ba */
68692   VdbeCursor *pCx;
68693 #endif /* local variables moved into u.ba */
68694
68695   u.ba.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
68696   if( u.ba.pCx==0 ) goto no_mem;
68697   u.ba.pCx->pKeyInfo = pOp->p4.pKeyInfo;
68698   u.ba.pCx->pKeyInfo->enc = ENC(p->db);
68699   u.ba.pCx->isSorter = 1;
68700   rc = sqlite3VdbeSorterInit(db, u.ba.pCx);
68701   break;
68702 }
68703
68704 /* Opcode: OpenPseudo P1 P2 P3 * P5
68705 **
68706 ** Open a new cursor that points to a fake table that contains a single
68707 ** row of data.  The content of that one row in the content of memory
68708 ** register P2 when P5==0.  In other words, cursor P1 becomes an alias for the 
68709 ** MEM_Blob content contained in register P2.  When P5==1, then the
68710 ** row is represented by P3 consecutive registers beginning with P2.
68711 **
68712 ** A pseudo-table created by this opcode is used to hold a single
68713 ** row output from the sorter so that the row can be decomposed into
68714 ** individual columns using the OP_Column opcode.  The OP_Column opcode
68715 ** is the only cursor opcode that works with a pseudo-table.
68716 **
68717 ** P3 is the number of fields in the records that will be stored by
68718 ** the pseudo-table.
68719 */
68720 case OP_OpenPseudo: {
68721 #if 0  /* local variables moved into u.bb */
68722   VdbeCursor *pCx;
68723 #endif /* local variables moved into u.bb */
68724
68725   assert( pOp->p1>=0 );
68726   u.bb.pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
68727   if( u.bb.pCx==0 ) goto no_mem;
68728   u.bb.pCx->nullRow = 1;
68729   u.bb.pCx->pseudoTableReg = pOp->p2;
68730   u.bb.pCx->isTable = 1;
68731   u.bb.pCx->isIndex = 0;
68732   u.bb.pCx->multiPseudo = pOp->p5;
68733   break;
68734 }
68735
68736 /* Opcode: Close P1 * * * *
68737 **
68738 ** Close a cursor previously opened as P1.  If P1 is not
68739 ** currently open, this instruction is a no-op.
68740 */
68741 case OP_Close: {
68742   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68743   sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
68744   p->apCsr[pOp->p1] = 0;
68745   break;
68746 }
68747
68748 /* Opcode: SeekGe P1 P2 P3 P4 *
68749 **
68750 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
68751 ** use the value in register P3 as the key.  If cursor P1 refers 
68752 ** to an SQL index, then P3 is the first in an array of P4 registers 
68753 ** that are used as an unpacked index key. 
68754 **
68755 ** Reposition cursor P1 so that  it points to the smallest entry that 
68756 ** is greater than or equal to the key value. If there are no records 
68757 ** greater than or equal to the key and P2 is not zero, then jump to P2.
68758 **
68759 ** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe
68760 */
68761 /* Opcode: SeekGt P1 P2 P3 P4 *
68762 **
68763 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
68764 ** use the value in register P3 as a key. If cursor P1 refers 
68765 ** to an SQL index, then P3 is the first in an array of P4 registers 
68766 ** that are used as an unpacked index key. 
68767 **
68768 ** Reposition cursor P1 so that  it points to the smallest entry that 
68769 ** is greater than the key value. If there are no records greater than 
68770 ** the key and P2 is not zero, then jump to P2.
68771 **
68772 ** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe
68773 */
68774 /* Opcode: SeekLt P1 P2 P3 P4 * 
68775 **
68776 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
68777 ** use the value in register P3 as a key. If cursor P1 refers 
68778 ** to an SQL index, then P3 is the first in an array of P4 registers 
68779 ** that are used as an unpacked index key. 
68780 **
68781 ** Reposition cursor P1 so that  it points to the largest entry that 
68782 ** is less than the key value. If there are no records less than 
68783 ** the key and P2 is not zero, then jump to P2.
68784 **
68785 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe
68786 */
68787 /* Opcode: SeekLe P1 P2 P3 P4 *
68788 **
68789 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
68790 ** use the value in register P3 as a key. If cursor P1 refers 
68791 ** to an SQL index, then P3 is the first in an array of P4 registers 
68792 ** that are used as an unpacked index key. 
68793 **
68794 ** Reposition cursor P1 so that it points to the largest entry that 
68795 ** is less than or equal to the key value. If there are no records 
68796 ** less than or equal to the key and P2 is not zero, then jump to P2.
68797 **
68798 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
68799 */
68800 case OP_SeekLt:         /* jump, in3 */
68801 case OP_SeekLe:         /* jump, in3 */
68802 case OP_SeekGe:         /* jump, in3 */
68803 case OP_SeekGt: {       /* jump, in3 */
68804 #if 0  /* local variables moved into u.bc */
68805   int res;
68806   int oc;
68807   VdbeCursor *pC;
68808   UnpackedRecord r;
68809   int nField;
68810   i64 iKey;      /* The rowid we are to seek to */
68811 #endif /* local variables moved into u.bc */
68812
68813   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68814   assert( pOp->p2!=0 );
68815   u.bc.pC = p->apCsr[pOp->p1];
68816   assert( u.bc.pC!=0 );
68817   assert( u.bc.pC->pseudoTableReg==0 );
68818   assert( OP_SeekLe == OP_SeekLt+1 );
68819   assert( OP_SeekGe == OP_SeekLt+2 );
68820   assert( OP_SeekGt == OP_SeekLt+3 );
68821   assert( u.bc.pC->isOrdered );
68822   if( ALWAYS(u.bc.pC->pCursor!=0) ){
68823     u.bc.oc = pOp->opcode;
68824     u.bc.pC->nullRow = 0;
68825     if( u.bc.pC->isTable ){
68826       /* The input value in P3 might be of any type: integer, real, string,
68827       ** blob, or NULL.  But it needs to be an integer before we can do
68828       ** the seek, so covert it. */
68829       pIn3 = &aMem[pOp->p3];
68830       applyNumericAffinity(pIn3);
68831       u.bc.iKey = sqlite3VdbeIntValue(pIn3);
68832       u.bc.pC->rowidIsValid = 0;
68833
68834       /* If the P3 value could not be converted into an integer without
68835       ** loss of information, then special processing is required... */
68836       if( (pIn3->flags & MEM_Int)==0 ){
68837         if( (pIn3->flags & MEM_Real)==0 ){
68838           /* If the P3 value cannot be converted into any kind of a number,
68839           ** then the seek is not possible, so jump to P2 */
68840           pc = pOp->p2 - 1;
68841           break;
68842         }
68843         /* If we reach this point, then the P3 value must be a floating
68844         ** point number. */
68845         assert( (pIn3->flags & MEM_Real)!=0 );
68846
68847         if( u.bc.iKey==SMALLEST_INT64 && (pIn3->r<(double)u.bc.iKey || pIn3->r>0) ){
68848           /* The P3 value is too large in magnitude to be expressed as an
68849           ** integer. */
68850           u.bc.res = 1;
68851           if( pIn3->r<0 ){
68852             if( u.bc.oc>=OP_SeekGe ){  assert( u.bc.oc==OP_SeekGe || u.bc.oc==OP_SeekGt );
68853               rc = sqlite3BtreeFirst(u.bc.pC->pCursor, &u.bc.res);
68854               if( rc!=SQLITE_OK ) goto abort_due_to_error;
68855             }
68856           }else{
68857             if( u.bc.oc<=OP_SeekLe ){  assert( u.bc.oc==OP_SeekLt || u.bc.oc==OP_SeekLe );
68858               rc = sqlite3BtreeLast(u.bc.pC->pCursor, &u.bc.res);
68859               if( rc!=SQLITE_OK ) goto abort_due_to_error;
68860             }
68861           }
68862           if( u.bc.res ){
68863             pc = pOp->p2 - 1;
68864           }
68865           break;
68866         }else if( u.bc.oc==OP_SeekLt || u.bc.oc==OP_SeekGe ){
68867           /* Use the ceiling() function to convert real->int */
68868           if( pIn3->r > (double)u.bc.iKey ) u.bc.iKey++;
68869         }else{
68870           /* Use the floor() function to convert real->int */
68871           assert( u.bc.oc==OP_SeekLe || u.bc.oc==OP_SeekGt );
68872           if( pIn3->r < (double)u.bc.iKey ) u.bc.iKey--;
68873         }
68874       }
68875       rc = sqlite3BtreeMovetoUnpacked(u.bc.pC->pCursor, 0, (u64)u.bc.iKey, 0, &u.bc.res);
68876       if( rc!=SQLITE_OK ){
68877         goto abort_due_to_error;
68878       }
68879       if( u.bc.res==0 ){
68880         u.bc.pC->rowidIsValid = 1;
68881         u.bc.pC->lastRowid = u.bc.iKey;
68882       }
68883     }else{
68884       u.bc.nField = pOp->p4.i;
68885       assert( pOp->p4type==P4_INT32 );
68886       assert( u.bc.nField>0 );
68887       u.bc.r.pKeyInfo = u.bc.pC->pKeyInfo;
68888       u.bc.r.nField = (u16)u.bc.nField;
68889
68890       /* The next line of code computes as follows, only faster:
68891       **   if( u.bc.oc==OP_SeekGt || u.bc.oc==OP_SeekLe ){
68892       **     u.bc.r.flags = UNPACKED_INCRKEY;
68893       **   }else{
68894       **     u.bc.r.flags = 0;
68895       **   }
68896       */
68897       u.bc.r.flags = (u8)(UNPACKED_INCRKEY * (1 & (u.bc.oc - OP_SeekLt)));
68898       assert( u.bc.oc!=OP_SeekGt || u.bc.r.flags==UNPACKED_INCRKEY );
68899       assert( u.bc.oc!=OP_SeekLe || u.bc.r.flags==UNPACKED_INCRKEY );
68900       assert( u.bc.oc!=OP_SeekGe || u.bc.r.flags==0 );
68901       assert( u.bc.oc!=OP_SeekLt || u.bc.r.flags==0 );
68902
68903       u.bc.r.aMem = &aMem[pOp->p3];
68904 #ifdef SQLITE_DEBUG
68905       { int i; for(i=0; i<u.bc.r.nField; i++) assert( memIsValid(&u.bc.r.aMem[i]) ); }
68906 #endif
68907       ExpandBlob(u.bc.r.aMem);
68908       rc = sqlite3BtreeMovetoUnpacked(u.bc.pC->pCursor, &u.bc.r, 0, 0, &u.bc.res);
68909       if( rc!=SQLITE_OK ){
68910         goto abort_due_to_error;
68911       }
68912       u.bc.pC->rowidIsValid = 0;
68913     }
68914     u.bc.pC->deferredMoveto = 0;
68915     u.bc.pC->cacheStatus = CACHE_STALE;
68916 #ifdef SQLITE_TEST
68917     sqlite3_search_count++;
68918 #endif
68919     if( u.bc.oc>=OP_SeekGe ){  assert( u.bc.oc==OP_SeekGe || u.bc.oc==OP_SeekGt );
68920       if( u.bc.res<0 || (u.bc.res==0 && u.bc.oc==OP_SeekGt) ){
68921         rc = sqlite3BtreeNext(u.bc.pC->pCursor, &u.bc.res);
68922         if( rc!=SQLITE_OK ) goto abort_due_to_error;
68923         u.bc.pC->rowidIsValid = 0;
68924       }else{
68925         u.bc.res = 0;
68926       }
68927     }else{
68928       assert( u.bc.oc==OP_SeekLt || u.bc.oc==OP_SeekLe );
68929       if( u.bc.res>0 || (u.bc.res==0 && u.bc.oc==OP_SeekLt) ){
68930         rc = sqlite3BtreePrevious(u.bc.pC->pCursor, &u.bc.res);
68931         if( rc!=SQLITE_OK ) goto abort_due_to_error;
68932         u.bc.pC->rowidIsValid = 0;
68933       }else{
68934         /* u.bc.res might be negative because the table is empty.  Check to
68935         ** see if this is the case.
68936         */
68937         u.bc.res = sqlite3BtreeEof(u.bc.pC->pCursor);
68938       }
68939     }
68940     assert( pOp->p2>0 );
68941     if( u.bc.res ){
68942       pc = pOp->p2 - 1;
68943     }
68944   }else{
68945     /* This happens when attempting to open the sqlite3_master table
68946     ** for read access returns SQLITE_EMPTY. In this case always
68947     ** take the jump (since there are no records in the table).
68948     */
68949     pc = pOp->p2 - 1;
68950   }
68951   break;
68952 }
68953
68954 /* Opcode: Seek P1 P2 * * *
68955 **
68956 ** P1 is an open table cursor and P2 is a rowid integer.  Arrange
68957 ** for P1 to move so that it points to the rowid given by P2.
68958 **
68959 ** This is actually a deferred seek.  Nothing actually happens until
68960 ** the cursor is used to read a record.  That way, if no reads
68961 ** occur, no unnecessary I/O happens.
68962 */
68963 case OP_Seek: {    /* in2 */
68964 #if 0  /* local variables moved into u.bd */
68965   VdbeCursor *pC;
68966 #endif /* local variables moved into u.bd */
68967
68968   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
68969   u.bd.pC = p->apCsr[pOp->p1];
68970   assert( u.bd.pC!=0 );
68971   if( ALWAYS(u.bd.pC->pCursor!=0) ){
68972     assert( u.bd.pC->isTable );
68973     u.bd.pC->nullRow = 0;
68974     pIn2 = &aMem[pOp->p2];
68975     u.bd.pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
68976     u.bd.pC->rowidIsValid = 0;
68977     u.bd.pC->deferredMoveto = 1;
68978   }
68979   break;
68980 }
68981   
68982
68983 /* Opcode: Found P1 P2 P3 P4 *
68984 **
68985 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
68986 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
68987 ** record.
68988 **
68989 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
68990 ** is a prefix of any entry in P1 then a jump is made to P2 and
68991 ** P1 is left pointing at the matching entry.
68992 */
68993 /* Opcode: NotFound P1 P2 P3 P4 *
68994 **
68995 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
68996 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
68997 ** record.
68998 ** 
68999 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
69000 ** is not the prefix of any entry in P1 then a jump is made to P2.  If P1 
69001 ** does contain an entry whose prefix matches the P3/P4 record then control
69002 ** falls through to the next instruction and P1 is left pointing at the
69003 ** matching entry.
69004 **
69005 ** See also: Found, NotExists, IsUnique
69006 */
69007 case OP_NotFound:       /* jump, in3 */
69008 case OP_Found: {        /* jump, in3 */
69009 #if 0  /* local variables moved into u.be */
69010   int alreadyExists;
69011   VdbeCursor *pC;
69012   int res;
69013   char *pFree;
69014   UnpackedRecord *pIdxKey;
69015   UnpackedRecord r;
69016   char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
69017 #endif /* local variables moved into u.be */
69018
69019 #ifdef SQLITE_TEST
69020   sqlite3_found_count++;
69021 #endif
69022
69023   u.be.alreadyExists = 0;
69024   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69025   assert( pOp->p4type==P4_INT32 );
69026   u.be.pC = p->apCsr[pOp->p1];
69027   assert( u.be.pC!=0 );
69028   pIn3 = &aMem[pOp->p3];
69029   if( ALWAYS(u.be.pC->pCursor!=0) ){
69030
69031     assert( u.be.pC->isTable==0 );
69032     if( pOp->p4.i>0 ){
69033       u.be.r.pKeyInfo = u.be.pC->pKeyInfo;
69034       u.be.r.nField = (u16)pOp->p4.i;
69035       u.be.r.aMem = pIn3;
69036 #ifdef SQLITE_DEBUG
69037       { int i; for(i=0; i<u.be.r.nField; i++) assert( memIsValid(&u.be.r.aMem[i]) ); }
69038 #endif
69039       u.be.r.flags = UNPACKED_PREFIX_MATCH;
69040       u.be.pIdxKey = &u.be.r;
69041     }else{
69042       u.be.pIdxKey = sqlite3VdbeAllocUnpackedRecord(
69043           u.be.pC->pKeyInfo, u.be.aTempRec, sizeof(u.be.aTempRec), &u.be.pFree
69044       );
69045       if( u.be.pIdxKey==0 ) goto no_mem;
69046       assert( pIn3->flags & MEM_Blob );
69047       assert( (pIn3->flags & MEM_Zero)==0 );  /* zeroblobs already expanded */
69048       sqlite3VdbeRecordUnpack(u.be.pC->pKeyInfo, pIn3->n, pIn3->z, u.be.pIdxKey);
69049       u.be.pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
69050     }
69051     rc = sqlite3BtreeMovetoUnpacked(u.be.pC->pCursor, u.be.pIdxKey, 0, 0, &u.be.res);
69052     if( pOp->p4.i==0 ){
69053       sqlite3DbFree(db, u.be.pFree);
69054     }
69055     if( rc!=SQLITE_OK ){
69056       break;
69057     }
69058     u.be.alreadyExists = (u.be.res==0);
69059     u.be.pC->deferredMoveto = 0;
69060     u.be.pC->cacheStatus = CACHE_STALE;
69061   }
69062   if( pOp->opcode==OP_Found ){
69063     if( u.be.alreadyExists ) pc = pOp->p2 - 1;
69064   }else{
69065     if( !u.be.alreadyExists ) pc = pOp->p2 - 1;
69066   }
69067   break;
69068 }
69069
69070 /* Opcode: IsUnique P1 P2 P3 P4 *
69071 **
69072 ** Cursor P1 is open on an index b-tree - that is to say, a btree which
69073 ** no data and where the key are records generated by OP_MakeRecord with
69074 ** the list field being the integer ROWID of the entry that the index
69075 ** entry refers to.
69076 **
69077 ** The P3 register contains an integer record number. Call this record 
69078 ** number R. Register P4 is the first in a set of N contiguous registers
69079 ** that make up an unpacked index key that can be used with cursor P1.
69080 ** The value of N can be inferred from the cursor. N includes the rowid
69081 ** value appended to the end of the index record. This rowid value may
69082 ** or may not be the same as R.
69083 **
69084 ** If any of the N registers beginning with register P4 contains a NULL
69085 ** value, jump immediately to P2.
69086 **
69087 ** Otherwise, this instruction checks if cursor P1 contains an entry
69088 ** where the first (N-1) fields match but the rowid value at the end
69089 ** of the index entry is not R. If there is no such entry, control jumps
69090 ** to instruction P2. Otherwise, the rowid of the conflicting index
69091 ** entry is copied to register P3 and control falls through to the next
69092 ** instruction.
69093 **
69094 ** See also: NotFound, NotExists, Found
69095 */
69096 case OP_IsUnique: {        /* jump, in3 */
69097 #if 0  /* local variables moved into u.bf */
69098   u16 ii;
69099   VdbeCursor *pCx;
69100   BtCursor *pCrsr;
69101   u16 nField;
69102   Mem *aMx;
69103   UnpackedRecord r;                  /* B-Tree index search key */
69104   i64 R;                             /* Rowid stored in register P3 */
69105 #endif /* local variables moved into u.bf */
69106
69107   pIn3 = &aMem[pOp->p3];
69108   u.bf.aMx = &aMem[pOp->p4.i];
69109   /* Assert that the values of parameters P1 and P4 are in range. */
69110   assert( pOp->p4type==P4_INT32 );
69111   assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
69112   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69113
69114   /* Find the index cursor. */
69115   u.bf.pCx = p->apCsr[pOp->p1];
69116   assert( u.bf.pCx->deferredMoveto==0 );
69117   u.bf.pCx->seekResult = 0;
69118   u.bf.pCx->cacheStatus = CACHE_STALE;
69119   u.bf.pCrsr = u.bf.pCx->pCursor;
69120
69121   /* If any of the values are NULL, take the jump. */
69122   u.bf.nField = u.bf.pCx->pKeyInfo->nField;
69123   for(u.bf.ii=0; u.bf.ii<u.bf.nField; u.bf.ii++){
69124     if( u.bf.aMx[u.bf.ii].flags & MEM_Null ){
69125       pc = pOp->p2 - 1;
69126       u.bf.pCrsr = 0;
69127       break;
69128     }
69129   }
69130   assert( (u.bf.aMx[u.bf.nField].flags & MEM_Null)==0 );
69131
69132   if( u.bf.pCrsr!=0 ){
69133     /* Populate the index search key. */
69134     u.bf.r.pKeyInfo = u.bf.pCx->pKeyInfo;
69135     u.bf.r.nField = u.bf.nField + 1;
69136     u.bf.r.flags = UNPACKED_PREFIX_SEARCH;
69137     u.bf.r.aMem = u.bf.aMx;
69138 #ifdef SQLITE_DEBUG
69139     { int i; for(i=0; i<u.bf.r.nField; i++) assert( memIsValid(&u.bf.r.aMem[i]) ); }
69140 #endif
69141
69142     /* Extract the value of u.bf.R from register P3. */
69143     sqlite3VdbeMemIntegerify(pIn3);
69144     u.bf.R = pIn3->u.i;
69145
69146     /* Search the B-Tree index. If no conflicting record is found, jump
69147     ** to P2. Otherwise, copy the rowid of the conflicting record to
69148     ** register P3 and fall through to the next instruction.  */
69149     rc = sqlite3BtreeMovetoUnpacked(u.bf.pCrsr, &u.bf.r, 0, 0, &u.bf.pCx->seekResult);
69150     if( (u.bf.r.flags & UNPACKED_PREFIX_SEARCH) || u.bf.r.rowid==u.bf.R ){
69151       pc = pOp->p2 - 1;
69152     }else{
69153       pIn3->u.i = u.bf.r.rowid;
69154     }
69155   }
69156   break;
69157 }
69158
69159 /* Opcode: NotExists P1 P2 P3 * *
69160 **
69161 ** Use the content of register P3 as an integer key.  If a record 
69162 ** with that key does not exist in table of P1, then jump to P2. 
69163 ** If the record does exist, then fall through.  The cursor is left 
69164 ** pointing to the record if it exists.
69165 **
69166 ** The difference between this operation and NotFound is that this
69167 ** operation assumes the key is an integer and that P1 is a table whereas
69168 ** NotFound assumes key is a blob constructed from MakeRecord and
69169 ** P1 is an index.
69170 **
69171 ** See also: Found, NotFound, IsUnique
69172 */
69173 case OP_NotExists: {        /* jump, in3 */
69174 #if 0  /* local variables moved into u.bg */
69175   VdbeCursor *pC;
69176   BtCursor *pCrsr;
69177   int res;
69178   u64 iKey;
69179 #endif /* local variables moved into u.bg */
69180
69181   pIn3 = &aMem[pOp->p3];
69182   assert( pIn3->flags & MEM_Int );
69183   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69184   u.bg.pC = p->apCsr[pOp->p1];
69185   assert( u.bg.pC!=0 );
69186   assert( u.bg.pC->isTable );
69187   assert( u.bg.pC->pseudoTableReg==0 );
69188   u.bg.pCrsr = u.bg.pC->pCursor;
69189   if( ALWAYS(u.bg.pCrsr!=0) ){
69190     u.bg.res = 0;
69191     u.bg.iKey = pIn3->u.i;
69192     rc = sqlite3BtreeMovetoUnpacked(u.bg.pCrsr, 0, u.bg.iKey, 0, &u.bg.res);
69193     u.bg.pC->lastRowid = pIn3->u.i;
69194     u.bg.pC->rowidIsValid = u.bg.res==0 ?1:0;
69195     u.bg.pC->nullRow = 0;
69196     u.bg.pC->cacheStatus = CACHE_STALE;
69197     u.bg.pC->deferredMoveto = 0;
69198     if( u.bg.res!=0 ){
69199       pc = pOp->p2 - 1;
69200       assert( u.bg.pC->rowidIsValid==0 );
69201     }
69202     u.bg.pC->seekResult = u.bg.res;
69203   }else{
69204     /* This happens when an attempt to open a read cursor on the
69205     ** sqlite_master table returns SQLITE_EMPTY.
69206     */
69207     pc = pOp->p2 - 1;
69208     assert( u.bg.pC->rowidIsValid==0 );
69209     u.bg.pC->seekResult = 0;
69210   }
69211   break;
69212 }
69213
69214 /* Opcode: Sequence P1 P2 * * *
69215 **
69216 ** Find the next available sequence number for cursor P1.
69217 ** Write the sequence number into register P2.
69218 ** The sequence number on the cursor is incremented after this
69219 ** instruction.  
69220 */
69221 case OP_Sequence: {           /* out2-prerelease */
69222   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69223   assert( p->apCsr[pOp->p1]!=0 );
69224   pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
69225   break;
69226 }
69227
69228
69229 /* Opcode: NewRowid P1 P2 P3 * *
69230 **
69231 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
69232 ** The record number is not previously used as a key in the database
69233 ** table that cursor P1 points to.  The new record number is written
69234 ** written to register P2.
69235 **
69236 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds 
69237 ** the largest previously generated record number. No new record numbers are
69238 ** allowed to be less than this value. When this value reaches its maximum, 
69239 ** an SQLITE_FULL error is generated. The P3 register is updated with the '
69240 ** generated record number. This P3 mechanism is used to help implement the
69241 ** AUTOINCREMENT feature.
69242 */
69243 case OP_NewRowid: {           /* out2-prerelease */
69244 #if 0  /* local variables moved into u.bh */
69245   i64 v;                 /* The new rowid */
69246   VdbeCursor *pC;        /* Cursor of table to get the new rowid */
69247   int res;               /* Result of an sqlite3BtreeLast() */
69248   int cnt;               /* Counter to limit the number of searches */
69249   Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
69250   VdbeFrame *pFrame;     /* Root frame of VDBE */
69251 #endif /* local variables moved into u.bh */
69252
69253   u.bh.v = 0;
69254   u.bh.res = 0;
69255   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69256   u.bh.pC = p->apCsr[pOp->p1];
69257   assert( u.bh.pC!=0 );
69258   if( NEVER(u.bh.pC->pCursor==0) ){
69259     /* The zero initialization above is all that is needed */
69260   }else{
69261     /* The next rowid or record number (different terms for the same
69262     ** thing) is obtained in a two-step algorithm.
69263     **
69264     ** First we attempt to find the largest existing rowid and add one
69265     ** to that.  But if the largest existing rowid is already the maximum
69266     ** positive integer, we have to fall through to the second
69267     ** probabilistic algorithm
69268     **
69269     ** The second algorithm is to select a rowid at random and see if
69270     ** it already exists in the table.  If it does not exist, we have
69271     ** succeeded.  If the random rowid does exist, we select a new one
69272     ** and try again, up to 100 times.
69273     */
69274     assert( u.bh.pC->isTable );
69275
69276 #ifdef SQLITE_32BIT_ROWID
69277 #   define MAX_ROWID 0x7fffffff
69278 #else
69279     /* Some compilers complain about constants of the form 0x7fffffffffffffff.
69280     ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
69281     ** to provide the constant while making all compilers happy.
69282     */
69283 #   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
69284 #endif
69285
69286     if( !u.bh.pC->useRandomRowid ){
69287       u.bh.v = sqlite3BtreeGetCachedRowid(u.bh.pC->pCursor);
69288       if( u.bh.v==0 ){
69289         rc = sqlite3BtreeLast(u.bh.pC->pCursor, &u.bh.res);
69290         if( rc!=SQLITE_OK ){
69291           goto abort_due_to_error;
69292         }
69293         if( u.bh.res ){
69294           u.bh.v = 1;   /* IMP: R-61914-48074 */
69295         }else{
69296           assert( sqlite3BtreeCursorIsValid(u.bh.pC->pCursor) );
69297           rc = sqlite3BtreeKeySize(u.bh.pC->pCursor, &u.bh.v);
69298           assert( rc==SQLITE_OK );   /* Cannot fail following BtreeLast() */
69299           if( u.bh.v>=MAX_ROWID ){
69300             u.bh.pC->useRandomRowid = 1;
69301           }else{
69302             u.bh.v++;   /* IMP: R-29538-34987 */
69303           }
69304         }
69305       }
69306
69307 #ifndef SQLITE_OMIT_AUTOINCREMENT
69308       if( pOp->p3 ){
69309         /* Assert that P3 is a valid memory cell. */
69310         assert( pOp->p3>0 );
69311         if( p->pFrame ){
69312           for(u.bh.pFrame=p->pFrame; u.bh.pFrame->pParent; u.bh.pFrame=u.bh.pFrame->pParent);
69313           /* Assert that P3 is a valid memory cell. */
69314           assert( pOp->p3<=u.bh.pFrame->nMem );
69315           u.bh.pMem = &u.bh.pFrame->aMem[pOp->p3];
69316         }else{
69317           /* Assert that P3 is a valid memory cell. */
69318           assert( pOp->p3<=p->nMem );
69319           u.bh.pMem = &aMem[pOp->p3];
69320           memAboutToChange(p, u.bh.pMem);
69321         }
69322         assert( memIsValid(u.bh.pMem) );
69323
69324         REGISTER_TRACE(pOp->p3, u.bh.pMem);
69325         sqlite3VdbeMemIntegerify(u.bh.pMem);
69326         assert( (u.bh.pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
69327         if( u.bh.pMem->u.i==MAX_ROWID || u.bh.pC->useRandomRowid ){
69328           rc = SQLITE_FULL;   /* IMP: R-12275-61338 */
69329           goto abort_due_to_error;
69330         }
69331         if( u.bh.v<u.bh.pMem->u.i+1 ){
69332           u.bh.v = u.bh.pMem->u.i + 1;
69333         }
69334         u.bh.pMem->u.i = u.bh.v;
69335       }
69336 #endif
69337
69338       sqlite3BtreeSetCachedRowid(u.bh.pC->pCursor, u.bh.v<MAX_ROWID ? u.bh.v+1 : 0);
69339     }
69340     if( u.bh.pC->useRandomRowid ){
69341       /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
69342       ** largest possible integer (9223372036854775807) then the database
69343       ** engine starts picking positive candidate ROWIDs at random until
69344       ** it finds one that is not previously used. */
69345       assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
69346                              ** an AUTOINCREMENT table. */
69347       /* on the first attempt, simply do one more than previous */
69348       u.bh.v = lastRowid;
69349       u.bh.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
69350       u.bh.v++; /* ensure non-zero */
69351       u.bh.cnt = 0;
69352       while(   ((rc = sqlite3BtreeMovetoUnpacked(u.bh.pC->pCursor, 0, (u64)u.bh.v,
69353                                                  0, &u.bh.res))==SQLITE_OK)
69354             && (u.bh.res==0)
69355             && (++u.bh.cnt<100)){
69356         /* collision - try another random rowid */
69357         sqlite3_randomness(sizeof(u.bh.v), &u.bh.v);
69358         if( u.bh.cnt<5 ){
69359           /* try "small" random rowids for the initial attempts */
69360           u.bh.v &= 0xffffff;
69361         }else{
69362           u.bh.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
69363         }
69364         u.bh.v++; /* ensure non-zero */
69365       }
69366       if( rc==SQLITE_OK && u.bh.res==0 ){
69367         rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
69368         goto abort_due_to_error;
69369       }
69370       assert( u.bh.v>0 );  /* EV: R-40812-03570 */
69371     }
69372     u.bh.pC->rowidIsValid = 0;
69373     u.bh.pC->deferredMoveto = 0;
69374     u.bh.pC->cacheStatus = CACHE_STALE;
69375   }
69376   pOut->u.i = u.bh.v;
69377   break;
69378 }
69379
69380 /* Opcode: Insert P1 P2 P3 P4 P5
69381 **
69382 ** Write an entry into the table of cursor P1.  A new entry is
69383 ** created if it doesn't already exist or the data for an existing
69384 ** entry is overwritten.  The data is the value MEM_Blob stored in register
69385 ** number P2. The key is stored in register P3. The key must
69386 ** be a MEM_Int.
69387 **
69388 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
69389 ** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
69390 ** then rowid is stored for subsequent return by the
69391 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
69392 **
69393 ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
69394 ** the last seek operation (OP_NotExists) was a success, then this
69395 ** operation will not attempt to find the appropriate row before doing
69396 ** the insert but will instead overwrite the row that the cursor is
69397 ** currently pointing to.  Presumably, the prior OP_NotExists opcode
69398 ** has already positioned the cursor correctly.  This is an optimization
69399 ** that boosts performance by avoiding redundant seeks.
69400 **
69401 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
69402 ** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
69403 ** is part of an INSERT operation.  The difference is only important to
69404 ** the update hook.
69405 **
69406 ** Parameter P4 may point to a string containing the table-name, or
69407 ** may be NULL. If it is not NULL, then the update-hook 
69408 ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
69409 **
69410 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
69411 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
69412 ** and register P2 becomes ephemeral.  If the cursor is changed, the
69413 ** value of register P2 will then change.  Make sure this does not
69414 ** cause any problems.)
69415 **
69416 ** This instruction only works on tables.  The equivalent instruction
69417 ** for indices is OP_IdxInsert.
69418 */
69419 /* Opcode: InsertInt P1 P2 P3 P4 P5
69420 **
69421 ** This works exactly like OP_Insert except that the key is the
69422 ** integer value P3, not the value of the integer stored in register P3.
69423 */
69424 case OP_Insert: 
69425 case OP_InsertInt: {
69426 #if 0  /* local variables moved into u.bi */
69427   Mem *pData;       /* MEM cell holding data for the record to be inserted */
69428   Mem *pKey;        /* MEM cell holding key  for the record */
69429   i64 iKey;         /* The integer ROWID or key for the record to be inserted */
69430   VdbeCursor *pC;   /* Cursor to table into which insert is written */
69431   int nZero;        /* Number of zero-bytes to append */
69432   int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
69433   const char *zDb;  /* database name - used by the update hook */
69434   const char *zTbl; /* Table name - used by the opdate hook */
69435   int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
69436 #endif /* local variables moved into u.bi */
69437
69438   u.bi.pData = &aMem[pOp->p2];
69439   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69440   assert( memIsValid(u.bi.pData) );
69441   u.bi.pC = p->apCsr[pOp->p1];
69442   assert( u.bi.pC!=0 );
69443   assert( u.bi.pC->pCursor!=0 );
69444   assert( u.bi.pC->pseudoTableReg==0 );
69445   assert( u.bi.pC->isTable );
69446   REGISTER_TRACE(pOp->p2, u.bi.pData);
69447
69448   if( pOp->opcode==OP_Insert ){
69449     u.bi.pKey = &aMem[pOp->p3];
69450     assert( u.bi.pKey->flags & MEM_Int );
69451     assert( memIsValid(u.bi.pKey) );
69452     REGISTER_TRACE(pOp->p3, u.bi.pKey);
69453     u.bi.iKey = u.bi.pKey->u.i;
69454   }else{
69455     assert( pOp->opcode==OP_InsertInt );
69456     u.bi.iKey = pOp->p3;
69457   }
69458
69459   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
69460   if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = u.bi.iKey;
69461   if( u.bi.pData->flags & MEM_Null ){
69462     u.bi.pData->z = 0;
69463     u.bi.pData->n = 0;
69464   }else{
69465     assert( u.bi.pData->flags & (MEM_Blob|MEM_Str) );
69466   }
69467   u.bi.seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bi.pC->seekResult : 0);
69468   if( u.bi.pData->flags & MEM_Zero ){
69469     u.bi.nZero = u.bi.pData->u.nZero;
69470   }else{
69471     u.bi.nZero = 0;
69472   }
69473   sqlite3BtreeSetCachedRowid(u.bi.pC->pCursor, 0);
69474   rc = sqlite3BtreeInsert(u.bi.pC->pCursor, 0, u.bi.iKey,
69475                           u.bi.pData->z, u.bi.pData->n, u.bi.nZero,
69476                           pOp->p5 & OPFLAG_APPEND, u.bi.seekResult
69477   );
69478   u.bi.pC->rowidIsValid = 0;
69479   u.bi.pC->deferredMoveto = 0;
69480   u.bi.pC->cacheStatus = CACHE_STALE;
69481
69482   /* Invoke the update-hook if required. */
69483   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
69484     u.bi.zDb = db->aDb[u.bi.pC->iDb].zName;
69485     u.bi.zTbl = pOp->p4.z;
69486     u.bi.op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
69487     assert( u.bi.pC->isTable );
69488     db->xUpdateCallback(db->pUpdateArg, u.bi.op, u.bi.zDb, u.bi.zTbl, u.bi.iKey);
69489     assert( u.bi.pC->iDb>=0 );
69490   }
69491   break;
69492 }
69493
69494 /* Opcode: Delete P1 P2 * P4 *
69495 **
69496 ** Delete the record at which the P1 cursor is currently pointing.
69497 **
69498 ** The cursor will be left pointing at either the next or the previous
69499 ** record in the table. If it is left pointing at the next record, then
69500 ** the next Next instruction will be a no-op.  Hence it is OK to delete
69501 ** a record from within an Next loop.
69502 **
69503 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
69504 ** incremented (otherwise not).
69505 **
69506 ** P1 must not be pseudo-table.  It has to be a real table with
69507 ** multiple rows.
69508 **
69509 ** If P4 is not NULL, then it is the name of the table that P1 is
69510 ** pointing to.  The update hook will be invoked, if it exists.
69511 ** If P4 is not NULL then the P1 cursor must have been positioned
69512 ** using OP_NotFound prior to invoking this opcode.
69513 */
69514 case OP_Delete: {
69515 #if 0  /* local variables moved into u.bj */
69516   i64 iKey;
69517   VdbeCursor *pC;
69518 #endif /* local variables moved into u.bj */
69519
69520   u.bj.iKey = 0;
69521   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69522   u.bj.pC = p->apCsr[pOp->p1];
69523   assert( u.bj.pC!=0 );
69524   assert( u.bj.pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */
69525
69526   /* If the update-hook will be invoked, set u.bj.iKey to the rowid of the
69527   ** row being deleted.
69528   */
69529   if( db->xUpdateCallback && pOp->p4.z ){
69530     assert( u.bj.pC->isTable );
69531     assert( u.bj.pC->rowidIsValid );  /* lastRowid set by previous OP_NotFound */
69532     u.bj.iKey = u.bj.pC->lastRowid;
69533   }
69534
69535   /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
69536   ** OP_Column on the same table without any intervening operations that
69537   ** might move or invalidate the cursor.  Hence cursor u.bj.pC is always pointing
69538   ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation
69539   ** below is always a no-op and cannot fail.  We will run it anyhow, though,
69540   ** to guard against future changes to the code generator.
69541   **/
69542   assert( u.bj.pC->deferredMoveto==0 );
69543   rc = sqlite3VdbeCursorMoveto(u.bj.pC);
69544   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
69545
69546   sqlite3BtreeSetCachedRowid(u.bj.pC->pCursor, 0);
69547   rc = sqlite3BtreeDelete(u.bj.pC->pCursor);
69548   u.bj.pC->cacheStatus = CACHE_STALE;
69549
69550   /* Invoke the update-hook if required. */
69551   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
69552     const char *zDb = db->aDb[u.bj.pC->iDb].zName;
69553     const char *zTbl = pOp->p4.z;
69554     db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, u.bj.iKey);
69555     assert( u.bj.pC->iDb>=0 );
69556   }
69557   if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
69558   break;
69559 }
69560 /* Opcode: ResetCount * * * * *
69561 **
69562 ** The value of the change counter is copied to the database handle
69563 ** change counter (returned by subsequent calls to sqlite3_changes()).
69564 ** Then the VMs internal change counter resets to 0.
69565 ** This is used by trigger programs.
69566 */
69567 case OP_ResetCount: {
69568   sqlite3VdbeSetChanges(db, p->nChange);
69569   p->nChange = 0;
69570   break;
69571 }
69572
69573 /* Opcode: SorterCompare P1 P2 P3
69574 **
69575 ** P1 is a sorter cursor. This instruction compares the record blob in 
69576 ** register P3 with the entry that the sorter cursor currently points to.
69577 ** If, excluding the rowid fields at the end, the two records are a match,
69578 ** fall through to the next instruction. Otherwise, jump to instruction P2.
69579 */
69580 case OP_SorterCompare: {
69581 #if 0  /* local variables moved into u.bk */
69582   VdbeCursor *pC;
69583   int res;
69584 #endif /* local variables moved into u.bk */
69585
69586   u.bk.pC = p->apCsr[pOp->p1];
69587   assert( isSorter(u.bk.pC) );
69588   pIn3 = &aMem[pOp->p3];
69589   rc = sqlite3VdbeSorterCompare(u.bk.pC, pIn3, &u.bk.res);
69590   if( u.bk.res ){
69591     pc = pOp->p2-1;
69592   }
69593   break;
69594 };
69595
69596 /* Opcode: SorterData P1 P2 * * *
69597 **
69598 ** Write into register P2 the current sorter data for sorter cursor P1.
69599 */
69600 case OP_SorterData: {
69601 #if 0  /* local variables moved into u.bl */
69602   VdbeCursor *pC;
69603 #endif /* local variables moved into u.bl */
69604
69605   pOut = &aMem[pOp->p2];
69606   u.bl.pC = p->apCsr[pOp->p1];
69607   assert( u.bl.pC->isSorter );
69608   rc = sqlite3VdbeSorterRowkey(u.bl.pC, pOut);
69609   break;
69610 }
69611
69612 /* Opcode: RowData P1 P2 * * *
69613 **
69614 ** Write into register P2 the complete row data for cursor P1.
69615 ** There is no interpretation of the data.  
69616 ** It is just copied onto the P2 register exactly as 
69617 ** it is found in the database file.
69618 **
69619 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
69620 ** of a real table, not a pseudo-table.
69621 */
69622 /* Opcode: RowKey P1 P2 * * *
69623 **
69624 ** Write into register P2 the complete row key for cursor P1.
69625 ** There is no interpretation of the data.  
69626 ** The key is copied onto the P3 register exactly as 
69627 ** it is found in the database file.
69628 **
69629 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
69630 ** of a real table, not a pseudo-table.
69631 */
69632 case OP_RowKey:
69633 case OP_RowData: {
69634 #if 0  /* local variables moved into u.bm */
69635   VdbeCursor *pC;
69636   BtCursor *pCrsr;
69637   u32 n;
69638   i64 n64;
69639 #endif /* local variables moved into u.bm */
69640
69641   pOut = &aMem[pOp->p2];
69642   memAboutToChange(p, pOut);
69643
69644   /* Note that RowKey and RowData are really exactly the same instruction */
69645   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69646   u.bm.pC = p->apCsr[pOp->p1];
69647   assert( u.bm.pC->isSorter==0 );
69648   assert( u.bm.pC->isTable || pOp->opcode!=OP_RowData );
69649   assert( u.bm.pC->isIndex || pOp->opcode==OP_RowData );
69650   assert( u.bm.pC!=0 );
69651   assert( u.bm.pC->nullRow==0 );
69652   assert( u.bm.pC->pseudoTableReg==0 );
69653   assert( u.bm.pC->pCursor!=0 );
69654   u.bm.pCrsr = u.bm.pC->pCursor;
69655   assert( sqlite3BtreeCursorIsValid(u.bm.pCrsr) );
69656
69657   /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
69658   ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
69659   ** the cursor.  Hence the following sqlite3VdbeCursorMoveto() call is always
69660   ** a no-op and can never fail.  But we leave it in place as a safety.
69661   */
69662   assert( u.bm.pC->deferredMoveto==0 );
69663   rc = sqlite3VdbeCursorMoveto(u.bm.pC);
69664   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
69665
69666   if( u.bm.pC->isIndex ){
69667     assert( !u.bm.pC->isTable );
69668     VVA_ONLY(rc =) sqlite3BtreeKeySize(u.bm.pCrsr, &u.bm.n64);
69669     assert( rc==SQLITE_OK );    /* True because of CursorMoveto() call above */
69670     if( u.bm.n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
69671       goto too_big;
69672     }
69673     u.bm.n = (u32)u.bm.n64;
69674   }else{
69675     VVA_ONLY(rc =) sqlite3BtreeDataSize(u.bm.pCrsr, &u.bm.n);
69676     assert( rc==SQLITE_OK );    /* DataSize() cannot fail */
69677     if( u.bm.n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
69678       goto too_big;
69679     }
69680   }
69681   if( sqlite3VdbeMemGrow(pOut, u.bm.n, 0) ){
69682     goto no_mem;
69683   }
69684   pOut->n = u.bm.n;
69685   MemSetTypeFlag(pOut, MEM_Blob);
69686   if( u.bm.pC->isIndex ){
69687     rc = sqlite3BtreeKey(u.bm.pCrsr, 0, u.bm.n, pOut->z);
69688   }else{
69689     rc = sqlite3BtreeData(u.bm.pCrsr, 0, u.bm.n, pOut->z);
69690   }
69691   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
69692   UPDATE_MAX_BLOBSIZE(pOut);
69693   break;
69694 }
69695
69696 /* Opcode: Rowid P1 P2 * * *
69697 **
69698 ** Store in register P2 an integer which is the key of the table entry that
69699 ** P1 is currently point to.
69700 **
69701 ** P1 can be either an ordinary table or a virtual table.  There used to
69702 ** be a separate OP_VRowid opcode for use with virtual tables, but this
69703 ** one opcode now works for both table types.
69704 */
69705 case OP_Rowid: {                 /* out2-prerelease */
69706 #if 0  /* local variables moved into u.bn */
69707   VdbeCursor *pC;
69708   i64 v;
69709   sqlite3_vtab *pVtab;
69710   const sqlite3_module *pModule;
69711 #endif /* local variables moved into u.bn */
69712
69713   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69714   u.bn.pC = p->apCsr[pOp->p1];
69715   assert( u.bn.pC!=0 );
69716   assert( u.bn.pC->pseudoTableReg==0 || u.bn.pC->nullRow );
69717   if( u.bn.pC->nullRow ){
69718     pOut->flags = MEM_Null;
69719     break;
69720   }else if( u.bn.pC->deferredMoveto ){
69721     u.bn.v = u.bn.pC->movetoTarget;
69722 #ifndef SQLITE_OMIT_VIRTUALTABLE
69723   }else if( u.bn.pC->pVtabCursor ){
69724     u.bn.pVtab = u.bn.pC->pVtabCursor->pVtab;
69725     u.bn.pModule = u.bn.pVtab->pModule;
69726     assert( u.bn.pModule->xRowid );
69727     rc = u.bn.pModule->xRowid(u.bn.pC->pVtabCursor, &u.bn.v);
69728     importVtabErrMsg(p, u.bn.pVtab);
69729 #endif /* SQLITE_OMIT_VIRTUALTABLE */
69730   }else{
69731     assert( u.bn.pC->pCursor!=0 );
69732     rc = sqlite3VdbeCursorMoveto(u.bn.pC);
69733     if( rc ) goto abort_due_to_error;
69734     if( u.bn.pC->rowidIsValid ){
69735       u.bn.v = u.bn.pC->lastRowid;
69736     }else{
69737       rc = sqlite3BtreeKeySize(u.bn.pC->pCursor, &u.bn.v);
69738       assert( rc==SQLITE_OK );  /* Always so because of CursorMoveto() above */
69739     }
69740   }
69741   pOut->u.i = u.bn.v;
69742   break;
69743 }
69744
69745 /* Opcode: NullRow P1 * * * *
69746 **
69747 ** Move the cursor P1 to a null row.  Any OP_Column operations
69748 ** that occur while the cursor is on the null row will always
69749 ** write a NULL.
69750 */
69751 case OP_NullRow: {
69752 #if 0  /* local variables moved into u.bo */
69753   VdbeCursor *pC;
69754 #endif /* local variables moved into u.bo */
69755
69756   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69757   u.bo.pC = p->apCsr[pOp->p1];
69758   assert( u.bo.pC!=0 );
69759   u.bo.pC->nullRow = 1;
69760   u.bo.pC->rowidIsValid = 0;
69761   assert( u.bo.pC->pCursor || u.bo.pC->pVtabCursor );
69762   if( u.bo.pC->pCursor ){
69763     sqlite3BtreeClearCursor(u.bo.pC->pCursor);
69764   }
69765   break;
69766 }
69767
69768 /* Opcode: Last P1 P2 * * *
69769 **
69770 ** The next use of the Rowid or Column or Next instruction for P1 
69771 ** will refer to the last entry in the database table or index.
69772 ** If the table or index is empty and P2>0, then jump immediately to P2.
69773 ** If P2 is 0 or if the table or index is not empty, fall through
69774 ** to the following instruction.
69775 */
69776 case OP_Last: {        /* jump */
69777 #if 0  /* local variables moved into u.bp */
69778   VdbeCursor *pC;
69779   BtCursor *pCrsr;
69780   int res;
69781 #endif /* local variables moved into u.bp */
69782
69783   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69784   u.bp.pC = p->apCsr[pOp->p1];
69785   assert( u.bp.pC!=0 );
69786   u.bp.pCrsr = u.bp.pC->pCursor;
69787   u.bp.res = 0;
69788   if( ALWAYS(u.bp.pCrsr!=0) ){
69789     rc = sqlite3BtreeLast(u.bp.pCrsr, &u.bp.res);
69790   }
69791   u.bp.pC->nullRow = (u8)u.bp.res;
69792   u.bp.pC->deferredMoveto = 0;
69793   u.bp.pC->rowidIsValid = 0;
69794   u.bp.pC->cacheStatus = CACHE_STALE;
69795   if( pOp->p2>0 && u.bp.res ){
69796     pc = pOp->p2 - 1;
69797   }
69798   break;
69799 }
69800
69801
69802 /* Opcode: Sort P1 P2 * * *
69803 **
69804 ** This opcode does exactly the same thing as OP_Rewind except that
69805 ** it increments an undocumented global variable used for testing.
69806 **
69807 ** Sorting is accomplished by writing records into a sorting index,
69808 ** then rewinding that index and playing it back from beginning to
69809 ** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
69810 ** rewinding so that the global variable will be incremented and
69811 ** regression tests can determine whether or not the optimizer is
69812 ** correctly optimizing out sorts.
69813 */
69814 case OP_SorterSort:    /* jump */
69815 case OP_Sort: {        /* jump */
69816 #ifdef SQLITE_TEST
69817   sqlite3_sort_count++;
69818   sqlite3_search_count--;
69819 #endif
69820   p->aCounter[SQLITE_STMTSTATUS_SORT-1]++;
69821   /* Fall through into OP_Rewind */
69822 }
69823 /* Opcode: Rewind P1 P2 * * *
69824 **
69825 ** The next use of the Rowid or Column or Next instruction for P1 
69826 ** will refer to the first entry in the database table or index.
69827 ** If the table or index is empty and P2>0, then jump immediately to P2.
69828 ** If P2 is 0 or if the table or index is not empty, fall through
69829 ** to the following instruction.
69830 */
69831 case OP_Rewind: {        /* jump */
69832 #if 0  /* local variables moved into u.bq */
69833   VdbeCursor *pC;
69834   BtCursor *pCrsr;
69835   int res;
69836 #endif /* local variables moved into u.bq */
69837
69838   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69839   u.bq.pC = p->apCsr[pOp->p1];
69840   assert( u.bq.pC!=0 );
69841   assert( u.bq.pC->isSorter==(pOp->opcode==OP_SorterSort) );
69842   u.bq.res = 1;
69843   if( isSorter(u.bq.pC) ){
69844     rc = sqlite3VdbeSorterRewind(db, u.bq.pC, &u.bq.res);
69845   }else{
69846     u.bq.pCrsr = u.bq.pC->pCursor;
69847     assert( u.bq.pCrsr );
69848     rc = sqlite3BtreeFirst(u.bq.pCrsr, &u.bq.res);
69849     u.bq.pC->atFirst = u.bq.res==0 ?1:0;
69850     u.bq.pC->deferredMoveto = 0;
69851     u.bq.pC->cacheStatus = CACHE_STALE;
69852     u.bq.pC->rowidIsValid = 0;
69853   }
69854   u.bq.pC->nullRow = (u8)u.bq.res;
69855   assert( pOp->p2>0 && pOp->p2<p->nOp );
69856   if( u.bq.res ){
69857     pc = pOp->p2 - 1;
69858   }
69859   break;
69860 }
69861
69862 /* Opcode: Next P1 P2 * P4 P5
69863 **
69864 ** Advance cursor P1 so that it points to the next key/data pair in its
69865 ** table or index.  If there are no more key/value pairs then fall through
69866 ** to the following instruction.  But if the cursor advance was successful,
69867 ** jump immediately to P2.
69868 **
69869 ** The P1 cursor must be for a real table, not a pseudo-table.
69870 **
69871 ** P4 is always of type P4_ADVANCE. The function pointer points to
69872 ** sqlite3BtreeNext().
69873 **
69874 ** If P5 is positive and the jump is taken, then event counter
69875 ** number P5-1 in the prepared statement is incremented.
69876 **
69877 ** See also: Prev
69878 */
69879 /* Opcode: Prev P1 P2 * * P5
69880 **
69881 ** Back up cursor P1 so that it points to the previous key/data pair in its
69882 ** table or index.  If there is no previous key/value pairs then fall through
69883 ** to the following instruction.  But if the cursor backup was successful,
69884 ** jump immediately to P2.
69885 **
69886 ** The P1 cursor must be for a real table, not a pseudo-table.
69887 **
69888 ** P4 is always of type P4_ADVANCE. The function pointer points to
69889 ** sqlite3BtreePrevious().
69890 **
69891 ** If P5 is positive and the jump is taken, then event counter
69892 ** number P5-1 in the prepared statement is incremented.
69893 */
69894 case OP_SorterNext:    /* jump */
69895 case OP_Prev:          /* jump */
69896 case OP_Next: {        /* jump */
69897 #if 0  /* local variables moved into u.br */
69898   VdbeCursor *pC;
69899   int res;
69900 #endif /* local variables moved into u.br */
69901
69902   CHECK_FOR_INTERRUPT;
69903   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69904   assert( pOp->p5<=ArraySize(p->aCounter) );
69905   u.br.pC = p->apCsr[pOp->p1];
69906   if( u.br.pC==0 ){
69907     break;  /* See ticket #2273 */
69908   }
69909   assert( u.br.pC->isSorter==(pOp->opcode==OP_SorterNext) );
69910   if( isSorter(u.br.pC) ){
69911     assert( pOp->opcode==OP_SorterNext );
69912     rc = sqlite3VdbeSorterNext(db, u.br.pC, &u.br.res);
69913   }else{
69914     u.br.res = 1;
69915     assert( u.br.pC->deferredMoveto==0 );
69916     assert( u.br.pC->pCursor );
69917     assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
69918     assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
69919     rc = pOp->p4.xAdvance(u.br.pC->pCursor, &u.br.res);
69920   }
69921   u.br.pC->nullRow = (u8)u.br.res;
69922   u.br.pC->cacheStatus = CACHE_STALE;
69923   if( u.br.res==0 ){
69924     pc = pOp->p2 - 1;
69925     if( pOp->p5 ) p->aCounter[pOp->p5-1]++;
69926 #ifdef SQLITE_TEST
69927     sqlite3_search_count++;
69928 #endif
69929   }
69930   u.br.pC->rowidIsValid = 0;
69931   break;
69932 }
69933
69934 /* Opcode: IdxInsert P1 P2 P3 * P5
69935 **
69936 ** Register P2 holds an SQL index key made using the
69937 ** MakeRecord instructions.  This opcode writes that key
69938 ** into the index P1.  Data for the entry is nil.
69939 **
69940 ** P3 is a flag that provides a hint to the b-tree layer that this
69941 ** insert is likely to be an append.
69942 **
69943 ** This instruction only works for indices.  The equivalent instruction
69944 ** for tables is OP_Insert.
69945 */
69946 case OP_SorterInsert:       /* in2 */
69947 case OP_IdxInsert: {        /* in2 */
69948 #if 0  /* local variables moved into u.bs */
69949   VdbeCursor *pC;
69950   BtCursor *pCrsr;
69951   int nKey;
69952   const char *zKey;
69953 #endif /* local variables moved into u.bs */
69954
69955   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69956   u.bs.pC = p->apCsr[pOp->p1];
69957   assert( u.bs.pC!=0 );
69958   assert( u.bs.pC->isSorter==(pOp->opcode==OP_SorterInsert) );
69959   pIn2 = &aMem[pOp->p2];
69960   assert( pIn2->flags & MEM_Blob );
69961   u.bs.pCrsr = u.bs.pC->pCursor;
69962   if( ALWAYS(u.bs.pCrsr!=0) ){
69963     assert( u.bs.pC->isTable==0 );
69964     rc = ExpandBlob(pIn2);
69965     if( rc==SQLITE_OK ){
69966       if( isSorter(u.bs.pC) ){
69967         rc = sqlite3VdbeSorterWrite(db, u.bs.pC, pIn2);
69968       }else{
69969         u.bs.nKey = pIn2->n;
69970         u.bs.zKey = pIn2->z;
69971         rc = sqlite3BtreeInsert(u.bs.pCrsr, u.bs.zKey, u.bs.nKey, "", 0, 0, pOp->p3,
69972             ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bs.pC->seekResult : 0)
69973             );
69974         assert( u.bs.pC->deferredMoveto==0 );
69975         u.bs.pC->cacheStatus = CACHE_STALE;
69976       }
69977     }
69978   }
69979   break;
69980 }
69981
69982 /* Opcode: IdxDelete P1 P2 P3 * *
69983 **
69984 ** The content of P3 registers starting at register P2 form
69985 ** an unpacked index key. This opcode removes that entry from the 
69986 ** index opened by cursor P1.
69987 */
69988 case OP_IdxDelete: {
69989 #if 0  /* local variables moved into u.bt */
69990   VdbeCursor *pC;
69991   BtCursor *pCrsr;
69992   int res;
69993   UnpackedRecord r;
69994 #endif /* local variables moved into u.bt */
69995
69996   assert( pOp->p3>0 );
69997   assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem+1 );
69998   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
69999   u.bt.pC = p->apCsr[pOp->p1];
70000   assert( u.bt.pC!=0 );
70001   u.bt.pCrsr = u.bt.pC->pCursor;
70002   if( ALWAYS(u.bt.pCrsr!=0) ){
70003     u.bt.r.pKeyInfo = u.bt.pC->pKeyInfo;
70004     u.bt.r.nField = (u16)pOp->p3;
70005     u.bt.r.flags = 0;
70006     u.bt.r.aMem = &aMem[pOp->p2];
70007 #ifdef SQLITE_DEBUG
70008     { int i; for(i=0; i<u.bt.r.nField; i++) assert( memIsValid(&u.bt.r.aMem[i]) ); }
70009 #endif
70010     rc = sqlite3BtreeMovetoUnpacked(u.bt.pCrsr, &u.bt.r, 0, 0, &u.bt.res);
70011     if( rc==SQLITE_OK && u.bt.res==0 ){
70012       rc = sqlite3BtreeDelete(u.bt.pCrsr);
70013     }
70014     assert( u.bt.pC->deferredMoveto==0 );
70015     u.bt.pC->cacheStatus = CACHE_STALE;
70016   }
70017   break;
70018 }
70019
70020 /* Opcode: IdxRowid P1 P2 * * *
70021 **
70022 ** Write into register P2 an integer which is the last entry in the record at
70023 ** the end of the index key pointed to by cursor P1.  This integer should be
70024 ** the rowid of the table entry to which this index entry points.
70025 **
70026 ** See also: Rowid, MakeRecord.
70027 */
70028 case OP_IdxRowid: {              /* out2-prerelease */
70029 #if 0  /* local variables moved into u.bu */
70030   BtCursor *pCrsr;
70031   VdbeCursor *pC;
70032   i64 rowid;
70033 #endif /* local variables moved into u.bu */
70034
70035   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
70036   u.bu.pC = p->apCsr[pOp->p1];
70037   assert( u.bu.pC!=0 );
70038   u.bu.pCrsr = u.bu.pC->pCursor;
70039   pOut->flags = MEM_Null;
70040   if( ALWAYS(u.bu.pCrsr!=0) ){
70041     rc = sqlite3VdbeCursorMoveto(u.bu.pC);
70042     if( NEVER(rc) ) goto abort_due_to_error;
70043     assert( u.bu.pC->deferredMoveto==0 );
70044     assert( u.bu.pC->isTable==0 );
70045     if( !u.bu.pC->nullRow ){
70046       rc = sqlite3VdbeIdxRowid(db, u.bu.pCrsr, &u.bu.rowid);
70047       if( rc!=SQLITE_OK ){
70048         goto abort_due_to_error;
70049       }
70050       pOut->u.i = u.bu.rowid;
70051       pOut->flags = MEM_Int;
70052     }
70053   }
70054   break;
70055 }
70056
70057 /* Opcode: IdxGE P1 P2 P3 P4 P5
70058 **
70059 ** The P4 register values beginning with P3 form an unpacked index 
70060 ** key that omits the ROWID.  Compare this key value against the index 
70061 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
70062 **
70063 ** If the P1 index entry is greater than or equal to the key value
70064 ** then jump to P2.  Otherwise fall through to the next instruction.
70065 **
70066 ** If P5 is non-zero then the key value is increased by an epsilon 
70067 ** prior to the comparison.  This make the opcode work like IdxGT except
70068 ** that if the key from register P3 is a prefix of the key in the cursor,
70069 ** the result is false whereas it would be true with IdxGT.
70070 */
70071 /* Opcode: IdxLT P1 P2 P3 P4 P5
70072 **
70073 ** The P4 register values beginning with P3 form an unpacked index 
70074 ** key that omits the ROWID.  Compare this key value against the index 
70075 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
70076 **
70077 ** If the P1 index entry is less than the key value then jump to P2.
70078 ** Otherwise fall through to the next instruction.
70079 **
70080 ** If P5 is non-zero then the key value is increased by an epsilon prior 
70081 ** to the comparison.  This makes the opcode work like IdxLE.
70082 */
70083 case OP_IdxLT:          /* jump */
70084 case OP_IdxGE: {        /* jump */
70085 #if 0  /* local variables moved into u.bv */
70086   VdbeCursor *pC;
70087   int res;
70088   UnpackedRecord r;
70089 #endif /* local variables moved into u.bv */
70090
70091   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
70092   u.bv.pC = p->apCsr[pOp->p1];
70093   assert( u.bv.pC!=0 );
70094   assert( u.bv.pC->isOrdered );
70095   if( ALWAYS(u.bv.pC->pCursor!=0) ){
70096     assert( u.bv.pC->deferredMoveto==0 );
70097     assert( pOp->p5==0 || pOp->p5==1 );
70098     assert( pOp->p4type==P4_INT32 );
70099     u.bv.r.pKeyInfo = u.bv.pC->pKeyInfo;
70100     u.bv.r.nField = (u16)pOp->p4.i;
70101     if( pOp->p5 ){
70102       u.bv.r.flags = UNPACKED_INCRKEY | UNPACKED_PREFIX_MATCH;
70103     }else{
70104       u.bv.r.flags = UNPACKED_PREFIX_MATCH;
70105     }
70106     u.bv.r.aMem = &aMem[pOp->p3];
70107 #ifdef SQLITE_DEBUG
70108     { int i; for(i=0; i<u.bv.r.nField; i++) assert( memIsValid(&u.bv.r.aMem[i]) ); }
70109 #endif
70110     rc = sqlite3VdbeIdxKeyCompare(u.bv.pC, &u.bv.r, &u.bv.res);
70111     if( pOp->opcode==OP_IdxLT ){
70112       u.bv.res = -u.bv.res;
70113     }else{
70114       assert( pOp->opcode==OP_IdxGE );
70115       u.bv.res++;
70116     }
70117     if( u.bv.res>0 ){
70118       pc = pOp->p2 - 1 ;
70119     }
70120   }
70121   break;
70122 }
70123
70124 /* Opcode: Destroy P1 P2 P3 * *
70125 **
70126 ** Delete an entire database table or index whose root page in the database
70127 ** file is given by P1.
70128 **
70129 ** The table being destroyed is in the main database file if P3==0.  If
70130 ** P3==1 then the table to be clear is in the auxiliary database file
70131 ** that is used to store tables create using CREATE TEMPORARY TABLE.
70132 **
70133 ** If AUTOVACUUM is enabled then it is possible that another root page
70134 ** might be moved into the newly deleted root page in order to keep all
70135 ** root pages contiguous at the beginning of the database.  The former
70136 ** value of the root page that moved - its value before the move occurred -
70137 ** is stored in register P2.  If no page 
70138 ** movement was required (because the table being dropped was already 
70139 ** the last one in the database) then a zero is stored in register P2.
70140 ** If AUTOVACUUM is disabled then a zero is stored in register P2.
70141 **
70142 ** See also: Clear
70143 */
70144 case OP_Destroy: {     /* out2-prerelease */
70145 #if 0  /* local variables moved into u.bw */
70146   int iMoved;
70147   int iCnt;
70148   Vdbe *pVdbe;
70149   int iDb;
70150 #endif /* local variables moved into u.bw */
70151
70152 #ifndef SQLITE_OMIT_VIRTUALTABLE
70153   u.bw.iCnt = 0;
70154   for(u.bw.pVdbe=db->pVdbe; u.bw.pVdbe; u.bw.pVdbe = u.bw.pVdbe->pNext){
70155     if( u.bw.pVdbe->magic==VDBE_MAGIC_RUN && u.bw.pVdbe->inVtabMethod<2 && u.bw.pVdbe->pc>=0 ){
70156       u.bw.iCnt++;
70157     }
70158   }
70159 #else
70160   u.bw.iCnt = db->activeVdbeCnt;
70161 #endif
70162   pOut->flags = MEM_Null;
70163   if( u.bw.iCnt>1 ){
70164     rc = SQLITE_LOCKED;
70165     p->errorAction = OE_Abort;
70166   }else{
70167     u.bw.iDb = pOp->p3;
70168     assert( u.bw.iCnt==1 );
70169     assert( (p->btreeMask & (((yDbMask)1)<<u.bw.iDb))!=0 );
70170     rc = sqlite3BtreeDropTable(db->aDb[u.bw.iDb].pBt, pOp->p1, &u.bw.iMoved);
70171     pOut->flags = MEM_Int;
70172     pOut->u.i = u.bw.iMoved;
70173 #ifndef SQLITE_OMIT_AUTOVACUUM
70174     if( rc==SQLITE_OK && u.bw.iMoved!=0 ){
70175       sqlite3RootPageMoved(db, u.bw.iDb, u.bw.iMoved, pOp->p1);
70176       /* All OP_Destroy operations occur on the same btree */
70177       assert( resetSchemaOnFault==0 || resetSchemaOnFault==u.bw.iDb+1 );
70178       resetSchemaOnFault = u.bw.iDb+1;
70179     }
70180 #endif
70181   }
70182   break;
70183 }
70184
70185 /* Opcode: Clear P1 P2 P3
70186 **
70187 ** Delete all contents of the database table or index whose root page
70188 ** in the database file is given by P1.  But, unlike Destroy, do not
70189 ** remove the table or index from the database file.
70190 **
70191 ** The table being clear is in the main database file if P2==0.  If
70192 ** P2==1 then the table to be clear is in the auxiliary database file
70193 ** that is used to store tables create using CREATE TEMPORARY TABLE.
70194 **
70195 ** If the P3 value is non-zero, then the table referred to must be an
70196 ** intkey table (an SQL table, not an index). In this case the row change 
70197 ** count is incremented by the number of rows in the table being cleared. 
70198 ** If P3 is greater than zero, then the value stored in register P3 is
70199 ** also incremented by the number of rows in the table being cleared.
70200 **
70201 ** See also: Destroy
70202 */
70203 case OP_Clear: {
70204 #if 0  /* local variables moved into u.bx */
70205   int nChange;
70206 #endif /* local variables moved into u.bx */
70207
70208   u.bx.nChange = 0;
70209   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p2))!=0 );
70210   rc = sqlite3BtreeClearTable(
70211       db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &u.bx.nChange : 0)
70212   );
70213   if( pOp->p3 ){
70214     p->nChange += u.bx.nChange;
70215     if( pOp->p3>0 ){
70216       assert( memIsValid(&aMem[pOp->p3]) );
70217       memAboutToChange(p, &aMem[pOp->p3]);
70218       aMem[pOp->p3].u.i += u.bx.nChange;
70219     }
70220   }
70221   break;
70222 }
70223
70224 /* Opcode: CreateTable P1 P2 * * *
70225 **
70226 ** Allocate a new table in the main database file if P1==0 or in the
70227 ** auxiliary database file if P1==1 or in an attached database if
70228 ** P1>1.  Write the root page number of the new table into
70229 ** register P2
70230 **
70231 ** The difference between a table and an index is this:  A table must
70232 ** have a 4-byte integer key and can have arbitrary data.  An index
70233 ** has an arbitrary key but no data.
70234 **
70235 ** See also: CreateIndex
70236 */
70237 /* Opcode: CreateIndex P1 P2 * * *
70238 **
70239 ** Allocate a new index in the main database file if P1==0 or in the
70240 ** auxiliary database file if P1==1 or in an attached database if
70241 ** P1>1.  Write the root page number of the new table into
70242 ** register P2.
70243 **
70244 ** See documentation on OP_CreateTable for additional information.
70245 */
70246 case OP_CreateIndex:            /* out2-prerelease */
70247 case OP_CreateTable: {          /* out2-prerelease */
70248 #if 0  /* local variables moved into u.by */
70249   int pgno;
70250   int flags;
70251   Db *pDb;
70252 #endif /* local variables moved into u.by */
70253
70254   u.by.pgno = 0;
70255   assert( pOp->p1>=0 && pOp->p1<db->nDb );
70256   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
70257   u.by.pDb = &db->aDb[pOp->p1];
70258   assert( u.by.pDb->pBt!=0 );
70259   if( pOp->opcode==OP_CreateTable ){
70260     /* u.by.flags = BTREE_INTKEY; */
70261     u.by.flags = BTREE_INTKEY;
70262   }else{
70263     u.by.flags = BTREE_BLOBKEY;
70264   }
70265   rc = sqlite3BtreeCreateTable(u.by.pDb->pBt, &u.by.pgno, u.by.flags);
70266   pOut->u.i = u.by.pgno;
70267   break;
70268 }
70269
70270 /* Opcode: ParseSchema P1 * * P4 *
70271 **
70272 ** Read and parse all entries from the SQLITE_MASTER table of database P1
70273 ** that match the WHERE clause P4. 
70274 **
70275 ** This opcode invokes the parser to create a new virtual machine,
70276 ** then runs the new virtual machine.  It is thus a re-entrant opcode.
70277 */
70278 case OP_ParseSchema: {
70279 #if 0  /* local variables moved into u.bz */
70280   int iDb;
70281   const char *zMaster;
70282   char *zSql;
70283   InitData initData;
70284 #endif /* local variables moved into u.bz */
70285
70286   /* Any prepared statement that invokes this opcode will hold mutexes
70287   ** on every btree.  This is a prerequisite for invoking
70288   ** sqlite3InitCallback().
70289   */
70290 #ifdef SQLITE_DEBUG
70291   for(u.bz.iDb=0; u.bz.iDb<db->nDb; u.bz.iDb++){
70292     assert( u.bz.iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[u.bz.iDb].pBt) );
70293   }
70294 #endif
70295
70296   u.bz.iDb = pOp->p1;
70297   assert( u.bz.iDb>=0 && u.bz.iDb<db->nDb );
70298   assert( DbHasProperty(db, u.bz.iDb, DB_SchemaLoaded) );
70299   /* Used to be a conditional */ {
70300     u.bz.zMaster = SCHEMA_TABLE(u.bz.iDb);
70301     u.bz.initData.db = db;
70302     u.bz.initData.iDb = pOp->p1;
70303     u.bz.initData.pzErrMsg = &p->zErrMsg;
70304     u.bz.zSql = sqlite3MPrintf(db,
70305        "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
70306        db->aDb[u.bz.iDb].zName, u.bz.zMaster, pOp->p4.z);
70307     if( u.bz.zSql==0 ){
70308       rc = SQLITE_NOMEM;
70309     }else{
70310       assert( db->init.busy==0 );
70311       db->init.busy = 1;
70312       u.bz.initData.rc = SQLITE_OK;
70313       assert( !db->mallocFailed );
70314       rc = sqlite3_exec(db, u.bz.zSql, sqlite3InitCallback, &u.bz.initData, 0);
70315       if( rc==SQLITE_OK ) rc = u.bz.initData.rc;
70316       sqlite3DbFree(db, u.bz.zSql);
70317       db->init.busy = 0;
70318     }
70319   }
70320   if( rc ) sqlite3ResetAllSchemasOfConnection(db);
70321   if( rc==SQLITE_NOMEM ){
70322     goto no_mem;
70323   }
70324   break;
70325 }
70326
70327 #if !defined(SQLITE_OMIT_ANALYZE)
70328 /* Opcode: LoadAnalysis P1 * * * *
70329 **
70330 ** Read the sqlite_stat1 table for database P1 and load the content
70331 ** of that table into the internal index hash table.  This will cause
70332 ** the analysis to be used when preparing all subsequent queries.
70333 */
70334 case OP_LoadAnalysis: {
70335   assert( pOp->p1>=0 && pOp->p1<db->nDb );
70336   rc = sqlite3AnalysisLoad(db, pOp->p1);
70337   break;  
70338 }
70339 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
70340
70341 /* Opcode: DropTable P1 * * P4 *
70342 **
70343 ** Remove the internal (in-memory) data structures that describe
70344 ** the table named P4 in database P1.  This is called after a table
70345 ** is dropped in order to keep the internal representation of the
70346 ** schema consistent with what is on disk.
70347 */
70348 case OP_DropTable: {
70349   sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
70350   break;
70351 }
70352
70353 /* Opcode: DropIndex P1 * * P4 *
70354 **
70355 ** Remove the internal (in-memory) data structures that describe
70356 ** the index named P4 in database P1.  This is called after an index
70357 ** is dropped in order to keep the internal representation of the
70358 ** schema consistent with what is on disk.
70359 */
70360 case OP_DropIndex: {
70361   sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
70362   break;
70363 }
70364
70365 /* Opcode: DropTrigger P1 * * P4 *
70366 **
70367 ** Remove the internal (in-memory) data structures that describe
70368 ** the trigger named P4 in database P1.  This is called after a trigger
70369 ** is dropped in order to keep the internal representation of the
70370 ** schema consistent with what is on disk.
70371 */
70372 case OP_DropTrigger: {
70373   sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
70374   break;
70375 }
70376
70377
70378 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
70379 /* Opcode: IntegrityCk P1 P2 P3 * P5
70380 **
70381 ** Do an analysis of the currently open database.  Store in
70382 ** register P1 the text of an error message describing any problems.
70383 ** If no problems are found, store a NULL in register P1.
70384 **
70385 ** The register P3 contains the maximum number of allowed errors.
70386 ** At most reg(P3) errors will be reported.
70387 ** In other words, the analysis stops as soon as reg(P1) errors are 
70388 ** seen.  Reg(P1) is updated with the number of errors remaining.
70389 **
70390 ** The root page numbers of all tables in the database are integer
70391 ** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
70392 ** total.
70393 **
70394 ** If P5 is not zero, the check is done on the auxiliary database
70395 ** file, not the main database file.
70396 **
70397 ** This opcode is used to implement the integrity_check pragma.
70398 */
70399 case OP_IntegrityCk: {
70400 #if 0  /* local variables moved into u.ca */
70401   int nRoot;      /* Number of tables to check.  (Number of root pages.) */
70402   int *aRoot;     /* Array of rootpage numbers for tables to be checked */
70403   int j;          /* Loop counter */
70404   int nErr;       /* Number of errors reported */
70405   char *z;        /* Text of the error report */
70406   Mem *pnErr;     /* Register keeping track of errors remaining */
70407 #endif /* local variables moved into u.ca */
70408
70409   u.ca.nRoot = pOp->p2;
70410   assert( u.ca.nRoot>0 );
70411   u.ca.aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(u.ca.nRoot+1) );
70412   if( u.ca.aRoot==0 ) goto no_mem;
70413   assert( pOp->p3>0 && pOp->p3<=p->nMem );
70414   u.ca.pnErr = &aMem[pOp->p3];
70415   assert( (u.ca.pnErr->flags & MEM_Int)!=0 );
70416   assert( (u.ca.pnErr->flags & (MEM_Str|MEM_Blob))==0 );
70417   pIn1 = &aMem[pOp->p1];
70418   for(u.ca.j=0; u.ca.j<u.ca.nRoot; u.ca.j++){
70419     u.ca.aRoot[u.ca.j] = (int)sqlite3VdbeIntValue(&pIn1[u.ca.j]);
70420   }
70421   u.ca.aRoot[u.ca.j] = 0;
70422   assert( pOp->p5<db->nDb );
70423   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p5))!=0 );
70424   u.ca.z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, u.ca.aRoot, u.ca.nRoot,
70425                                  (int)u.ca.pnErr->u.i, &u.ca.nErr);
70426   sqlite3DbFree(db, u.ca.aRoot);
70427   u.ca.pnErr->u.i -= u.ca.nErr;
70428   sqlite3VdbeMemSetNull(pIn1);
70429   if( u.ca.nErr==0 ){
70430     assert( u.ca.z==0 );
70431   }else if( u.ca.z==0 ){
70432     goto no_mem;
70433   }else{
70434     sqlite3VdbeMemSetStr(pIn1, u.ca.z, -1, SQLITE_UTF8, sqlite3_free);
70435   }
70436   UPDATE_MAX_BLOBSIZE(pIn1);
70437   sqlite3VdbeChangeEncoding(pIn1, encoding);
70438   break;
70439 }
70440 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
70441
70442 /* Opcode: RowSetAdd P1 P2 * * *
70443 **
70444 ** Insert the integer value held by register P2 into a boolean index
70445 ** held in register P1.
70446 **
70447 ** An assertion fails if P2 is not an integer.
70448 */
70449 case OP_RowSetAdd: {       /* in1, in2 */
70450   pIn1 = &aMem[pOp->p1];
70451   pIn2 = &aMem[pOp->p2];
70452   assert( (pIn2->flags & MEM_Int)!=0 );
70453   if( (pIn1->flags & MEM_RowSet)==0 ){
70454     sqlite3VdbeMemSetRowSet(pIn1);
70455     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
70456   }
70457   sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
70458   break;
70459 }
70460
70461 /* Opcode: RowSetRead P1 P2 P3 * *
70462 **
70463 ** Extract the smallest value from boolean index P1 and put that value into
70464 ** register P3.  Or, if boolean index P1 is initially empty, leave P3
70465 ** unchanged and jump to instruction P2.
70466 */
70467 case OP_RowSetRead: {       /* jump, in1, out3 */
70468 #if 0  /* local variables moved into u.cb */
70469   i64 val;
70470 #endif /* local variables moved into u.cb */
70471   CHECK_FOR_INTERRUPT;
70472   pIn1 = &aMem[pOp->p1];
70473   if( (pIn1->flags & MEM_RowSet)==0
70474    || sqlite3RowSetNext(pIn1->u.pRowSet, &u.cb.val)==0
70475   ){
70476     /* The boolean index is empty */
70477     sqlite3VdbeMemSetNull(pIn1);
70478     pc = pOp->p2 - 1;
70479   }else{
70480     /* A value was pulled from the index */
70481     sqlite3VdbeMemSetInt64(&aMem[pOp->p3], u.cb.val);
70482   }
70483   break;
70484 }
70485
70486 /* Opcode: RowSetTest P1 P2 P3 P4
70487 **
70488 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
70489 ** contains a RowSet object and that RowSet object contains
70490 ** the value held in P3, jump to register P2. Otherwise, insert the
70491 ** integer in P3 into the RowSet and continue on to the
70492 ** next opcode.
70493 **
70494 ** The RowSet object is optimized for the case where successive sets
70495 ** of integers, where each set contains no duplicates. Each set
70496 ** of values is identified by a unique P4 value. The first set
70497 ** must have P4==0, the final set P4=-1.  P4 must be either -1 or
70498 ** non-negative.  For non-negative values of P4 only the lower 4
70499 ** bits are significant.
70500 **
70501 ** This allows optimizations: (a) when P4==0 there is no need to test
70502 ** the rowset object for P3, as it is guaranteed not to contain it,
70503 ** (b) when P4==-1 there is no need to insert the value, as it will
70504 ** never be tested for, and (c) when a value that is part of set X is
70505 ** inserted, there is no need to search to see if the same value was
70506 ** previously inserted as part of set X (only if it was previously
70507 ** inserted as part of some other set).
70508 */
70509 case OP_RowSetTest: {                     /* jump, in1, in3 */
70510 #if 0  /* local variables moved into u.cc */
70511   int iSet;
70512   int exists;
70513 #endif /* local variables moved into u.cc */
70514
70515   pIn1 = &aMem[pOp->p1];
70516   pIn3 = &aMem[pOp->p3];
70517   u.cc.iSet = pOp->p4.i;
70518   assert( pIn3->flags&MEM_Int );
70519
70520   /* If there is anything other than a rowset object in memory cell P1,
70521   ** delete it now and initialize P1 with an empty rowset
70522   */
70523   if( (pIn1->flags & MEM_RowSet)==0 ){
70524     sqlite3VdbeMemSetRowSet(pIn1);
70525     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
70526   }
70527
70528   assert( pOp->p4type==P4_INT32 );
70529   assert( u.cc.iSet==-1 || u.cc.iSet>=0 );
70530   if( u.cc.iSet ){
70531     u.cc.exists = sqlite3RowSetTest(pIn1->u.pRowSet,
70532                                (u8)(u.cc.iSet>=0 ? u.cc.iSet & 0xf : 0xff),
70533                                pIn3->u.i);
70534     if( u.cc.exists ){
70535       pc = pOp->p2 - 1;
70536       break;
70537     }
70538   }
70539   if( u.cc.iSet>=0 ){
70540     sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
70541   }
70542   break;
70543 }
70544
70545
70546 #ifndef SQLITE_OMIT_TRIGGER
70547
70548 /* Opcode: Program P1 P2 P3 P4 *
70549 **
70550 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM). 
70551 **
70552 ** P1 contains the address of the memory cell that contains the first memory 
70553 ** cell in an array of values used as arguments to the sub-program. P2 
70554 ** contains the address to jump to if the sub-program throws an IGNORE 
70555 ** exception using the RAISE() function. Register P3 contains the address 
70556 ** of a memory cell in this (the parent) VM that is used to allocate the 
70557 ** memory required by the sub-vdbe at runtime.
70558 **
70559 ** P4 is a pointer to the VM containing the trigger program.
70560 */
70561 case OP_Program: {        /* jump */
70562 #if 0  /* local variables moved into u.cd */
70563   int nMem;               /* Number of memory registers for sub-program */
70564   int nByte;              /* Bytes of runtime space required for sub-program */
70565   Mem *pRt;               /* Register to allocate runtime space */
70566   Mem *pMem;              /* Used to iterate through memory cells */
70567   Mem *pEnd;              /* Last memory cell in new array */
70568   VdbeFrame *pFrame;      /* New vdbe frame to execute in */
70569   SubProgram *pProgram;   /* Sub-program to execute */
70570   void *t;                /* Token identifying trigger */
70571 #endif /* local variables moved into u.cd */
70572
70573   u.cd.pProgram = pOp->p4.pProgram;
70574   u.cd.pRt = &aMem[pOp->p3];
70575   assert( u.cd.pProgram->nOp>0 );
70576
70577   /* If the p5 flag is clear, then recursive invocation of triggers is
70578   ** disabled for backwards compatibility (p5 is set if this sub-program
70579   ** is really a trigger, not a foreign key action, and the flag set
70580   ** and cleared by the "PRAGMA recursive_triggers" command is clear).
70581   **
70582   ** It is recursive invocation of triggers, at the SQL level, that is
70583   ** disabled. In some cases a single trigger may generate more than one
70584   ** SubProgram (if the trigger may be executed with more than one different
70585   ** ON CONFLICT algorithm). SubProgram structures associated with a
70586   ** single trigger all have the same value for the SubProgram.token
70587   ** variable.  */
70588   if( pOp->p5 ){
70589     u.cd.t = u.cd.pProgram->token;
70590     for(u.cd.pFrame=p->pFrame; u.cd.pFrame && u.cd.pFrame->token!=u.cd.t; u.cd.pFrame=u.cd.pFrame->pParent);
70591     if( u.cd.pFrame ) break;
70592   }
70593
70594   if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
70595     rc = SQLITE_ERROR;
70596     sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
70597     break;
70598   }
70599
70600   /* Register u.cd.pRt is used to store the memory required to save the state
70601   ** of the current program, and the memory required at runtime to execute
70602   ** the trigger program. If this trigger has been fired before, then u.cd.pRt
70603   ** is already allocated. Otherwise, it must be initialized.  */
70604   if( (u.cd.pRt->flags&MEM_Frame)==0 ){
70605     /* SubProgram.nMem is set to the number of memory cells used by the
70606     ** program stored in SubProgram.aOp. As well as these, one memory
70607     ** cell is required for each cursor used by the program. Set local
70608     ** variable u.cd.nMem (and later, VdbeFrame.nChildMem) to this value.
70609     */
70610     u.cd.nMem = u.cd.pProgram->nMem + u.cd.pProgram->nCsr;
70611     u.cd.nByte = ROUND8(sizeof(VdbeFrame))
70612               + u.cd.nMem * sizeof(Mem)
70613               + u.cd.pProgram->nCsr * sizeof(VdbeCursor *)
70614               + u.cd.pProgram->nOnce * sizeof(u8);
70615     u.cd.pFrame = sqlite3DbMallocZero(db, u.cd.nByte);
70616     if( !u.cd.pFrame ){
70617       goto no_mem;
70618     }
70619     sqlite3VdbeMemRelease(u.cd.pRt);
70620     u.cd.pRt->flags = MEM_Frame;
70621     u.cd.pRt->u.pFrame = u.cd.pFrame;
70622
70623     u.cd.pFrame->v = p;
70624     u.cd.pFrame->nChildMem = u.cd.nMem;
70625     u.cd.pFrame->nChildCsr = u.cd.pProgram->nCsr;
70626     u.cd.pFrame->pc = pc;
70627     u.cd.pFrame->aMem = p->aMem;
70628     u.cd.pFrame->nMem = p->nMem;
70629     u.cd.pFrame->apCsr = p->apCsr;
70630     u.cd.pFrame->nCursor = p->nCursor;
70631     u.cd.pFrame->aOp = p->aOp;
70632     u.cd.pFrame->nOp = p->nOp;
70633     u.cd.pFrame->token = u.cd.pProgram->token;
70634     u.cd.pFrame->aOnceFlag = p->aOnceFlag;
70635     u.cd.pFrame->nOnceFlag = p->nOnceFlag;
70636
70637     u.cd.pEnd = &VdbeFrameMem(u.cd.pFrame)[u.cd.pFrame->nChildMem];
70638     for(u.cd.pMem=VdbeFrameMem(u.cd.pFrame); u.cd.pMem!=u.cd.pEnd; u.cd.pMem++){
70639       u.cd.pMem->flags = MEM_Invalid;
70640       u.cd.pMem->db = db;
70641     }
70642   }else{
70643     u.cd.pFrame = u.cd.pRt->u.pFrame;
70644     assert( u.cd.pProgram->nMem+u.cd.pProgram->nCsr==u.cd.pFrame->nChildMem );
70645     assert( u.cd.pProgram->nCsr==u.cd.pFrame->nChildCsr );
70646     assert( pc==u.cd.pFrame->pc );
70647   }
70648
70649   p->nFrame++;
70650   u.cd.pFrame->pParent = p->pFrame;
70651   u.cd.pFrame->lastRowid = lastRowid;
70652   u.cd.pFrame->nChange = p->nChange;
70653   p->nChange = 0;
70654   p->pFrame = u.cd.pFrame;
70655   p->aMem = aMem = &VdbeFrameMem(u.cd.pFrame)[-1];
70656   p->nMem = u.cd.pFrame->nChildMem;
70657   p->nCursor = (u16)u.cd.pFrame->nChildCsr;
70658   p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
70659   p->aOp = aOp = u.cd.pProgram->aOp;
70660   p->nOp = u.cd.pProgram->nOp;
70661   p->aOnceFlag = (u8 *)&p->apCsr[p->nCursor];
70662   p->nOnceFlag = u.cd.pProgram->nOnce;
70663   pc = -1;
70664   memset(p->aOnceFlag, 0, p->nOnceFlag);
70665
70666   break;
70667 }
70668
70669 /* Opcode: Param P1 P2 * * *
70670 **
70671 ** This opcode is only ever present in sub-programs called via the 
70672 ** OP_Program instruction. Copy a value currently stored in a memory 
70673 ** cell of the calling (parent) frame to cell P2 in the current frames 
70674 ** address space. This is used by trigger programs to access the new.* 
70675 ** and old.* values.
70676 **
70677 ** The address of the cell in the parent frame is determined by adding
70678 ** the value of the P1 argument to the value of the P1 argument to the
70679 ** calling OP_Program instruction.
70680 */
70681 case OP_Param: {           /* out2-prerelease */
70682 #if 0  /* local variables moved into u.ce */
70683   VdbeFrame *pFrame;
70684   Mem *pIn;
70685 #endif /* local variables moved into u.ce */
70686   u.ce.pFrame = p->pFrame;
70687   u.ce.pIn = &u.ce.pFrame->aMem[pOp->p1 + u.ce.pFrame->aOp[u.ce.pFrame->pc].p1];
70688   sqlite3VdbeMemShallowCopy(pOut, u.ce.pIn, MEM_Ephem);
70689   break;
70690 }
70691
70692 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
70693
70694 #ifndef SQLITE_OMIT_FOREIGN_KEY
70695 /* Opcode: FkCounter P1 P2 * * *
70696 **
70697 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
70698 ** If P1 is non-zero, the database constraint counter is incremented 
70699 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the 
70700 ** statement counter is incremented (immediate foreign key constraints).
70701 */
70702 case OP_FkCounter: {
70703   if( pOp->p1 ){
70704     db->nDeferredCons += pOp->p2;
70705   }else{
70706     p->nFkConstraint += pOp->p2;
70707   }
70708   break;
70709 }
70710
70711 /* Opcode: FkIfZero P1 P2 * * *
70712 **
70713 ** This opcode tests if a foreign key constraint-counter is currently zero.
70714 ** If so, jump to instruction P2. Otherwise, fall through to the next 
70715 ** instruction.
70716 **
70717 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
70718 ** is zero (the one that counts deferred constraint violations). If P1 is
70719 ** zero, the jump is taken if the statement constraint-counter is zero
70720 ** (immediate foreign key constraint violations).
70721 */
70722 case OP_FkIfZero: {         /* jump */
70723   if( pOp->p1 ){
70724     if( db->nDeferredCons==0 ) pc = pOp->p2-1;
70725   }else{
70726     if( p->nFkConstraint==0 ) pc = pOp->p2-1;
70727   }
70728   break;
70729 }
70730 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
70731
70732 #ifndef SQLITE_OMIT_AUTOINCREMENT
70733 /* Opcode: MemMax P1 P2 * * *
70734 **
70735 ** P1 is a register in the root frame of this VM (the root frame is
70736 ** different from the current frame if this instruction is being executed
70737 ** within a sub-program). Set the value of register P1 to the maximum of 
70738 ** its current value and the value in register P2.
70739 **
70740 ** This instruction throws an error if the memory cell is not initially
70741 ** an integer.
70742 */
70743 case OP_MemMax: {        /* in2 */
70744 #if 0  /* local variables moved into u.cf */
70745   Mem *pIn1;
70746   VdbeFrame *pFrame;
70747 #endif /* local variables moved into u.cf */
70748   if( p->pFrame ){
70749     for(u.cf.pFrame=p->pFrame; u.cf.pFrame->pParent; u.cf.pFrame=u.cf.pFrame->pParent);
70750     u.cf.pIn1 = &u.cf.pFrame->aMem[pOp->p1];
70751   }else{
70752     u.cf.pIn1 = &aMem[pOp->p1];
70753   }
70754   assert( memIsValid(u.cf.pIn1) );
70755   sqlite3VdbeMemIntegerify(u.cf.pIn1);
70756   pIn2 = &aMem[pOp->p2];
70757   sqlite3VdbeMemIntegerify(pIn2);
70758   if( u.cf.pIn1->u.i<pIn2->u.i){
70759     u.cf.pIn1->u.i = pIn2->u.i;
70760   }
70761   break;
70762 }
70763 #endif /* SQLITE_OMIT_AUTOINCREMENT */
70764
70765 /* Opcode: IfPos P1 P2 * * *
70766 **
70767 ** If the value of register P1 is 1 or greater, jump to P2.
70768 **
70769 ** It is illegal to use this instruction on a register that does
70770 ** not contain an integer.  An assertion fault will result if you try.
70771 */
70772 case OP_IfPos: {        /* jump, in1 */
70773   pIn1 = &aMem[pOp->p1];
70774   assert( pIn1->flags&MEM_Int );
70775   if( pIn1->u.i>0 ){
70776      pc = pOp->p2 - 1;
70777   }
70778   break;
70779 }
70780
70781 /* Opcode: IfNeg P1 P2 * * *
70782 **
70783 ** If the value of register P1 is less than zero, jump to P2. 
70784 **
70785 ** It is illegal to use this instruction on a register that does
70786 ** not contain an integer.  An assertion fault will result if you try.
70787 */
70788 case OP_IfNeg: {        /* jump, in1 */
70789   pIn1 = &aMem[pOp->p1];
70790   assert( pIn1->flags&MEM_Int );
70791   if( pIn1->u.i<0 ){
70792      pc = pOp->p2 - 1;
70793   }
70794   break;
70795 }
70796
70797 /* Opcode: IfZero P1 P2 P3 * *
70798 **
70799 ** The register P1 must contain an integer.  Add literal P3 to the
70800 ** value in register P1.  If the result is exactly 0, jump to P2. 
70801 **
70802 ** It is illegal to use this instruction on a register that does
70803 ** not contain an integer.  An assertion fault will result if you try.
70804 */
70805 case OP_IfZero: {        /* jump, in1 */
70806   pIn1 = &aMem[pOp->p1];
70807   assert( pIn1->flags&MEM_Int );
70808   pIn1->u.i += pOp->p3;
70809   if( pIn1->u.i==0 ){
70810      pc = pOp->p2 - 1;
70811   }
70812   break;
70813 }
70814
70815 /* Opcode: AggStep * P2 P3 P4 P5
70816 **
70817 ** Execute the step function for an aggregate.  The
70818 ** function has P5 arguments.   P4 is a pointer to the FuncDef
70819 ** structure that specifies the function.  Use register
70820 ** P3 as the accumulator.
70821 **
70822 ** The P5 arguments are taken from register P2 and its
70823 ** successors.
70824 */
70825 case OP_AggStep: {
70826 #if 0  /* local variables moved into u.cg */
70827   int n;
70828   int i;
70829   Mem *pMem;
70830   Mem *pRec;
70831   sqlite3_context ctx;
70832   sqlite3_value **apVal;
70833 #endif /* local variables moved into u.cg */
70834
70835   u.cg.n = pOp->p5;
70836   assert( u.cg.n>=0 );
70837   u.cg.pRec = &aMem[pOp->p2];
70838   u.cg.apVal = p->apArg;
70839   assert( u.cg.apVal || u.cg.n==0 );
70840   for(u.cg.i=0; u.cg.i<u.cg.n; u.cg.i++, u.cg.pRec++){
70841     assert( memIsValid(u.cg.pRec) );
70842     u.cg.apVal[u.cg.i] = u.cg.pRec;
70843     memAboutToChange(p, u.cg.pRec);
70844     sqlite3VdbeMemStoreType(u.cg.pRec);
70845   }
70846   u.cg.ctx.pFunc = pOp->p4.pFunc;
70847   assert( pOp->p3>0 && pOp->p3<=p->nMem );
70848   u.cg.ctx.pMem = u.cg.pMem = &aMem[pOp->p3];
70849   u.cg.pMem->n++;
70850   u.cg.ctx.s.flags = MEM_Null;
70851   u.cg.ctx.s.z = 0;
70852   u.cg.ctx.s.zMalloc = 0;
70853   u.cg.ctx.s.xDel = 0;
70854   u.cg.ctx.s.db = db;
70855   u.cg.ctx.isError = 0;
70856   u.cg.ctx.pColl = 0;
70857   u.cg.ctx.skipFlag = 0;
70858   if( u.cg.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
70859     assert( pOp>p->aOp );
70860     assert( pOp[-1].p4type==P4_COLLSEQ );
70861     assert( pOp[-1].opcode==OP_CollSeq );
70862     u.cg.ctx.pColl = pOp[-1].p4.pColl;
70863   }
70864   (u.cg.ctx.pFunc->xStep)(&u.cg.ctx, u.cg.n, u.cg.apVal); /* IMP: R-24505-23230 */
70865   if( u.cg.ctx.isError ){
70866     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.cg.ctx.s));
70867     rc = u.cg.ctx.isError;
70868   }
70869   if( u.cg.ctx.skipFlag ){
70870     assert( pOp[-1].opcode==OP_CollSeq );
70871     u.cg.i = pOp[-1].p1;
70872     if( u.cg.i ) sqlite3VdbeMemSetInt64(&aMem[u.cg.i], 1);
70873   }
70874
70875   sqlite3VdbeMemRelease(&u.cg.ctx.s);
70876
70877   break;
70878 }
70879
70880 /* Opcode: AggFinal P1 P2 * P4 *
70881 **
70882 ** Execute the finalizer function for an aggregate.  P1 is
70883 ** the memory location that is the accumulator for the aggregate.
70884 **
70885 ** P2 is the number of arguments that the step function takes and
70886 ** P4 is a pointer to the FuncDef for this function.  The P2
70887 ** argument is not used by this opcode.  It is only there to disambiguate
70888 ** functions that can take varying numbers of arguments.  The
70889 ** P4 argument is only needed for the degenerate case where
70890 ** the step function was not previously called.
70891 */
70892 case OP_AggFinal: {
70893 #if 0  /* local variables moved into u.ch */
70894   Mem *pMem;
70895 #endif /* local variables moved into u.ch */
70896   assert( pOp->p1>0 && pOp->p1<=p->nMem );
70897   u.ch.pMem = &aMem[pOp->p1];
70898   assert( (u.ch.pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
70899   rc = sqlite3VdbeMemFinalize(u.ch.pMem, pOp->p4.pFunc);
70900   if( rc ){
70901     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(u.ch.pMem));
70902   }
70903   sqlite3VdbeChangeEncoding(u.ch.pMem, encoding);
70904   UPDATE_MAX_BLOBSIZE(u.ch.pMem);
70905   if( sqlite3VdbeMemTooBig(u.ch.pMem) ){
70906     goto too_big;
70907   }
70908   break;
70909 }
70910
70911 #ifndef SQLITE_OMIT_WAL
70912 /* Opcode: Checkpoint P1 P2 P3 * *
70913 **
70914 ** Checkpoint database P1. This is a no-op if P1 is not currently in
70915 ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL
70916 ** or RESTART.  Write 1 or 0 into mem[P3] if the checkpoint returns
70917 ** SQLITE_BUSY or not, respectively.  Write the number of pages in the
70918 ** WAL after the checkpoint into mem[P3+1] and the number of pages
70919 ** in the WAL that have been checkpointed after the checkpoint
70920 ** completes into mem[P3+2].  However on an error, mem[P3+1] and
70921 ** mem[P3+2] are initialized to -1.
70922 */
70923 case OP_Checkpoint: {
70924 #if 0  /* local variables moved into u.ci */
70925   int i;                          /* Loop counter */
70926   int aRes[3];                    /* Results */
70927   Mem *pMem;                      /* Write results here */
70928 #endif /* local variables moved into u.ci */
70929
70930   u.ci.aRes[0] = 0;
70931   u.ci.aRes[1] = u.ci.aRes[2] = -1;
70932   assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
70933        || pOp->p2==SQLITE_CHECKPOINT_FULL
70934        || pOp->p2==SQLITE_CHECKPOINT_RESTART
70935   );
70936   rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &u.ci.aRes[1], &u.ci.aRes[2]);
70937   if( rc==SQLITE_BUSY ){
70938     rc = SQLITE_OK;
70939     u.ci.aRes[0] = 1;
70940   }
70941   for(u.ci.i=0, u.ci.pMem = &aMem[pOp->p3]; u.ci.i<3; u.ci.i++, u.ci.pMem++){
70942     sqlite3VdbeMemSetInt64(u.ci.pMem, (i64)u.ci.aRes[u.ci.i]);
70943   }
70944   break;
70945 };  
70946 #endif
70947
70948 #ifndef SQLITE_OMIT_PRAGMA
70949 /* Opcode: JournalMode P1 P2 P3 * P5
70950 **
70951 ** Change the journal mode of database P1 to P3. P3 must be one of the
70952 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
70953 ** modes (delete, truncate, persist, off and memory), this is a simple
70954 ** operation. No IO is required.
70955 **
70956 ** If changing into or out of WAL mode the procedure is more complicated.
70957 **
70958 ** Write a string containing the final journal-mode to register P2.
70959 */
70960 case OP_JournalMode: {    /* out2-prerelease */
70961 #if 0  /* local variables moved into u.cj */
70962   Btree *pBt;                     /* Btree to change journal mode of */
70963   Pager *pPager;                  /* Pager associated with pBt */
70964   int eNew;                       /* New journal mode */
70965   int eOld;                       /* The old journal mode */
70966 #ifndef SQLITE_OMIT_WAL
70967   const char *zFilename;          /* Name of database file for pPager */
70968 #endif
70969 #endif /* local variables moved into u.cj */
70970
70971   u.cj.eNew = pOp->p3;
70972   assert( u.cj.eNew==PAGER_JOURNALMODE_DELETE
70973        || u.cj.eNew==PAGER_JOURNALMODE_TRUNCATE
70974        || u.cj.eNew==PAGER_JOURNALMODE_PERSIST
70975        || u.cj.eNew==PAGER_JOURNALMODE_OFF
70976        || u.cj.eNew==PAGER_JOURNALMODE_MEMORY
70977        || u.cj.eNew==PAGER_JOURNALMODE_WAL
70978        || u.cj.eNew==PAGER_JOURNALMODE_QUERY
70979   );
70980   assert( pOp->p1>=0 && pOp->p1<db->nDb );
70981
70982   u.cj.pBt = db->aDb[pOp->p1].pBt;
70983   u.cj.pPager = sqlite3BtreePager(u.cj.pBt);
70984   u.cj.eOld = sqlite3PagerGetJournalMode(u.cj.pPager);
70985   if( u.cj.eNew==PAGER_JOURNALMODE_QUERY ) u.cj.eNew = u.cj.eOld;
70986   if( !sqlite3PagerOkToChangeJournalMode(u.cj.pPager) ) u.cj.eNew = u.cj.eOld;
70987
70988 #ifndef SQLITE_OMIT_WAL
70989   u.cj.zFilename = sqlite3PagerFilename(u.cj.pPager, 1);
70990
70991   /* Do not allow a transition to journal_mode=WAL for a database
70992   ** in temporary storage or if the VFS does not support shared memory
70993   */
70994   if( u.cj.eNew==PAGER_JOURNALMODE_WAL
70995    && (sqlite3Strlen30(u.cj.zFilename)==0           /* Temp file */
70996        || !sqlite3PagerWalSupported(u.cj.pPager))   /* No shared-memory support */
70997   ){
70998     u.cj.eNew = u.cj.eOld;
70999   }
71000
71001   if( (u.cj.eNew!=u.cj.eOld)
71002    && (u.cj.eOld==PAGER_JOURNALMODE_WAL || u.cj.eNew==PAGER_JOURNALMODE_WAL)
71003   ){
71004     if( !db->autoCommit || db->activeVdbeCnt>1 ){
71005       rc = SQLITE_ERROR;
71006       sqlite3SetString(&p->zErrMsg, db,
71007           "cannot change %s wal mode from within a transaction",
71008           (u.cj.eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
71009       );
71010       break;
71011     }else{
71012
71013       if( u.cj.eOld==PAGER_JOURNALMODE_WAL ){
71014         /* If leaving WAL mode, close the log file. If successful, the call
71015         ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
71016         ** file. An EXCLUSIVE lock may still be held on the database file
71017         ** after a successful return.
71018         */
71019         rc = sqlite3PagerCloseWal(u.cj.pPager);
71020         if( rc==SQLITE_OK ){
71021           sqlite3PagerSetJournalMode(u.cj.pPager, u.cj.eNew);
71022         }
71023       }else if( u.cj.eOld==PAGER_JOURNALMODE_MEMORY ){
71024         /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
71025         ** as an intermediate */
71026         sqlite3PagerSetJournalMode(u.cj.pPager, PAGER_JOURNALMODE_OFF);
71027       }
71028
71029       /* Open a transaction on the database file. Regardless of the journal
71030       ** mode, this transaction always uses a rollback journal.
71031       */
71032       assert( sqlite3BtreeIsInTrans(u.cj.pBt)==0 );
71033       if( rc==SQLITE_OK ){
71034         rc = sqlite3BtreeSetVersion(u.cj.pBt, (u.cj.eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
71035       }
71036     }
71037   }
71038 #endif /* ifndef SQLITE_OMIT_WAL */
71039
71040   if( rc ){
71041     u.cj.eNew = u.cj.eOld;
71042   }
71043   u.cj.eNew = sqlite3PagerSetJournalMode(u.cj.pPager, u.cj.eNew);
71044
71045   pOut = &aMem[pOp->p2];
71046   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
71047   pOut->z = (char *)sqlite3JournalModename(u.cj.eNew);
71048   pOut->n = sqlite3Strlen30(pOut->z);
71049   pOut->enc = SQLITE_UTF8;
71050   sqlite3VdbeChangeEncoding(pOut, encoding);
71051   break;
71052 };
71053 #endif /* SQLITE_OMIT_PRAGMA */
71054
71055 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
71056 /* Opcode: Vacuum * * * * *
71057 **
71058 ** Vacuum the entire database.  This opcode will cause other virtual
71059 ** machines to be created and run.  It may not be called from within
71060 ** a transaction.
71061 */
71062 case OP_Vacuum: {
71063   rc = sqlite3RunVacuum(&p->zErrMsg, db);
71064   break;
71065 }
71066 #endif
71067
71068 #if !defined(SQLITE_OMIT_AUTOVACUUM)
71069 /* Opcode: IncrVacuum P1 P2 * * *
71070 **
71071 ** Perform a single step of the incremental vacuum procedure on
71072 ** the P1 database. If the vacuum has finished, jump to instruction
71073 ** P2. Otherwise, fall through to the next instruction.
71074 */
71075 case OP_IncrVacuum: {        /* jump */
71076 #if 0  /* local variables moved into u.ck */
71077   Btree *pBt;
71078 #endif /* local variables moved into u.ck */
71079
71080   assert( pOp->p1>=0 && pOp->p1<db->nDb );
71081   assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
71082   u.ck.pBt = db->aDb[pOp->p1].pBt;
71083   rc = sqlite3BtreeIncrVacuum(u.ck.pBt);
71084   if( rc==SQLITE_DONE ){
71085     pc = pOp->p2 - 1;
71086     rc = SQLITE_OK;
71087   }
71088   break;
71089 }
71090 #endif
71091
71092 /* Opcode: Expire P1 * * * *
71093 **
71094 ** Cause precompiled statements to become expired. An expired statement
71095 ** fails with an error code of SQLITE_SCHEMA if it is ever executed 
71096 ** (via sqlite3_step()).
71097 ** 
71098 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
71099 ** then only the currently executing statement is affected. 
71100 */
71101 case OP_Expire: {
71102   if( !pOp->p1 ){
71103     sqlite3ExpirePreparedStatements(db);
71104   }else{
71105     p->expired = 1;
71106   }
71107   break;
71108 }
71109
71110 #ifndef SQLITE_OMIT_SHARED_CACHE
71111 /* Opcode: TableLock P1 P2 P3 P4 *
71112 **
71113 ** Obtain a lock on a particular table. This instruction is only used when
71114 ** the shared-cache feature is enabled. 
71115 **
71116 ** P1 is the index of the database in sqlite3.aDb[] of the database
71117 ** on which the lock is acquired.  A readlock is obtained if P3==0 or
71118 ** a write lock if P3==1.
71119 **
71120 ** P2 contains the root-page of the table to lock.
71121 **
71122 ** P4 contains a pointer to the name of the table being locked. This is only
71123 ** used to generate an error message if the lock cannot be obtained.
71124 */
71125 case OP_TableLock: {
71126   u8 isWriteLock = (u8)pOp->p3;
71127   if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
71128     int p1 = pOp->p1; 
71129     assert( p1>=0 && p1<db->nDb );
71130     assert( (p->btreeMask & (((yDbMask)1)<<p1))!=0 );
71131     assert( isWriteLock==0 || isWriteLock==1 );
71132     rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
71133     if( (rc&0xFF)==SQLITE_LOCKED ){
71134       const char *z = pOp->p4.z;
71135       sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
71136     }
71137   }
71138   break;
71139 }
71140 #endif /* SQLITE_OMIT_SHARED_CACHE */
71141
71142 #ifndef SQLITE_OMIT_VIRTUALTABLE
71143 /* Opcode: VBegin * * * P4 *
71144 **
71145 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the 
71146 ** xBegin method for that table.
71147 **
71148 ** Also, whether or not P4 is set, check that this is not being called from
71149 ** within a callback to a virtual table xSync() method. If it is, the error
71150 ** code will be set to SQLITE_LOCKED.
71151 */
71152 case OP_VBegin: {
71153 #if 0  /* local variables moved into u.cl */
71154   VTable *pVTab;
71155 #endif /* local variables moved into u.cl */
71156   u.cl.pVTab = pOp->p4.pVtab;
71157   rc = sqlite3VtabBegin(db, u.cl.pVTab);
71158   if( u.cl.pVTab ) importVtabErrMsg(p, u.cl.pVTab->pVtab);
71159   break;
71160 }
71161 #endif /* SQLITE_OMIT_VIRTUALTABLE */
71162
71163 #ifndef SQLITE_OMIT_VIRTUALTABLE
71164 /* Opcode: VCreate P1 * * P4 *
71165 **
71166 ** P4 is the name of a virtual table in database P1. Call the xCreate method
71167 ** for that table.
71168 */
71169 case OP_VCreate: {
71170   rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
71171   break;
71172 }
71173 #endif /* SQLITE_OMIT_VIRTUALTABLE */
71174
71175 #ifndef SQLITE_OMIT_VIRTUALTABLE
71176 /* Opcode: VDestroy P1 * * P4 *
71177 **
71178 ** P4 is the name of a virtual table in database P1.  Call the xDestroy method
71179 ** of that table.
71180 */
71181 case OP_VDestroy: {
71182   p->inVtabMethod = 2;
71183   rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
71184   p->inVtabMethod = 0;
71185   break;
71186 }
71187 #endif /* SQLITE_OMIT_VIRTUALTABLE */
71188
71189 #ifndef SQLITE_OMIT_VIRTUALTABLE
71190 /* Opcode: VOpen P1 * * P4 *
71191 **
71192 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
71193 ** P1 is a cursor number.  This opcode opens a cursor to the virtual
71194 ** table and stores that cursor in P1.
71195 */
71196 case OP_VOpen: {
71197 #if 0  /* local variables moved into u.cm */
71198   VdbeCursor *pCur;
71199   sqlite3_vtab_cursor *pVtabCursor;
71200   sqlite3_vtab *pVtab;
71201   sqlite3_module *pModule;
71202 #endif /* local variables moved into u.cm */
71203
71204   u.cm.pCur = 0;
71205   u.cm.pVtabCursor = 0;
71206   u.cm.pVtab = pOp->p4.pVtab->pVtab;
71207   u.cm.pModule = (sqlite3_module *)u.cm.pVtab->pModule;
71208   assert(u.cm.pVtab && u.cm.pModule);
71209   rc = u.cm.pModule->xOpen(u.cm.pVtab, &u.cm.pVtabCursor);
71210   importVtabErrMsg(p, u.cm.pVtab);
71211   if( SQLITE_OK==rc ){
71212     /* Initialize sqlite3_vtab_cursor base class */
71213     u.cm.pVtabCursor->pVtab = u.cm.pVtab;
71214
71215     /* Initialize vdbe cursor object */
71216     u.cm.pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
71217     if( u.cm.pCur ){
71218       u.cm.pCur->pVtabCursor = u.cm.pVtabCursor;
71219       u.cm.pCur->pModule = u.cm.pVtabCursor->pVtab->pModule;
71220     }else{
71221       db->mallocFailed = 1;
71222       u.cm.pModule->xClose(u.cm.pVtabCursor);
71223     }
71224   }
71225   break;
71226 }
71227 #endif /* SQLITE_OMIT_VIRTUALTABLE */
71228
71229 #ifndef SQLITE_OMIT_VIRTUALTABLE
71230 /* Opcode: VFilter P1 P2 P3 P4 *
71231 **
71232 ** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
71233 ** the filtered result set is empty.
71234 **
71235 ** P4 is either NULL or a string that was generated by the xBestIndex
71236 ** method of the module.  The interpretation of the P4 string is left
71237 ** to the module implementation.
71238 **
71239 ** This opcode invokes the xFilter method on the virtual table specified
71240 ** by P1.  The integer query plan parameter to xFilter is stored in register
71241 ** P3. Register P3+1 stores the argc parameter to be passed to the
71242 ** xFilter method. Registers P3+2..P3+1+argc are the argc
71243 ** additional parameters which are passed to
71244 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
71245 **
71246 ** A jump is made to P2 if the result set after filtering would be empty.
71247 */
71248 case OP_VFilter: {   /* jump */
71249 #if 0  /* local variables moved into u.cn */
71250   int nArg;
71251   int iQuery;
71252   const sqlite3_module *pModule;
71253   Mem *pQuery;
71254   Mem *pArgc;
71255   sqlite3_vtab_cursor *pVtabCursor;
71256   sqlite3_vtab *pVtab;
71257   VdbeCursor *pCur;
71258   int res;
71259   int i;
71260   Mem **apArg;
71261 #endif /* local variables moved into u.cn */
71262
71263   u.cn.pQuery = &aMem[pOp->p3];
71264   u.cn.pArgc = &u.cn.pQuery[1];
71265   u.cn.pCur = p->apCsr[pOp->p1];
71266   assert( memIsValid(u.cn.pQuery) );
71267   REGISTER_TRACE(pOp->p3, u.cn.pQuery);
71268   assert( u.cn.pCur->pVtabCursor );
71269   u.cn.pVtabCursor = u.cn.pCur->pVtabCursor;
71270   u.cn.pVtab = u.cn.pVtabCursor->pVtab;
71271   u.cn.pModule = u.cn.pVtab->pModule;
71272
71273   /* Grab the index number and argc parameters */
71274   assert( (u.cn.pQuery->flags&MEM_Int)!=0 && u.cn.pArgc->flags==MEM_Int );
71275   u.cn.nArg = (int)u.cn.pArgc->u.i;
71276   u.cn.iQuery = (int)u.cn.pQuery->u.i;
71277
71278   /* Invoke the xFilter method */
71279   {
71280     u.cn.res = 0;
71281     u.cn.apArg = p->apArg;
71282     for(u.cn.i = 0; u.cn.i<u.cn.nArg; u.cn.i++){
71283       u.cn.apArg[u.cn.i] = &u.cn.pArgc[u.cn.i+1];
71284       sqlite3VdbeMemStoreType(u.cn.apArg[u.cn.i]);
71285     }
71286
71287     p->inVtabMethod = 1;
71288     rc = u.cn.pModule->xFilter(u.cn.pVtabCursor, u.cn.iQuery, pOp->p4.z, u.cn.nArg, u.cn.apArg);
71289     p->inVtabMethod = 0;
71290     importVtabErrMsg(p, u.cn.pVtab);
71291     if( rc==SQLITE_OK ){
71292       u.cn.res = u.cn.pModule->xEof(u.cn.pVtabCursor);
71293     }
71294
71295     if( u.cn.res ){
71296       pc = pOp->p2 - 1;
71297     }
71298   }
71299   u.cn.pCur->nullRow = 0;
71300
71301   break;
71302 }
71303 #endif /* SQLITE_OMIT_VIRTUALTABLE */
71304
71305 #ifndef SQLITE_OMIT_VIRTUALTABLE
71306 /* Opcode: VColumn P1 P2 P3 * *
71307 **
71308 ** Store the value of the P2-th column of
71309 ** the row of the virtual-table that the 
71310 ** P1 cursor is pointing to into register P3.
71311 */
71312 case OP_VColumn: {
71313 #if 0  /* local variables moved into u.co */
71314   sqlite3_vtab *pVtab;
71315   const sqlite3_module *pModule;
71316   Mem *pDest;
71317   sqlite3_context sContext;
71318 #endif /* local variables moved into u.co */
71319
71320   VdbeCursor *pCur = p->apCsr[pOp->p1];
71321   assert( pCur->pVtabCursor );
71322   assert( pOp->p3>0 && pOp->p3<=p->nMem );
71323   u.co.pDest = &aMem[pOp->p3];
71324   memAboutToChange(p, u.co.pDest);
71325   if( pCur->nullRow ){
71326     sqlite3VdbeMemSetNull(u.co.pDest);
71327     break;
71328   }
71329   u.co.pVtab = pCur->pVtabCursor->pVtab;
71330   u.co.pModule = u.co.pVtab->pModule;
71331   assert( u.co.pModule->xColumn );
71332   memset(&u.co.sContext, 0, sizeof(u.co.sContext));
71333
71334   /* The output cell may already have a buffer allocated. Move
71335   ** the current contents to u.co.sContext.s so in case the user-function
71336   ** can use the already allocated buffer instead of allocating a
71337   ** new one.
71338   */
71339   sqlite3VdbeMemMove(&u.co.sContext.s, u.co.pDest);
71340   MemSetTypeFlag(&u.co.sContext.s, MEM_Null);
71341
71342   rc = u.co.pModule->xColumn(pCur->pVtabCursor, &u.co.sContext, pOp->p2);
71343   importVtabErrMsg(p, u.co.pVtab);
71344   if( u.co.sContext.isError ){
71345     rc = u.co.sContext.isError;
71346   }
71347
71348   /* Copy the result of the function to the P3 register. We
71349   ** do this regardless of whether or not an error occurred to ensure any
71350   ** dynamic allocation in u.co.sContext.s (a Mem struct) is  released.
71351   */
71352   sqlite3VdbeChangeEncoding(&u.co.sContext.s, encoding);
71353   sqlite3VdbeMemMove(u.co.pDest, &u.co.sContext.s);
71354   REGISTER_TRACE(pOp->p3, u.co.pDest);
71355   UPDATE_MAX_BLOBSIZE(u.co.pDest);
71356
71357   if( sqlite3VdbeMemTooBig(u.co.pDest) ){
71358     goto too_big;
71359   }
71360   break;
71361 }
71362 #endif /* SQLITE_OMIT_VIRTUALTABLE */
71363
71364 #ifndef SQLITE_OMIT_VIRTUALTABLE
71365 /* Opcode: VNext P1 P2 * * *
71366 **
71367 ** Advance virtual table P1 to the next row in its result set and
71368 ** jump to instruction P2.  Or, if the virtual table has reached
71369 ** the end of its result set, then fall through to the next instruction.
71370 */
71371 case OP_VNext: {   /* jump */
71372 #if 0  /* local variables moved into u.cp */
71373   sqlite3_vtab *pVtab;
71374   const sqlite3_module *pModule;
71375   int res;
71376   VdbeCursor *pCur;
71377 #endif /* local variables moved into u.cp */
71378
71379   u.cp.res = 0;
71380   u.cp.pCur = p->apCsr[pOp->p1];
71381   assert( u.cp.pCur->pVtabCursor );
71382   if( u.cp.pCur->nullRow ){
71383     break;
71384   }
71385   u.cp.pVtab = u.cp.pCur->pVtabCursor->pVtab;
71386   u.cp.pModule = u.cp.pVtab->pModule;
71387   assert( u.cp.pModule->xNext );
71388
71389   /* Invoke the xNext() method of the module. There is no way for the
71390   ** underlying implementation to return an error if one occurs during
71391   ** xNext(). Instead, if an error occurs, true is returned (indicating that
71392   ** data is available) and the error code returned when xColumn or
71393   ** some other method is next invoked on the save virtual table cursor.
71394   */
71395   p->inVtabMethod = 1;
71396   rc = u.cp.pModule->xNext(u.cp.pCur->pVtabCursor);
71397   p->inVtabMethod = 0;
71398   importVtabErrMsg(p, u.cp.pVtab);
71399   if( rc==SQLITE_OK ){
71400     u.cp.res = u.cp.pModule->xEof(u.cp.pCur->pVtabCursor);
71401   }
71402
71403   if( !u.cp.res ){
71404     /* If there is data, jump to P2 */
71405     pc = pOp->p2 - 1;
71406   }
71407   break;
71408 }
71409 #endif /* SQLITE_OMIT_VIRTUALTABLE */
71410
71411 #ifndef SQLITE_OMIT_VIRTUALTABLE
71412 /* Opcode: VRename P1 * * P4 *
71413 **
71414 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
71415 ** This opcode invokes the corresponding xRename method. The value
71416 ** in register P1 is passed as the zName argument to the xRename method.
71417 */
71418 case OP_VRename: {
71419 #if 0  /* local variables moved into u.cq */
71420   sqlite3_vtab *pVtab;
71421   Mem *pName;
71422 #endif /* local variables moved into u.cq */
71423
71424   u.cq.pVtab = pOp->p4.pVtab->pVtab;
71425   u.cq.pName = &aMem[pOp->p1];
71426   assert( u.cq.pVtab->pModule->xRename );
71427   assert( memIsValid(u.cq.pName) );
71428   REGISTER_TRACE(pOp->p1, u.cq.pName);
71429   assert( u.cq.pName->flags & MEM_Str );
71430   testcase( u.cq.pName->enc==SQLITE_UTF8 );
71431   testcase( u.cq.pName->enc==SQLITE_UTF16BE );
71432   testcase( u.cq.pName->enc==SQLITE_UTF16LE );
71433   rc = sqlite3VdbeChangeEncoding(u.cq.pName, SQLITE_UTF8);
71434   if( rc==SQLITE_OK ){
71435     rc = u.cq.pVtab->pModule->xRename(u.cq.pVtab, u.cq.pName->z);
71436     importVtabErrMsg(p, u.cq.pVtab);
71437     p->expired = 0;
71438   }
71439   break;
71440 }
71441 #endif
71442
71443 #ifndef SQLITE_OMIT_VIRTUALTABLE
71444 /* Opcode: VUpdate P1 P2 P3 P4 *
71445 **
71446 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
71447 ** This opcode invokes the corresponding xUpdate method. P2 values
71448 ** are contiguous memory cells starting at P3 to pass to the xUpdate 
71449 ** invocation. The value in register (P3+P2-1) corresponds to the 
71450 ** p2th element of the argv array passed to xUpdate.
71451 **
71452 ** The xUpdate method will do a DELETE or an INSERT or both.
71453 ** The argv[0] element (which corresponds to memory cell P3)
71454 ** is the rowid of a row to delete.  If argv[0] is NULL then no 
71455 ** deletion occurs.  The argv[1] element is the rowid of the new 
71456 ** row.  This can be NULL to have the virtual table select the new 
71457 ** rowid for itself.  The subsequent elements in the array are 
71458 ** the values of columns in the new row.
71459 **
71460 ** If P2==1 then no insert is performed.  argv[0] is the rowid of
71461 ** a row to delete.
71462 **
71463 ** P1 is a boolean flag. If it is set to true and the xUpdate call
71464 ** is successful, then the value returned by sqlite3_last_insert_rowid() 
71465 ** is set to the value of the rowid for the row just inserted.
71466 */
71467 case OP_VUpdate: {
71468 #if 0  /* local variables moved into u.cr */
71469   sqlite3_vtab *pVtab;
71470   sqlite3_module *pModule;
71471   int nArg;
71472   int i;
71473   sqlite_int64 rowid;
71474   Mem **apArg;
71475   Mem *pX;
71476 #endif /* local variables moved into u.cr */
71477
71478   assert( pOp->p2==1        || pOp->p5==OE_Fail   || pOp->p5==OE_Rollback
71479        || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
71480   );
71481   u.cr.pVtab = pOp->p4.pVtab->pVtab;
71482   u.cr.pModule = (sqlite3_module *)u.cr.pVtab->pModule;
71483   u.cr.nArg = pOp->p2;
71484   assert( pOp->p4type==P4_VTAB );
71485   if( ALWAYS(u.cr.pModule->xUpdate) ){
71486     u8 vtabOnConflict = db->vtabOnConflict;
71487     u.cr.apArg = p->apArg;
71488     u.cr.pX = &aMem[pOp->p3];
71489     for(u.cr.i=0; u.cr.i<u.cr.nArg; u.cr.i++){
71490       assert( memIsValid(u.cr.pX) );
71491       memAboutToChange(p, u.cr.pX);
71492       sqlite3VdbeMemStoreType(u.cr.pX);
71493       u.cr.apArg[u.cr.i] = u.cr.pX;
71494       u.cr.pX++;
71495     }
71496     db->vtabOnConflict = pOp->p5;
71497     rc = u.cr.pModule->xUpdate(u.cr.pVtab, u.cr.nArg, u.cr.apArg, &u.cr.rowid);
71498     db->vtabOnConflict = vtabOnConflict;
71499     importVtabErrMsg(p, u.cr.pVtab);
71500     if( rc==SQLITE_OK && pOp->p1 ){
71501       assert( u.cr.nArg>1 && u.cr.apArg[0] && (u.cr.apArg[0]->flags&MEM_Null) );
71502       db->lastRowid = lastRowid = u.cr.rowid;
71503     }
71504     if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
71505       if( pOp->p5==OE_Ignore ){
71506         rc = SQLITE_OK;
71507       }else{
71508         p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
71509       }
71510     }else{
71511       p->nChange++;
71512     }
71513   }
71514   break;
71515 }
71516 #endif /* SQLITE_OMIT_VIRTUALTABLE */
71517
71518 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
71519 /* Opcode: Pagecount P1 P2 * * *
71520 **
71521 ** Write the current number of pages in database P1 to memory cell P2.
71522 */
71523 case OP_Pagecount: {            /* out2-prerelease */
71524   pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
71525   break;
71526 }
71527 #endif
71528
71529
71530 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
71531 /* Opcode: MaxPgcnt P1 P2 P3 * *
71532 **
71533 ** Try to set the maximum page count for database P1 to the value in P3.
71534 ** Do not let the maximum page count fall below the current page count and
71535 ** do not change the maximum page count value if P3==0.
71536 **
71537 ** Store the maximum page count after the change in register P2.
71538 */
71539 case OP_MaxPgcnt: {            /* out2-prerelease */
71540   unsigned int newMax;
71541   Btree *pBt;
71542
71543   pBt = db->aDb[pOp->p1].pBt;
71544   newMax = 0;
71545   if( pOp->p3 ){
71546     newMax = sqlite3BtreeLastPage(pBt);
71547     if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
71548   }
71549   pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
71550   break;
71551 }
71552 #endif
71553
71554
71555 #ifndef SQLITE_OMIT_TRACE
71556 /* Opcode: Trace * * * P4 *
71557 **
71558 ** If tracing is enabled (by the sqlite3_trace()) interface, then
71559 ** the UTF-8 string contained in P4 is emitted on the trace callback.
71560 */
71561 case OP_Trace: {
71562 #if 0  /* local variables moved into u.cs */
71563   char *zTrace;
71564   char *z;
71565 #endif /* local variables moved into u.cs */
71566
71567   if( db->xTrace
71568    && !p->doingRerun
71569    && (u.cs.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
71570   ){
71571     u.cs.z = sqlite3VdbeExpandSql(p, u.cs.zTrace);
71572     db->xTrace(db->pTraceArg, u.cs.z);
71573     sqlite3DbFree(db, u.cs.z);
71574   }
71575 #ifdef SQLITE_DEBUG
71576   if( (db->flags & SQLITE_SqlTrace)!=0
71577    && (u.cs.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
71578   ){
71579     sqlite3DebugPrintf("SQL-trace: %s\n", u.cs.zTrace);
71580   }
71581 #endif /* SQLITE_DEBUG */
71582   break;
71583 }
71584 #endif
71585
71586
71587 /* Opcode: Noop * * * * *
71588 **
71589 ** Do nothing.  This instruction is often useful as a jump
71590 ** destination.
71591 */
71592 /*
71593 ** The magic Explain opcode are only inserted when explain==2 (which
71594 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
71595 ** This opcode records information from the optimizer.  It is the
71596 ** the same as a no-op.  This opcodesnever appears in a real VM program.
71597 */
71598 default: {          /* This is really OP_Noop and OP_Explain */
71599   assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
71600   break;
71601 }
71602
71603 /*****************************************************************************
71604 ** The cases of the switch statement above this line should all be indented
71605 ** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
71606 ** readability.  From this point on down, the normal indentation rules are
71607 ** restored.
71608 *****************************************************************************/
71609     }
71610
71611 #ifdef VDBE_PROFILE
71612     {
71613       u64 elapsed = sqlite3Hwtime() - start;
71614       pOp->cycles += elapsed;
71615       pOp->cnt++;
71616 #if 0
71617         fprintf(stdout, "%10llu ", elapsed);
71618         sqlite3VdbePrintOp(stdout, origPc, &aOp[origPc]);
71619 #endif
71620     }
71621 #endif
71622
71623     /* The following code adds nothing to the actual functionality
71624     ** of the program.  It is only here for testing and debugging.
71625     ** On the other hand, it does burn CPU cycles every time through
71626     ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
71627     */
71628 #ifndef NDEBUG
71629     assert( pc>=-1 && pc<p->nOp );
71630
71631 #ifdef SQLITE_DEBUG
71632     if( p->trace ){
71633       if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
71634       if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
71635         registerTrace(p->trace, pOp->p2, &aMem[pOp->p2]);
71636       }
71637       if( pOp->opflags & OPFLG_OUT3 ){
71638         registerTrace(p->trace, pOp->p3, &aMem[pOp->p3]);
71639       }
71640     }
71641 #endif  /* SQLITE_DEBUG */
71642 #endif  /* NDEBUG */
71643   }  /* The end of the for(;;) loop the loops through opcodes */
71644
71645   /* If we reach this point, it means that execution is finished with
71646   ** an error of some kind.
71647   */
71648 vdbe_error_halt:
71649   assert( rc );
71650   p->rc = rc;
71651   testcase( sqlite3GlobalConfig.xLog!=0 );
71652   sqlite3_log(rc, "statement aborts at %d: [%s] %s", 
71653                    pc, p->zSql, p->zErrMsg);
71654   sqlite3VdbeHalt(p);
71655   if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
71656   rc = SQLITE_ERROR;
71657   if( resetSchemaOnFault>0 ){
71658     sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
71659   }
71660
71661   /* This is the only way out of this procedure.  We have to
71662   ** release the mutexes on btrees that were acquired at the
71663   ** top. */
71664 vdbe_return:
71665   db->lastRowid = lastRowid;
71666   sqlite3VdbeLeave(p);
71667   return rc;
71668
71669   /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
71670   ** is encountered.
71671   */
71672 too_big:
71673   sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
71674   rc = SQLITE_TOOBIG;
71675   goto vdbe_error_halt;
71676
71677   /* Jump to here if a malloc() fails.
71678   */
71679 no_mem:
71680   db->mallocFailed = 1;
71681   sqlite3SetString(&p->zErrMsg, db, "out of memory");
71682   rc = SQLITE_NOMEM;
71683   goto vdbe_error_halt;
71684
71685   /* Jump to here for any other kind of fatal error.  The "rc" variable
71686   ** should hold the error number.
71687   */
71688 abort_due_to_error:
71689   assert( p->zErrMsg==0 );
71690   if( db->mallocFailed ) rc = SQLITE_NOMEM;
71691   if( rc!=SQLITE_IOERR_NOMEM ){
71692     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
71693   }
71694   goto vdbe_error_halt;
71695
71696   /* Jump to here if the sqlite3_interrupt() API sets the interrupt
71697   ** flag.
71698   */
71699 abort_due_to_interrupt:
71700   assert( db->u1.isInterrupted );
71701   rc = SQLITE_INTERRUPT;
71702   p->rc = rc;
71703   sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
71704   goto vdbe_error_halt;
71705 }
71706
71707 /************** End of vdbe.c ************************************************/
71708 /************** Begin file vdbeblob.c ****************************************/
71709 /*
71710 ** 2007 May 1
71711 **
71712 ** The author disclaims copyright to this source code.  In place of
71713 ** a legal notice, here is a blessing:
71714 **
71715 **    May you do good and not evil.
71716 **    May you find forgiveness for yourself and forgive others.
71717 **    May you share freely, never taking more than you give.
71718 **
71719 *************************************************************************
71720 **
71721 ** This file contains code used to implement incremental BLOB I/O.
71722 */
71723
71724
71725 #ifndef SQLITE_OMIT_INCRBLOB
71726
71727 /*
71728 ** Valid sqlite3_blob* handles point to Incrblob structures.
71729 */
71730 typedef struct Incrblob Incrblob;
71731 struct Incrblob {
71732   int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
71733   int nByte;              /* Size of open blob, in bytes */
71734   int iOffset;            /* Byte offset of blob in cursor data */
71735   int iCol;               /* Table column this handle is open on */
71736   BtCursor *pCsr;         /* Cursor pointing at blob row */
71737   sqlite3_stmt *pStmt;    /* Statement holding cursor open */
71738   sqlite3 *db;            /* The associated database */
71739 };
71740
71741
71742 /*
71743 ** This function is used by both blob_open() and blob_reopen(). It seeks
71744 ** the b-tree cursor associated with blob handle p to point to row iRow.
71745 ** If successful, SQLITE_OK is returned and subsequent calls to
71746 ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
71747 **
71748 ** If an error occurs, or if the specified row does not exist or does not
71749 ** contain a value of type TEXT or BLOB in the column nominated when the
71750 ** blob handle was opened, then an error code is returned and *pzErr may
71751 ** be set to point to a buffer containing an error message. It is the
71752 ** responsibility of the caller to free the error message buffer using
71753 ** sqlite3DbFree().
71754 **
71755 ** If an error does occur, then the b-tree cursor is closed. All subsequent
71756 ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will 
71757 ** immediately return SQLITE_ABORT.
71758 */
71759 static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
71760   int rc;                         /* Error code */
71761   char *zErr = 0;                 /* Error message */
71762   Vdbe *v = (Vdbe *)p->pStmt;
71763
71764   /* Set the value of the SQL statements only variable to integer iRow. 
71765   ** This is done directly instead of using sqlite3_bind_int64() to avoid 
71766   ** triggering asserts related to mutexes.
71767   */
71768   assert( v->aVar[0].flags&MEM_Int );
71769   v->aVar[0].u.i = iRow;
71770
71771   rc = sqlite3_step(p->pStmt);
71772   if( rc==SQLITE_ROW ){
71773     u32 type = v->apCsr[0]->aType[p->iCol];
71774     if( type<12 ){
71775       zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
71776           type==0?"null": type==7?"real": "integer"
71777       );
71778       rc = SQLITE_ERROR;
71779       sqlite3_finalize(p->pStmt);
71780       p->pStmt = 0;
71781     }else{
71782       p->iOffset = v->apCsr[0]->aOffset[p->iCol];
71783       p->nByte = sqlite3VdbeSerialTypeLen(type);
71784       p->pCsr =  v->apCsr[0]->pCursor;
71785       sqlite3BtreeEnterCursor(p->pCsr);
71786       sqlite3BtreeCacheOverflow(p->pCsr);
71787       sqlite3BtreeLeaveCursor(p->pCsr);
71788     }
71789   }
71790
71791   if( rc==SQLITE_ROW ){
71792     rc = SQLITE_OK;
71793   }else if( p->pStmt ){
71794     rc = sqlite3_finalize(p->pStmt);
71795     p->pStmt = 0;
71796     if( rc==SQLITE_OK ){
71797       zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
71798       rc = SQLITE_ERROR;
71799     }else{
71800       zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
71801     }
71802   }
71803
71804   assert( rc!=SQLITE_OK || zErr==0 );
71805   assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
71806
71807   *pzErr = zErr;
71808   return rc;
71809 }
71810
71811 /*
71812 ** Open a blob handle.
71813 */
71814 SQLITE_API int sqlite3_blob_open(
71815   sqlite3* db,            /* The database connection */
71816   const char *zDb,        /* The attached database containing the blob */
71817   const char *zTable,     /* The table containing the blob */
71818   const char *zColumn,    /* The column containing the blob */
71819   sqlite_int64 iRow,      /* The row containing the glob */
71820   int flags,              /* True -> read/write access, false -> read-only */
71821   sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
71822 ){
71823   int nAttempt = 0;
71824   int iCol;               /* Index of zColumn in row-record */
71825
71826   /* This VDBE program seeks a btree cursor to the identified 
71827   ** db/table/row entry. The reason for using a vdbe program instead
71828   ** of writing code to use the b-tree layer directly is that the
71829   ** vdbe program will take advantage of the various transaction,
71830   ** locking and error handling infrastructure built into the vdbe.
71831   **
71832   ** After seeking the cursor, the vdbe executes an OP_ResultRow.
71833   ** Code external to the Vdbe then "borrows" the b-tree cursor and
71834   ** uses it to implement the blob_read(), blob_write() and 
71835   ** blob_bytes() functions.
71836   **
71837   ** The sqlite3_blob_close() function finalizes the vdbe program,
71838   ** which closes the b-tree cursor and (possibly) commits the 
71839   ** transaction.
71840   */
71841   static const VdbeOpList openBlob[] = {
71842     {OP_Transaction, 0, 0, 0},     /* 0: Start a transaction */
71843     {OP_VerifyCookie, 0, 0, 0},    /* 1: Check the schema cookie */
71844     {OP_TableLock, 0, 0, 0},       /* 2: Acquire a read or write lock */
71845
71846     /* One of the following two instructions is replaced by an OP_Noop. */
71847     {OP_OpenRead, 0, 0, 0},        /* 3: Open cursor 0 for reading */
71848     {OP_OpenWrite, 0, 0, 0},       /* 4: Open cursor 0 for read/write */
71849
71850     {OP_Variable, 1, 1, 1},        /* 5: Push the rowid to the stack */
71851     {OP_NotExists, 0, 10, 1},      /* 6: Seek the cursor */
71852     {OP_Column, 0, 0, 1},          /* 7  */
71853     {OP_ResultRow, 1, 0, 0},       /* 8  */
71854     {OP_Goto, 0, 5, 0},            /* 9  */
71855     {OP_Close, 0, 0, 0},           /* 10 */
71856     {OP_Halt, 0, 0, 0},            /* 11 */
71857   };
71858
71859   int rc = SQLITE_OK;
71860   char *zErr = 0;
71861   Table *pTab;
71862   Parse *pParse = 0;
71863   Incrblob *pBlob = 0;
71864
71865   flags = !!flags;                /* flags = (flags ? 1 : 0); */
71866   *ppBlob = 0;
71867
71868   sqlite3_mutex_enter(db->mutex);
71869
71870   pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
71871   if( !pBlob ) goto blob_open_out;
71872   pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
71873   if( !pParse ) goto blob_open_out;
71874
71875   do {
71876     memset(pParse, 0, sizeof(Parse));
71877     pParse->db = db;
71878     sqlite3DbFree(db, zErr);
71879     zErr = 0;
71880
71881     sqlite3BtreeEnterAll(db);
71882     pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
71883     if( pTab && IsVirtual(pTab) ){
71884       pTab = 0;
71885       sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
71886     }
71887 #ifndef SQLITE_OMIT_VIEW
71888     if( pTab && pTab->pSelect ){
71889       pTab = 0;
71890       sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
71891     }
71892 #endif
71893     if( !pTab ){
71894       if( pParse->zErrMsg ){
71895         sqlite3DbFree(db, zErr);
71896         zErr = pParse->zErrMsg;
71897         pParse->zErrMsg = 0;
71898       }
71899       rc = SQLITE_ERROR;
71900       sqlite3BtreeLeaveAll(db);
71901       goto blob_open_out;
71902     }
71903
71904     /* Now search pTab for the exact column. */
71905     for(iCol=0; iCol<pTab->nCol; iCol++) {
71906       if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
71907         break;
71908       }
71909     }
71910     if( iCol==pTab->nCol ){
71911       sqlite3DbFree(db, zErr);
71912       zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
71913       rc = SQLITE_ERROR;
71914       sqlite3BtreeLeaveAll(db);
71915       goto blob_open_out;
71916     }
71917
71918     /* If the value is being opened for writing, check that the
71919     ** column is not indexed, and that it is not part of a foreign key. 
71920     ** It is against the rules to open a column to which either of these
71921     ** descriptions applies for writing.  */
71922     if( flags ){
71923       const char *zFault = 0;
71924       Index *pIdx;
71925 #ifndef SQLITE_OMIT_FOREIGN_KEY
71926       if( db->flags&SQLITE_ForeignKeys ){
71927         /* Check that the column is not part of an FK child key definition. It
71928         ** is not necessary to check if it is part of a parent key, as parent
71929         ** key columns must be indexed. The check below will pick up this 
71930         ** case.  */
71931         FKey *pFKey;
71932         for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
71933           int j;
71934           for(j=0; j<pFKey->nCol; j++){
71935             if( pFKey->aCol[j].iFrom==iCol ){
71936               zFault = "foreign key";
71937             }
71938           }
71939         }
71940       }
71941 #endif
71942       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
71943         int j;
71944         for(j=0; j<pIdx->nColumn; j++){
71945           if( pIdx->aiColumn[j]==iCol ){
71946             zFault = "indexed";
71947           }
71948         }
71949       }
71950       if( zFault ){
71951         sqlite3DbFree(db, zErr);
71952         zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
71953         rc = SQLITE_ERROR;
71954         sqlite3BtreeLeaveAll(db);
71955         goto blob_open_out;
71956       }
71957     }
71958
71959     pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(db);
71960     assert( pBlob->pStmt || db->mallocFailed );
71961     if( pBlob->pStmt ){
71962       Vdbe *v = (Vdbe *)pBlob->pStmt;
71963       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
71964
71965       sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
71966
71967
71968       /* Configure the OP_Transaction */
71969       sqlite3VdbeChangeP1(v, 0, iDb);
71970       sqlite3VdbeChangeP2(v, 0, flags);
71971
71972       /* Configure the OP_VerifyCookie */
71973       sqlite3VdbeChangeP1(v, 1, iDb);
71974       sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
71975       sqlite3VdbeChangeP3(v, 1, pTab->pSchema->iGeneration);
71976
71977       /* Make sure a mutex is held on the table to be accessed */
71978       sqlite3VdbeUsesBtree(v, iDb); 
71979
71980       /* Configure the OP_TableLock instruction */
71981 #ifdef SQLITE_OMIT_SHARED_CACHE
71982       sqlite3VdbeChangeToNoop(v, 2);
71983 #else
71984       sqlite3VdbeChangeP1(v, 2, iDb);
71985       sqlite3VdbeChangeP2(v, 2, pTab->tnum);
71986       sqlite3VdbeChangeP3(v, 2, flags);
71987       sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
71988 #endif
71989
71990       /* Remove either the OP_OpenWrite or OpenRead. Set the P2 
71991       ** parameter of the other to pTab->tnum.  */
71992       sqlite3VdbeChangeToNoop(v, 4 - flags);
71993       sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum);
71994       sqlite3VdbeChangeP3(v, 3 + flags, iDb);
71995
71996       /* Configure the number of columns. Configure the cursor to
71997       ** think that the table has one more column than it really
71998       ** does. An OP_Column to retrieve this imaginary column will
71999       ** always return an SQL NULL. This is useful because it means
72000       ** we can invoke OP_Column to fill in the vdbe cursors type 
72001       ** and offset cache without causing any IO.
72002       */
72003       sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
72004       sqlite3VdbeChangeP2(v, 7, pTab->nCol);
72005       if( !db->mallocFailed ){
72006         pParse->nVar = 1;
72007         pParse->nMem = 1;
72008         pParse->nTab = 1;
72009         sqlite3VdbeMakeReady(v, pParse);
72010       }
72011     }
72012    
72013     pBlob->flags = flags;
72014     pBlob->iCol = iCol;
72015     pBlob->db = db;
72016     sqlite3BtreeLeaveAll(db);
72017     if( db->mallocFailed ){
72018       goto blob_open_out;
72019     }
72020     sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
72021     rc = blobSeekToRow(pBlob, iRow, &zErr);
72022   } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
72023
72024 blob_open_out:
72025   if( rc==SQLITE_OK && db->mallocFailed==0 ){
72026     *ppBlob = (sqlite3_blob *)pBlob;
72027   }else{
72028     if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
72029     sqlite3DbFree(db, pBlob);
72030   }
72031   sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
72032   sqlite3DbFree(db, zErr);
72033   sqlite3StackFree(db, pParse);
72034   rc = sqlite3ApiExit(db, rc);
72035   sqlite3_mutex_leave(db->mutex);
72036   return rc;
72037 }
72038
72039 /*
72040 ** Close a blob handle that was previously created using
72041 ** sqlite3_blob_open().
72042 */
72043 SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
72044   Incrblob *p = (Incrblob *)pBlob;
72045   int rc;
72046   sqlite3 *db;
72047
72048   if( p ){
72049     db = p->db;
72050     sqlite3_mutex_enter(db->mutex);
72051     rc = sqlite3_finalize(p->pStmt);
72052     sqlite3DbFree(db, p);
72053     sqlite3_mutex_leave(db->mutex);
72054   }else{
72055     rc = SQLITE_OK;
72056   }
72057   return rc;
72058 }
72059
72060 /*
72061 ** Perform a read or write operation on a blob
72062 */
72063 static int blobReadWrite(
72064   sqlite3_blob *pBlob, 
72065   void *z, 
72066   int n, 
72067   int iOffset, 
72068   int (*xCall)(BtCursor*, u32, u32, void*)
72069 ){
72070   int rc;
72071   Incrblob *p = (Incrblob *)pBlob;
72072   Vdbe *v;
72073   sqlite3 *db;
72074
72075   if( p==0 ) return SQLITE_MISUSE_BKPT;
72076   db = p->db;
72077   sqlite3_mutex_enter(db->mutex);
72078   v = (Vdbe*)p->pStmt;
72079
72080   if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
72081     /* Request is out of range. Return a transient error. */
72082     rc = SQLITE_ERROR;
72083     sqlite3Error(db, SQLITE_ERROR, 0);
72084   }else if( v==0 ){
72085     /* If there is no statement handle, then the blob-handle has
72086     ** already been invalidated. Return SQLITE_ABORT in this case.
72087     */
72088     rc = SQLITE_ABORT;
72089   }else{
72090     /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
72091     ** returned, clean-up the statement handle.
72092     */
72093     assert( db == v->db );
72094     sqlite3BtreeEnterCursor(p->pCsr);
72095     rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
72096     sqlite3BtreeLeaveCursor(p->pCsr);
72097     if( rc==SQLITE_ABORT ){
72098       sqlite3VdbeFinalize(v);
72099       p->pStmt = 0;
72100     }else{
72101       db->errCode = rc;
72102       v->rc = rc;
72103     }
72104   }
72105   rc = sqlite3ApiExit(db, rc);
72106   sqlite3_mutex_leave(db->mutex);
72107   return rc;
72108 }
72109
72110 /*
72111 ** Read data from a blob handle.
72112 */
72113 SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
72114   return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
72115 }
72116
72117 /*
72118 ** Write data to a blob handle.
72119 */
72120 SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
72121   return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
72122 }
72123
72124 /*
72125 ** Query a blob handle for the size of the data.
72126 **
72127 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
72128 ** so no mutex is required for access.
72129 */
72130 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
72131   Incrblob *p = (Incrblob *)pBlob;
72132   return (p && p->pStmt) ? p->nByte : 0;
72133 }
72134
72135 /*
72136 ** Move an existing blob handle to point to a different row of the same
72137 ** database table.
72138 **
72139 ** If an error occurs, or if the specified row does not exist or does not
72140 ** contain a blob or text value, then an error code is returned and the
72141 ** database handle error code and message set. If this happens, then all 
72142 ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close()) 
72143 ** immediately return SQLITE_ABORT.
72144 */
72145 SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
72146   int rc;
72147   Incrblob *p = (Incrblob *)pBlob;
72148   sqlite3 *db;
72149
72150   if( p==0 ) return SQLITE_MISUSE_BKPT;
72151   db = p->db;
72152   sqlite3_mutex_enter(db->mutex);
72153
72154   if( p->pStmt==0 ){
72155     /* If there is no statement handle, then the blob-handle has
72156     ** already been invalidated. Return SQLITE_ABORT in this case.
72157     */
72158     rc = SQLITE_ABORT;
72159   }else{
72160     char *zErr;
72161     rc = blobSeekToRow(p, iRow, &zErr);
72162     if( rc!=SQLITE_OK ){
72163       sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
72164       sqlite3DbFree(db, zErr);
72165     }
72166     assert( rc!=SQLITE_SCHEMA );
72167   }
72168
72169   rc = sqlite3ApiExit(db, rc);
72170   assert( rc==SQLITE_OK || p->pStmt==0 );
72171   sqlite3_mutex_leave(db->mutex);
72172   return rc;
72173 }
72174
72175 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
72176
72177 /************** End of vdbeblob.c ********************************************/
72178 /************** Begin file vdbesort.c ****************************************/
72179 /*
72180 ** 2011 July 9
72181 **
72182 ** The author disclaims copyright to this source code.  In place of
72183 ** a legal notice, here is a blessing:
72184 **
72185 **    May you do good and not evil.
72186 **    May you find forgiveness for yourself and forgive others.
72187 **    May you share freely, never taking more than you give.
72188 **
72189 *************************************************************************
72190 ** This file contains code for the VdbeSorter object, used in concert with
72191 ** a VdbeCursor to sort large numbers of keys (as may be required, for
72192 ** example, by CREATE INDEX statements on tables too large to fit in main
72193 ** memory).
72194 */
72195
72196
72197
72198 typedef struct VdbeSorterIter VdbeSorterIter;
72199 typedef struct SorterRecord SorterRecord;
72200 typedef struct FileWriter FileWriter;
72201
72202 /*
72203 ** NOTES ON DATA STRUCTURE USED FOR N-WAY MERGES:
72204 **
72205 ** As keys are added to the sorter, they are written to disk in a series
72206 ** of sorted packed-memory-arrays (PMAs). The size of each PMA is roughly
72207 ** the same as the cache-size allowed for temporary databases. In order
72208 ** to allow the caller to extract keys from the sorter in sorted order,
72209 ** all PMAs currently stored on disk must be merged together. This comment
72210 ** describes the data structure used to do so. The structure supports 
72211 ** merging any number of arrays in a single pass with no redundant comparison 
72212 ** operations.
72213 **
72214 ** The aIter[] array contains an iterator for each of the PMAs being merged.
72215 ** An aIter[] iterator either points to a valid key or else is at EOF. For 
72216 ** the purposes of the paragraphs below, we assume that the array is actually 
72217 ** N elements in size, where N is the smallest power of 2 greater to or equal 
72218 ** to the number of iterators being merged. The extra aIter[] elements are 
72219 ** treated as if they are empty (always at EOF).
72220 **
72221 ** The aTree[] array is also N elements in size. The value of N is stored in
72222 ** the VdbeSorter.nTree variable.
72223 **
72224 ** The final (N/2) elements of aTree[] contain the results of comparing
72225 ** pairs of iterator keys together. Element i contains the result of 
72226 ** comparing aIter[2*i-N] and aIter[2*i-N+1]. Whichever key is smaller, the
72227 ** aTree element is set to the index of it. 
72228 **
72229 ** For the purposes of this comparison, EOF is considered greater than any
72230 ** other key value. If the keys are equal (only possible with two EOF
72231 ** values), it doesn't matter which index is stored.
72232 **
72233 ** The (N/4) elements of aTree[] that preceed the final (N/2) described 
72234 ** above contains the index of the smallest of each block of 4 iterators.
72235 ** And so on. So that aTree[1] contains the index of the iterator that 
72236 ** currently points to the smallest key value. aTree[0] is unused.
72237 **
72238 ** Example:
72239 **
72240 **     aIter[0] -> Banana
72241 **     aIter[1] -> Feijoa
72242 **     aIter[2] -> Elderberry
72243 **     aIter[3] -> Currant
72244 **     aIter[4] -> Grapefruit
72245 **     aIter[5] -> Apple
72246 **     aIter[6] -> Durian
72247 **     aIter[7] -> EOF
72248 **
72249 **     aTree[] = { X, 5   0, 5    0, 3, 5, 6 }
72250 **
72251 ** The current element is "Apple" (the value of the key indicated by 
72252 ** iterator 5). When the Next() operation is invoked, iterator 5 will
72253 ** be advanced to the next key in its segment. Say the next key is
72254 ** "Eggplant":
72255 **
72256 **     aIter[5] -> Eggplant
72257 **
72258 ** The contents of aTree[] are updated first by comparing the new iterator
72259 ** 5 key to the current key of iterator 4 (still "Grapefruit"). The iterator
72260 ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
72261 ** The value of iterator 6 - "Durian" - is now smaller than that of iterator
72262 ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
72263 ** so the value written into element 1 of the array is 0. As follows:
72264 **
72265 **     aTree[] = { X, 0   0, 6    0, 3, 5, 6 }
72266 **
72267 ** In other words, each time we advance to the next sorter element, log2(N)
72268 ** key comparison operations are required, where N is the number of segments
72269 ** being merged (rounded up to the next power of 2).
72270 */
72271 struct VdbeSorter {
72272   i64 iWriteOff;                  /* Current write offset within file pTemp1 */
72273   i64 iReadOff;                   /* Current read offset within file pTemp1 */
72274   int nInMemory;                  /* Current size of pRecord list as PMA */
72275   int nTree;                      /* Used size of aTree/aIter (power of 2) */
72276   int nPMA;                       /* Number of PMAs stored in pTemp1 */
72277   int mnPmaSize;                  /* Minimum PMA size, in bytes */
72278   int mxPmaSize;                  /* Maximum PMA size, in bytes.  0==no limit */
72279   VdbeSorterIter *aIter;          /* Array of iterators to merge */
72280   int *aTree;                     /* Current state of incremental merge */
72281   sqlite3_file *pTemp1;           /* PMA file 1 */
72282   SorterRecord *pRecord;          /* Head of in-memory record list */
72283   UnpackedRecord *pUnpacked;      /* Used to unpack keys */
72284 };
72285
72286 /*
72287 ** The following type is an iterator for a PMA. It caches the current key in 
72288 ** variables nKey/aKey. If the iterator is at EOF, pFile==0.
72289 */
72290 struct VdbeSorterIter {
72291   i64 iReadOff;                   /* Current read offset */
72292   i64 iEof;                       /* 1 byte past EOF for this iterator */
72293   int nAlloc;                     /* Bytes of space at aAlloc */
72294   int nKey;                       /* Number of bytes in key */
72295   sqlite3_file *pFile;            /* File iterator is reading from */
72296   u8 *aAlloc;                     /* Allocated space */
72297   u8 *aKey;                       /* Pointer to current key */
72298   u8 *aBuffer;                    /* Current read buffer */
72299   int nBuffer;                    /* Size of read buffer in bytes */
72300 };
72301
72302 /*
72303 ** An instance of this structure is used to organize the stream of records
72304 ** being written to files by the merge-sort code into aligned, page-sized
72305 ** blocks.  Doing all I/O in aligned page-sized blocks helps I/O to go
72306 ** faster on many operating systems.
72307 */
72308 struct FileWriter {
72309   int eFWErr;                     /* Non-zero if in an error state */
72310   u8 *aBuffer;                    /* Pointer to write buffer */
72311   int nBuffer;                    /* Size of write buffer in bytes */
72312   int iBufStart;                  /* First byte of buffer to write */
72313   int iBufEnd;                    /* Last byte of buffer to write */
72314   i64 iWriteOff;                  /* Offset of start of buffer in file */
72315   sqlite3_file *pFile;            /* File to write to */
72316 };
72317
72318 /*
72319 ** A structure to store a single record. All in-memory records are connected
72320 ** together into a linked list headed at VdbeSorter.pRecord using the 
72321 ** SorterRecord.pNext pointer.
72322 */
72323 struct SorterRecord {
72324   void *pVal;
72325   int nVal;
72326   SorterRecord *pNext;
72327 };
72328
72329 /* Minimum allowable value for the VdbeSorter.nWorking variable */
72330 #define SORTER_MIN_WORKING 10
72331
72332 /* Maximum number of segments to merge in a single pass. */
72333 #define SORTER_MAX_MERGE_COUNT 16
72334
72335 /*
72336 ** Free all memory belonging to the VdbeSorterIter object passed as the second
72337 ** argument. All structure fields are set to zero before returning.
72338 */
72339 static void vdbeSorterIterZero(sqlite3 *db, VdbeSorterIter *pIter){
72340   sqlite3DbFree(db, pIter->aAlloc);
72341   sqlite3DbFree(db, pIter->aBuffer);
72342   memset(pIter, 0, sizeof(VdbeSorterIter));
72343 }
72344
72345 /*
72346 ** Read nByte bytes of data from the stream of data iterated by object p.
72347 ** If successful, set *ppOut to point to a buffer containing the data
72348 ** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
72349 ** error code.
72350 **
72351 ** The buffer indicated by *ppOut may only be considered valid until the
72352 ** next call to this function.
72353 */
72354 static int vdbeSorterIterRead(
72355   sqlite3 *db,                    /* Database handle (for malloc) */
72356   VdbeSorterIter *p,              /* Iterator */
72357   int nByte,                      /* Bytes of data to read */
72358   u8 **ppOut                      /* OUT: Pointer to buffer containing data */
72359 ){
72360   int iBuf;                       /* Offset within buffer to read from */
72361   int nAvail;                     /* Bytes of data available in buffer */
72362   assert( p->aBuffer );
72363
72364   /* If there is no more data to be read from the buffer, read the next 
72365   ** p->nBuffer bytes of data from the file into it. Or, if there are less
72366   ** than p->nBuffer bytes remaining in the PMA, read all remaining data.  */
72367   iBuf = p->iReadOff % p->nBuffer;
72368   if( iBuf==0 ){
72369     int nRead;                    /* Bytes to read from disk */
72370     int rc;                       /* sqlite3OsRead() return code */
72371
72372     /* Determine how many bytes of data to read. */
72373     if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
72374       nRead = p->nBuffer;
72375     }else{
72376       nRead = (int)(p->iEof - p->iReadOff);
72377     }
72378     assert( nRead>0 );
72379
72380     /* Read data from the file. Return early if an error occurs. */
72381     rc = sqlite3OsRead(p->pFile, p->aBuffer, nRead, p->iReadOff);
72382     assert( rc!=SQLITE_IOERR_SHORT_READ );
72383     if( rc!=SQLITE_OK ) return rc;
72384   }
72385   nAvail = p->nBuffer - iBuf; 
72386
72387   if( nByte<=nAvail ){
72388     /* The requested data is available in the in-memory buffer. In this
72389     ** case there is no need to make a copy of the data, just return a 
72390     ** pointer into the buffer to the caller.  */
72391     *ppOut = &p->aBuffer[iBuf];
72392     p->iReadOff += nByte;
72393   }else{
72394     /* The requested data is not all available in the in-memory buffer.
72395     ** In this case, allocate space at p->aAlloc[] to copy the requested
72396     ** range into. Then return a copy of pointer p->aAlloc to the caller.  */
72397     int nRem;                     /* Bytes remaining to copy */
72398
72399     /* Extend the p->aAlloc[] allocation if required. */
72400     if( p->nAlloc<nByte ){
72401       int nNew = p->nAlloc*2;
72402       while( nByte>nNew ) nNew = nNew*2;
72403       p->aAlloc = sqlite3DbReallocOrFree(db, p->aAlloc, nNew);
72404       if( !p->aAlloc ) return SQLITE_NOMEM;
72405       p->nAlloc = nNew;
72406     }
72407
72408     /* Copy as much data as is available in the buffer into the start of
72409     ** p->aAlloc[].  */
72410     memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
72411     p->iReadOff += nAvail;
72412     nRem = nByte - nAvail;
72413
72414     /* The following loop copies up to p->nBuffer bytes per iteration into
72415     ** the p->aAlloc[] buffer.  */
72416     while( nRem>0 ){
72417       int rc;                     /* vdbeSorterIterRead() return code */
72418       int nCopy;                  /* Number of bytes to copy */
72419       u8 *aNext;                  /* Pointer to buffer to copy data from */
72420
72421       nCopy = nRem;
72422       if( nRem>p->nBuffer ) nCopy = p->nBuffer;
72423       rc = vdbeSorterIterRead(db, p, nCopy, &aNext);
72424       if( rc!=SQLITE_OK ) return rc;
72425       assert( aNext!=p->aAlloc );
72426       memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
72427       nRem -= nCopy;
72428     }
72429
72430     *ppOut = p->aAlloc;
72431   }
72432
72433   return SQLITE_OK;
72434 }
72435
72436 /*
72437 ** Read a varint from the stream of data accessed by p. Set *pnOut to
72438 ** the value read.
72439 */
72440 static int vdbeSorterIterVarint(sqlite3 *db, VdbeSorterIter *p, u64 *pnOut){
72441   int iBuf;
72442
72443   iBuf = p->iReadOff % p->nBuffer;
72444   if( iBuf && (p->nBuffer-iBuf)>=9 ){
72445     p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
72446   }else{
72447     u8 aVarint[16], *a;
72448     int i = 0, rc;
72449     do{
72450       rc = vdbeSorterIterRead(db, p, 1, &a);
72451       if( rc ) return rc;
72452       aVarint[(i++)&0xf] = a[0];
72453     }while( (a[0]&0x80)!=0 );
72454     sqlite3GetVarint(aVarint, pnOut);
72455   }
72456
72457   return SQLITE_OK;
72458 }
72459
72460
72461 /*
72462 ** Advance iterator pIter to the next key in its PMA. Return SQLITE_OK if
72463 ** no error occurs, or an SQLite error code if one does.
72464 */
72465 static int vdbeSorterIterNext(
72466   sqlite3 *db,                    /* Database handle (for sqlite3DbMalloc() ) */
72467   VdbeSorterIter *pIter           /* Iterator to advance */
72468 ){
72469   int rc;                         /* Return Code */
72470   u64 nRec = 0;                   /* Size of record in bytes */
72471
72472   if( pIter->iReadOff>=pIter->iEof ){
72473     /* This is an EOF condition */
72474     vdbeSorterIterZero(db, pIter);
72475     return SQLITE_OK;
72476   }
72477
72478   rc = vdbeSorterIterVarint(db, pIter, &nRec);
72479   if( rc==SQLITE_OK ){
72480     pIter->nKey = (int)nRec;
72481     rc = vdbeSorterIterRead(db, pIter, (int)nRec, &pIter->aKey);
72482   }
72483
72484   return rc;
72485 }
72486
72487 /*
72488 ** Initialize iterator pIter to scan through the PMA stored in file pFile
72489 ** starting at offset iStart and ending at offset iEof-1. This function 
72490 ** leaves the iterator pointing to the first key in the PMA (or EOF if the 
72491 ** PMA is empty).
72492 */
72493 static int vdbeSorterIterInit(
72494   sqlite3 *db,                    /* Database handle */
72495   const VdbeSorter *pSorter,      /* Sorter object */
72496   i64 iStart,                     /* Start offset in pFile */
72497   VdbeSorterIter *pIter,          /* Iterator to populate */
72498   i64 *pnByte                     /* IN/OUT: Increment this value by PMA size */
72499 ){
72500   int rc = SQLITE_OK;
72501   int nBuf;
72502
72503   nBuf = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
72504
72505   assert( pSorter->iWriteOff>iStart );
72506   assert( pIter->aAlloc==0 );
72507   assert( pIter->aBuffer==0 );
72508   pIter->pFile = pSorter->pTemp1;
72509   pIter->iReadOff = iStart;
72510   pIter->nAlloc = 128;
72511   pIter->aAlloc = (u8 *)sqlite3DbMallocRaw(db, pIter->nAlloc);
72512   pIter->nBuffer = nBuf;
72513   pIter->aBuffer = (u8 *)sqlite3DbMallocRaw(db, nBuf);
72514
72515   if( !pIter->aBuffer ){
72516     rc = SQLITE_NOMEM;
72517   }else{
72518     int iBuf;
72519
72520     iBuf = iStart % nBuf;
72521     if( iBuf ){
72522       int nRead = nBuf - iBuf;
72523       if( (iStart + nRead) > pSorter->iWriteOff ){
72524         nRead = (int)(pSorter->iWriteOff - iStart);
72525       }
72526       rc = sqlite3OsRead(
72527           pSorter->pTemp1, &pIter->aBuffer[iBuf], nRead, iStart
72528       );
72529       assert( rc!=SQLITE_IOERR_SHORT_READ );
72530     }
72531
72532     if( rc==SQLITE_OK ){
72533       u64 nByte;                       /* Size of PMA in bytes */
72534       pIter->iEof = pSorter->iWriteOff;
72535       rc = vdbeSorterIterVarint(db, pIter, &nByte);
72536       pIter->iEof = pIter->iReadOff + nByte;
72537       *pnByte += nByte;
72538     }
72539   }
72540
72541   if( rc==SQLITE_OK ){
72542     rc = vdbeSorterIterNext(db, pIter);
72543   }
72544   return rc;
72545 }
72546
72547
72548 /*
72549 ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2, 
72550 ** size nKey2 bytes).  Argument pKeyInfo supplies the collation functions
72551 ** used by the comparison. If an error occurs, return an SQLite error code.
72552 ** Otherwise, return SQLITE_OK and set *pRes to a negative, zero or positive
72553 ** value, depending on whether key1 is smaller, equal to or larger than key2.
72554 **
72555 ** If the bOmitRowid argument is non-zero, assume both keys end in a rowid
72556 ** field. For the purposes of the comparison, ignore it. Also, if bOmitRowid
72557 ** is true and key1 contains even a single NULL value, it is considered to
72558 ** be less than key2. Even if key2 also contains NULL values.
72559 **
72560 ** If pKey2 is passed a NULL pointer, then it is assumed that the pCsr->aSpace
72561 ** has been allocated and contains an unpacked record that is used as key2.
72562 */
72563 static void vdbeSorterCompare(
72564   const VdbeCursor *pCsr,         /* Cursor object (for pKeyInfo) */
72565   int bOmitRowid,                 /* Ignore rowid field at end of keys */
72566   const void *pKey1, int nKey1,   /* Left side of comparison */
72567   const void *pKey2, int nKey2,   /* Right side of comparison */
72568   int *pRes                       /* OUT: Result of comparison */
72569 ){
72570   KeyInfo *pKeyInfo = pCsr->pKeyInfo;
72571   VdbeSorter *pSorter = pCsr->pSorter;
72572   UnpackedRecord *r2 = pSorter->pUnpacked;
72573   int i;
72574
72575   if( pKey2 ){
72576     sqlite3VdbeRecordUnpack(pKeyInfo, nKey2, pKey2, r2);
72577   }
72578
72579   if( bOmitRowid ){
72580     r2->nField = pKeyInfo->nField;
72581     assert( r2->nField>0 );
72582     for(i=0; i<r2->nField; i++){
72583       if( r2->aMem[i].flags & MEM_Null ){
72584         *pRes = -1;
72585         return;
72586       }
72587     }
72588     r2->flags |= UNPACKED_PREFIX_MATCH;
72589   }
72590
72591   *pRes = sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
72592 }
72593
72594 /*
72595 ** This function is called to compare two iterator keys when merging 
72596 ** multiple b-tree segments. Parameter iOut is the index of the aTree[] 
72597 ** value to recalculate.
72598 */
72599 static int vdbeSorterDoCompare(const VdbeCursor *pCsr, int iOut){
72600   VdbeSorter *pSorter = pCsr->pSorter;
72601   int i1;
72602   int i2;
72603   int iRes;
72604   VdbeSorterIter *p1;
72605   VdbeSorterIter *p2;
72606
72607   assert( iOut<pSorter->nTree && iOut>0 );
72608
72609   if( iOut>=(pSorter->nTree/2) ){
72610     i1 = (iOut - pSorter->nTree/2) * 2;
72611     i2 = i1 + 1;
72612   }else{
72613     i1 = pSorter->aTree[iOut*2];
72614     i2 = pSorter->aTree[iOut*2+1];
72615   }
72616
72617   p1 = &pSorter->aIter[i1];
72618   p2 = &pSorter->aIter[i2];
72619
72620   if( p1->pFile==0 ){
72621     iRes = i2;
72622   }else if( p2->pFile==0 ){
72623     iRes = i1;
72624   }else{
72625     int res;
72626     assert( pCsr->pSorter->pUnpacked!=0 );  /* allocated in vdbeSorterMerge() */
72627     vdbeSorterCompare(
72628         pCsr, 0, p1->aKey, p1->nKey, p2->aKey, p2->nKey, &res
72629     );
72630     if( res<=0 ){
72631       iRes = i1;
72632     }else{
72633       iRes = i2;
72634     }
72635   }
72636
72637   pSorter->aTree[iOut] = iRes;
72638   return SQLITE_OK;
72639 }
72640
72641 /*
72642 ** Initialize the temporary index cursor just opened as a sorter cursor.
72643 */
72644 SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *db, VdbeCursor *pCsr){
72645   int pgsz;                       /* Page size of main database */
72646   int mxCache;                    /* Cache size */
72647   VdbeSorter *pSorter;            /* The new sorter */
72648   char *d;                        /* Dummy */
72649
72650   assert( pCsr->pKeyInfo && pCsr->pBt==0 );
72651   pCsr->pSorter = pSorter = sqlite3DbMallocZero(db, sizeof(VdbeSorter));
72652   if( pSorter==0 ){
72653     return SQLITE_NOMEM;
72654   }
72655   
72656   pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pCsr->pKeyInfo, 0, 0, &d);
72657   if( pSorter->pUnpacked==0 ) return SQLITE_NOMEM;
72658   assert( pSorter->pUnpacked==(UnpackedRecord *)d );
72659
72660   if( !sqlite3TempInMemory(db) ){
72661     pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
72662     pSorter->mnPmaSize = SORTER_MIN_WORKING * pgsz;
72663     mxCache = db->aDb[0].pSchema->cache_size;
72664     if( mxCache<SORTER_MIN_WORKING ) mxCache = SORTER_MIN_WORKING;
72665     pSorter->mxPmaSize = mxCache * pgsz;
72666   }
72667
72668   return SQLITE_OK;
72669 }
72670
72671 /*
72672 ** Free the list of sorted records starting at pRecord.
72673 */
72674 static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
72675   SorterRecord *p;
72676   SorterRecord *pNext;
72677   for(p=pRecord; p; p=pNext){
72678     pNext = p->pNext;
72679     sqlite3DbFree(db, p);
72680   }
72681 }
72682
72683 /*
72684 ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
72685 */
72686 SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
72687   VdbeSorter *pSorter = pCsr->pSorter;
72688   if( pSorter ){
72689     if( pSorter->aIter ){
72690       int i;
72691       for(i=0; i<pSorter->nTree; i++){
72692         vdbeSorterIterZero(db, &pSorter->aIter[i]);
72693       }
72694       sqlite3DbFree(db, pSorter->aIter);
72695     }
72696     if( pSorter->pTemp1 ){
72697       sqlite3OsCloseFree(pSorter->pTemp1);
72698     }
72699     vdbeSorterRecordFree(db, pSorter->pRecord);
72700     sqlite3DbFree(db, pSorter->pUnpacked);
72701     sqlite3DbFree(db, pSorter);
72702     pCsr->pSorter = 0;
72703   }
72704 }
72705
72706 /*
72707 ** Allocate space for a file-handle and open a temporary file. If successful,
72708 ** set *ppFile to point to the malloc'd file-handle and return SQLITE_OK.
72709 ** Otherwise, set *ppFile to 0 and return an SQLite error code.
72710 */
72711 static int vdbeSorterOpenTempFile(sqlite3 *db, sqlite3_file **ppFile){
72712   int dummy;
72713   return sqlite3OsOpenMalloc(db->pVfs, 0, ppFile,
72714       SQLITE_OPEN_TEMP_JOURNAL |
72715       SQLITE_OPEN_READWRITE    | SQLITE_OPEN_CREATE |
72716       SQLITE_OPEN_EXCLUSIVE    | SQLITE_OPEN_DELETEONCLOSE, &dummy
72717   );
72718 }
72719
72720 /*
72721 ** Merge the two sorted lists p1 and p2 into a single list.
72722 ** Set *ppOut to the head of the new list.
72723 */
72724 static void vdbeSorterMerge(
72725   const VdbeCursor *pCsr,         /* For pKeyInfo */
72726   SorterRecord *p1,               /* First list to merge */
72727   SorterRecord *p2,               /* Second list to merge */
72728   SorterRecord **ppOut            /* OUT: Head of merged list */
72729 ){
72730   SorterRecord *pFinal = 0;
72731   SorterRecord **pp = &pFinal;
72732   void *pVal2 = p2 ? p2->pVal : 0;
72733
72734   while( p1 && p2 ){
72735     int res;
72736     vdbeSorterCompare(pCsr, 0, p1->pVal, p1->nVal, pVal2, p2->nVal, &res);
72737     if( res<=0 ){
72738       *pp = p1;
72739       pp = &p1->pNext;
72740       p1 = p1->pNext;
72741       pVal2 = 0;
72742     }else{
72743       *pp = p2;
72744        pp = &p2->pNext;
72745       p2 = p2->pNext;
72746       if( p2==0 ) break;
72747       pVal2 = p2->pVal;
72748     }
72749   }
72750   *pp = p1 ? p1 : p2;
72751   *ppOut = pFinal;
72752 }
72753
72754 /*
72755 ** Sort the linked list of records headed at pCsr->pRecord. Return SQLITE_OK
72756 ** if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if an error
72757 ** occurs.
72758 */
72759 static int vdbeSorterSort(const VdbeCursor *pCsr){
72760   int i;
72761   SorterRecord **aSlot;
72762   SorterRecord *p;
72763   VdbeSorter *pSorter = pCsr->pSorter;
72764
72765   aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
72766   if( !aSlot ){
72767     return SQLITE_NOMEM;
72768   }
72769
72770   p = pSorter->pRecord;
72771   while( p ){
72772     SorterRecord *pNext = p->pNext;
72773     p->pNext = 0;
72774     for(i=0; aSlot[i]; i++){
72775       vdbeSorterMerge(pCsr, p, aSlot[i], &p);
72776       aSlot[i] = 0;
72777     }
72778     aSlot[i] = p;
72779     p = pNext;
72780   }
72781
72782   p = 0;
72783   for(i=0; i<64; i++){
72784     vdbeSorterMerge(pCsr, p, aSlot[i], &p);
72785   }
72786   pSorter->pRecord = p;
72787
72788   sqlite3_free(aSlot);
72789   return SQLITE_OK;
72790 }
72791
72792 /*
72793 ** Initialize a file-writer object.
72794 */
72795 static void fileWriterInit(
72796   sqlite3 *db,                    /* Database (for malloc) */
72797   sqlite3_file *pFile,            /* File to write to */
72798   FileWriter *p,                  /* Object to populate */
72799   i64 iStart                      /* Offset of pFile to begin writing at */
72800 ){
72801   int nBuf = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
72802
72803   memset(p, 0, sizeof(FileWriter));
72804   p->aBuffer = (u8 *)sqlite3DbMallocRaw(db, nBuf);
72805   if( !p->aBuffer ){
72806     p->eFWErr = SQLITE_NOMEM;
72807   }else{
72808     p->iBufEnd = p->iBufStart = (iStart % nBuf);
72809     p->iWriteOff = iStart - p->iBufStart;
72810     p->nBuffer = nBuf;
72811     p->pFile = pFile;
72812   }
72813 }
72814
72815 /*
72816 ** Write nData bytes of data to the file-write object. Return SQLITE_OK
72817 ** if successful, or an SQLite error code if an error occurs.
72818 */
72819 static void fileWriterWrite(FileWriter *p, u8 *pData, int nData){
72820   int nRem = nData;
72821   while( nRem>0 && p->eFWErr==0 ){
72822     int nCopy = nRem;
72823     if( nCopy>(p->nBuffer - p->iBufEnd) ){
72824       nCopy = p->nBuffer - p->iBufEnd;
72825     }
72826
72827     memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
72828     p->iBufEnd += nCopy;
72829     if( p->iBufEnd==p->nBuffer ){
72830       p->eFWErr = sqlite3OsWrite(p->pFile, 
72831           &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart, 
72832           p->iWriteOff + p->iBufStart
72833       );
72834       p->iBufStart = p->iBufEnd = 0;
72835       p->iWriteOff += p->nBuffer;
72836     }
72837     assert( p->iBufEnd<p->nBuffer );
72838
72839     nRem -= nCopy;
72840   }
72841 }
72842
72843 /*
72844 ** Flush any buffered data to disk and clean up the file-writer object.
72845 ** The results of using the file-writer after this call are undefined.
72846 ** Return SQLITE_OK if flushing the buffered data succeeds or is not 
72847 ** required. Otherwise, return an SQLite error code.
72848 **
72849 ** Before returning, set *piEof to the offset immediately following the
72850 ** last byte written to the file.
72851 */
72852 static int fileWriterFinish(sqlite3 *db, FileWriter *p, i64 *piEof){
72853   int rc;
72854   if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
72855     p->eFWErr = sqlite3OsWrite(p->pFile, 
72856         &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart, 
72857         p->iWriteOff + p->iBufStart
72858     );
72859   }
72860   *piEof = (p->iWriteOff + p->iBufEnd);
72861   sqlite3DbFree(db, p->aBuffer);
72862   rc = p->eFWErr;
72863   memset(p, 0, sizeof(FileWriter));
72864   return rc;
72865 }
72866
72867 /*
72868 ** Write value iVal encoded as a varint to the file-write object. Return 
72869 ** SQLITE_OK if successful, or an SQLite error code if an error occurs.
72870 */
72871 static void fileWriterWriteVarint(FileWriter *p, u64 iVal){
72872   int nByte; 
72873   u8 aByte[10];
72874   nByte = sqlite3PutVarint(aByte, iVal);
72875   fileWriterWrite(p, aByte, nByte);
72876 }
72877
72878 /*
72879 ** Write the current contents of the in-memory linked-list to a PMA. Return
72880 ** SQLITE_OK if successful, or an SQLite error code otherwise.
72881 **
72882 ** The format of a PMA is:
72883 **
72884 **     * A varint. This varint contains the total number of bytes of content
72885 **       in the PMA (not including the varint itself).
72886 **
72887 **     * One or more records packed end-to-end in order of ascending keys. 
72888 **       Each record consists of a varint followed by a blob of data (the 
72889 **       key). The varint is the number of bytes in the blob of data.
72890 */
72891 static int vdbeSorterListToPMA(sqlite3 *db, const VdbeCursor *pCsr){
72892   int rc = SQLITE_OK;             /* Return code */
72893   VdbeSorter *pSorter = pCsr->pSorter;
72894   FileWriter writer;
72895
72896   memset(&writer, 0, sizeof(FileWriter));
72897
72898   if( pSorter->nInMemory==0 ){
72899     assert( pSorter->pRecord==0 );
72900     return rc;
72901   }
72902
72903   rc = vdbeSorterSort(pCsr);
72904
72905   /* If the first temporary PMA file has not been opened, open it now. */
72906   if( rc==SQLITE_OK && pSorter->pTemp1==0 ){
72907     rc = vdbeSorterOpenTempFile(db, &pSorter->pTemp1);
72908     assert( rc!=SQLITE_OK || pSorter->pTemp1 );
72909     assert( pSorter->iWriteOff==0 );
72910     assert( pSorter->nPMA==0 );
72911   }
72912
72913   if( rc==SQLITE_OK ){
72914     SorterRecord *p;
72915     SorterRecord *pNext = 0;
72916
72917     fileWriterInit(db, pSorter->pTemp1, &writer, pSorter->iWriteOff);
72918     pSorter->nPMA++;
72919     fileWriterWriteVarint(&writer, pSorter->nInMemory);
72920     for(p=pSorter->pRecord; p; p=pNext){
72921       pNext = p->pNext;
72922       fileWriterWriteVarint(&writer, p->nVal);
72923       fileWriterWrite(&writer, p->pVal, p->nVal);
72924       sqlite3DbFree(db, p);
72925     }
72926     pSorter->pRecord = p;
72927     rc = fileWriterFinish(db, &writer, &pSorter->iWriteOff);
72928   }
72929
72930   return rc;
72931 }
72932
72933 /*
72934 ** Add a record to the sorter.
72935 */
72936 SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
72937   sqlite3 *db,                    /* Database handle */
72938   const VdbeCursor *pCsr,               /* Sorter cursor */
72939   Mem *pVal                       /* Memory cell containing record */
72940 ){
72941   VdbeSorter *pSorter = pCsr->pSorter;
72942   int rc = SQLITE_OK;             /* Return Code */
72943   SorterRecord *pNew;             /* New list element */
72944
72945   assert( pSorter );
72946   pSorter->nInMemory += sqlite3VarintLen(pVal->n) + pVal->n;
72947
72948   pNew = (SorterRecord *)sqlite3DbMallocRaw(db, pVal->n + sizeof(SorterRecord));
72949   if( pNew==0 ){
72950     rc = SQLITE_NOMEM;
72951   }else{
72952     pNew->pVal = (void *)&pNew[1];
72953     memcpy(pNew->pVal, pVal->z, pVal->n);
72954     pNew->nVal = pVal->n;
72955     pNew->pNext = pSorter->pRecord;
72956     pSorter->pRecord = pNew;
72957   }
72958
72959   /* See if the contents of the sorter should now be written out. They
72960   ** are written out when either of the following are true:
72961   **
72962   **   * The total memory allocated for the in-memory list is greater 
72963   **     than (page-size * cache-size), or
72964   **
72965   **   * The total memory allocated for the in-memory list is greater 
72966   **     than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
72967   */
72968   if( rc==SQLITE_OK && pSorter->mxPmaSize>0 && (
72969         (pSorter->nInMemory>pSorter->mxPmaSize)
72970      || (pSorter->nInMemory>pSorter->mnPmaSize && sqlite3HeapNearlyFull())
72971   )){
72972 #ifdef SQLITE_DEBUG
72973     i64 nExpect = pSorter->iWriteOff
72974                 + sqlite3VarintLen(pSorter->nInMemory)
72975                 + pSorter->nInMemory;
72976 #endif
72977     rc = vdbeSorterListToPMA(db, pCsr);
72978     pSorter->nInMemory = 0;
72979     assert( rc!=SQLITE_OK || (nExpect==pSorter->iWriteOff) );
72980   }
72981
72982   return rc;
72983 }
72984
72985 /*
72986 ** Helper function for sqlite3VdbeSorterRewind(). 
72987 */
72988 static int vdbeSorterInitMerge(
72989   sqlite3 *db,                    /* Database handle */
72990   const VdbeCursor *pCsr,         /* Cursor handle for this sorter */
72991   i64 *pnByte                     /* Sum of bytes in all opened PMAs */
72992 ){
72993   VdbeSorter *pSorter = pCsr->pSorter;
72994   int rc = SQLITE_OK;             /* Return code */
72995   int i;                          /* Used to iterator through aIter[] */
72996   i64 nByte = 0;                  /* Total bytes in all opened PMAs */
72997
72998   /* Initialize the iterators. */
72999   for(i=0; i<SORTER_MAX_MERGE_COUNT; i++){
73000     VdbeSorterIter *pIter = &pSorter->aIter[i];
73001     rc = vdbeSorterIterInit(db, pSorter, pSorter->iReadOff, pIter, &nByte);
73002     pSorter->iReadOff = pIter->iEof;
73003     assert( rc!=SQLITE_OK || pSorter->iReadOff<=pSorter->iWriteOff );
73004     if( rc!=SQLITE_OK || pSorter->iReadOff>=pSorter->iWriteOff ) break;
73005   }
73006
73007   /* Initialize the aTree[] array. */
73008   for(i=pSorter->nTree-1; rc==SQLITE_OK && i>0; i--){
73009     rc = vdbeSorterDoCompare(pCsr, i);
73010   }
73011
73012   *pnByte = nByte;
73013   return rc;
73014 }
73015
73016 /*
73017 ** Once the sorter has been populated, this function is called to prepare
73018 ** for iterating through its contents in sorted order.
73019 */
73020 SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
73021   VdbeSorter *pSorter = pCsr->pSorter;
73022   int rc;                         /* Return code */
73023   sqlite3_file *pTemp2 = 0;       /* Second temp file to use */
73024   i64 iWrite2 = 0;                /* Write offset for pTemp2 */
73025   int nIter;                      /* Number of iterators used */
73026   int nByte;                      /* Bytes of space required for aIter/aTree */
73027   int N = 2;                      /* Power of 2 >= nIter */
73028
73029   assert( pSorter );
73030
73031   /* If no data has been written to disk, then do not do so now. Instead,
73032   ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
73033   ** from the in-memory list.  */
73034   if( pSorter->nPMA==0 ){
73035     *pbEof = !pSorter->pRecord;
73036     assert( pSorter->aTree==0 );
73037     return vdbeSorterSort(pCsr);
73038   }
73039
73040   /* Write the current in-memory list to a PMA. */
73041   rc = vdbeSorterListToPMA(db, pCsr);
73042   if( rc!=SQLITE_OK ) return rc;
73043
73044   /* Allocate space for aIter[] and aTree[]. */
73045   nIter = pSorter->nPMA;
73046   if( nIter>SORTER_MAX_MERGE_COUNT ) nIter = SORTER_MAX_MERGE_COUNT;
73047   assert( nIter>0 );
73048   while( N<nIter ) N += N;
73049   nByte = N * (sizeof(int) + sizeof(VdbeSorterIter));
73050   pSorter->aIter = (VdbeSorterIter *)sqlite3DbMallocZero(db, nByte);
73051   if( !pSorter->aIter ) return SQLITE_NOMEM;
73052   pSorter->aTree = (int *)&pSorter->aIter[N];
73053   pSorter->nTree = N;
73054
73055   do {
73056     int iNew;                     /* Index of new, merged, PMA */
73057
73058     for(iNew=0; 
73059         rc==SQLITE_OK && iNew*SORTER_MAX_MERGE_COUNT<pSorter->nPMA; 
73060         iNew++
73061     ){
73062       int rc2;                    /* Return code from fileWriterFinish() */
73063       FileWriter writer;          /* Object used to write to disk */
73064       i64 nWrite;                 /* Number of bytes in new PMA */
73065
73066       memset(&writer, 0, sizeof(FileWriter));
73067
73068       /* If there are SORTER_MAX_MERGE_COUNT or less PMAs in file pTemp1,
73069       ** initialize an iterator for each of them and break out of the loop.
73070       ** These iterators will be incrementally merged as the VDBE layer calls
73071       ** sqlite3VdbeSorterNext().
73072       **
73073       ** Otherwise, if pTemp1 contains more than SORTER_MAX_MERGE_COUNT PMAs,
73074       ** initialize interators for SORTER_MAX_MERGE_COUNT of them. These PMAs
73075       ** are merged into a single PMA that is written to file pTemp2.
73076       */
73077       rc = vdbeSorterInitMerge(db, pCsr, &nWrite);
73078       assert( rc!=SQLITE_OK || pSorter->aIter[ pSorter->aTree[1] ].pFile );
73079       if( rc!=SQLITE_OK || pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
73080         break;
73081       }
73082
73083       /* Open the second temp file, if it is not already open. */
73084       if( pTemp2==0 ){
73085         assert( iWrite2==0 );
73086         rc = vdbeSorterOpenTempFile(db, &pTemp2);
73087       }
73088
73089       if( rc==SQLITE_OK ){
73090         int bEof = 0;
73091         fileWriterInit(db, pTemp2, &writer, iWrite2);
73092         fileWriterWriteVarint(&writer, nWrite);
73093         while( rc==SQLITE_OK && bEof==0 ){
73094           VdbeSorterIter *pIter = &pSorter->aIter[ pSorter->aTree[1] ];
73095           assert( pIter->pFile );
73096
73097           fileWriterWriteVarint(&writer, pIter->nKey);
73098           fileWriterWrite(&writer, pIter->aKey, pIter->nKey);
73099           rc = sqlite3VdbeSorterNext(db, pCsr, &bEof);
73100         }
73101         rc2 = fileWriterFinish(db, &writer, &iWrite2);
73102         if( rc==SQLITE_OK ) rc = rc2;
73103       }
73104     }
73105
73106     if( pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
73107       break;
73108     }else{
73109       sqlite3_file *pTmp = pSorter->pTemp1;
73110       pSorter->nPMA = iNew;
73111       pSorter->pTemp1 = pTemp2;
73112       pTemp2 = pTmp;
73113       pSorter->iWriteOff = iWrite2;
73114       pSorter->iReadOff = 0;
73115       iWrite2 = 0;
73116     }
73117   }while( rc==SQLITE_OK );
73118
73119   if( pTemp2 ){
73120     sqlite3OsCloseFree(pTemp2);
73121   }
73122   *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
73123   return rc;
73124 }
73125
73126 /*
73127 ** Advance to the next element in the sorter.
73128 */
73129 SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
73130   VdbeSorter *pSorter = pCsr->pSorter;
73131   int rc;                         /* Return code */
73132
73133   if( pSorter->aTree ){
73134     int iPrev = pSorter->aTree[1];/* Index of iterator to advance */
73135     int i;                        /* Index of aTree[] to recalculate */
73136
73137     rc = vdbeSorterIterNext(db, &pSorter->aIter[iPrev]);
73138     for(i=(pSorter->nTree+iPrev)/2; rc==SQLITE_OK && i>0; i=i/2){
73139       rc = vdbeSorterDoCompare(pCsr, i);
73140     }
73141
73142     *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
73143   }else{
73144     SorterRecord *pFree = pSorter->pRecord;
73145     pSorter->pRecord = pFree->pNext;
73146     pFree->pNext = 0;
73147     vdbeSorterRecordFree(db, pFree);
73148     *pbEof = !pSorter->pRecord;
73149     rc = SQLITE_OK;
73150   }
73151   return rc;
73152 }
73153
73154 /*
73155 ** Return a pointer to a buffer owned by the sorter that contains the 
73156 ** current key.
73157 */
73158 static void *vdbeSorterRowkey(
73159   const VdbeSorter *pSorter,      /* Sorter object */
73160   int *pnKey                      /* OUT: Size of current key in bytes */
73161 ){
73162   void *pKey;
73163   if( pSorter->aTree ){
73164     VdbeSorterIter *pIter;
73165     pIter = &pSorter->aIter[ pSorter->aTree[1] ];
73166     *pnKey = pIter->nKey;
73167     pKey = pIter->aKey;
73168   }else{
73169     *pnKey = pSorter->pRecord->nVal;
73170     pKey = pSorter->pRecord->pVal;
73171   }
73172   return pKey;
73173 }
73174
73175 /*
73176 ** Copy the current sorter key into the memory cell pOut.
73177 */
73178 SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
73179   VdbeSorter *pSorter = pCsr->pSorter;
73180   void *pKey; int nKey;           /* Sorter key to copy into pOut */
73181
73182   pKey = vdbeSorterRowkey(pSorter, &nKey);
73183   if( sqlite3VdbeMemGrow(pOut, nKey, 0) ){
73184     return SQLITE_NOMEM;
73185   }
73186   pOut->n = nKey;
73187   MemSetTypeFlag(pOut, MEM_Blob);
73188   memcpy(pOut->z, pKey, nKey);
73189
73190   return SQLITE_OK;
73191 }
73192
73193 /*
73194 ** Compare the key in memory cell pVal with the key that the sorter cursor
73195 ** passed as the first argument currently points to. For the purposes of
73196 ** the comparison, ignore the rowid field at the end of each record.
73197 **
73198 ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
73199 ** Otherwise, set *pRes to a negative, zero or positive value if the
73200 ** key in pVal is smaller than, equal to or larger than the current sorter
73201 ** key.
73202 */
73203 SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
73204   const VdbeCursor *pCsr,         /* Sorter cursor */
73205   Mem *pVal,                      /* Value to compare to current sorter key */
73206   int *pRes                       /* OUT: Result of comparison */
73207 ){
73208   VdbeSorter *pSorter = pCsr->pSorter;
73209   void *pKey; int nKey;           /* Sorter key to compare pVal with */
73210
73211   pKey = vdbeSorterRowkey(pSorter, &nKey);
73212   vdbeSorterCompare(pCsr, 1, pVal->z, pVal->n, pKey, nKey, pRes);
73213   return SQLITE_OK;
73214 }
73215
73216 /************** End of vdbesort.c ********************************************/
73217 /************** Begin file journal.c *****************************************/
73218 /*
73219 ** 2007 August 22
73220 **
73221 ** The author disclaims copyright to this source code.  In place of
73222 ** a legal notice, here is a blessing:
73223 **
73224 **    May you do good and not evil.
73225 **    May you find forgiveness for yourself and forgive others.
73226 **    May you share freely, never taking more than you give.
73227 **
73228 *************************************************************************
73229 **
73230 ** This file implements a special kind of sqlite3_file object used
73231 ** by SQLite to create journal files if the atomic-write optimization
73232 ** is enabled.
73233 **
73234 ** The distinctive characteristic of this sqlite3_file is that the
73235 ** actual on disk file is created lazily. When the file is created,
73236 ** the caller specifies a buffer size for an in-memory buffer to
73237 ** be used to service read() and write() requests. The actual file
73238 ** on disk is not created or populated until either:
73239 **
73240 **   1) The in-memory representation grows too large for the allocated 
73241 **      buffer, or
73242 **   2) The sqlite3JournalCreate() function is called.
73243 */
73244 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
73245
73246
73247 /*
73248 ** A JournalFile object is a subclass of sqlite3_file used by
73249 ** as an open file handle for journal files.
73250 */
73251 struct JournalFile {
73252   sqlite3_io_methods *pMethod;    /* I/O methods on journal files */
73253   int nBuf;                       /* Size of zBuf[] in bytes */
73254   char *zBuf;                     /* Space to buffer journal writes */
73255   int iSize;                      /* Amount of zBuf[] currently used */
73256   int flags;                      /* xOpen flags */
73257   sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
73258   sqlite3_file *pReal;            /* The "real" underlying file descriptor */
73259   const char *zJournal;           /* Name of the journal file */
73260 };
73261 typedef struct JournalFile JournalFile;
73262
73263 /*
73264 ** If it does not already exists, create and populate the on-disk file 
73265 ** for JournalFile p.
73266 */
73267 static int createFile(JournalFile *p){
73268   int rc = SQLITE_OK;
73269   if( !p->pReal ){
73270     sqlite3_file *pReal = (sqlite3_file *)&p[1];
73271     rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
73272     if( rc==SQLITE_OK ){
73273       p->pReal = pReal;
73274       if( p->iSize>0 ){
73275         assert(p->iSize<=p->nBuf);
73276         rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
73277       }
73278       if( rc!=SQLITE_OK ){
73279         /* If an error occurred while writing to the file, close it before
73280         ** returning. This way, SQLite uses the in-memory journal data to 
73281         ** roll back changes made to the internal page-cache before this
73282         ** function was called.  */
73283         sqlite3OsClose(pReal);
73284         p->pReal = 0;
73285       }
73286     }
73287   }
73288   return rc;
73289 }
73290
73291 /*
73292 ** Close the file.
73293 */
73294 static int jrnlClose(sqlite3_file *pJfd){
73295   JournalFile *p = (JournalFile *)pJfd;
73296   if( p->pReal ){
73297     sqlite3OsClose(p->pReal);
73298   }
73299   sqlite3_free(p->zBuf);
73300   return SQLITE_OK;
73301 }
73302
73303 /*
73304 ** Read data from the file.
73305 */
73306 static int jrnlRead(
73307   sqlite3_file *pJfd,    /* The journal file from which to read */
73308   void *zBuf,            /* Put the results here */
73309   int iAmt,              /* Number of bytes to read */
73310   sqlite_int64 iOfst     /* Begin reading at this offset */
73311 ){
73312   int rc = SQLITE_OK;
73313   JournalFile *p = (JournalFile *)pJfd;
73314   if( p->pReal ){
73315     rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
73316   }else if( (iAmt+iOfst)>p->iSize ){
73317     rc = SQLITE_IOERR_SHORT_READ;
73318   }else{
73319     memcpy(zBuf, &p->zBuf[iOfst], iAmt);
73320   }
73321   return rc;
73322 }
73323
73324 /*
73325 ** Write data to the file.
73326 */
73327 static int jrnlWrite(
73328   sqlite3_file *pJfd,    /* The journal file into which to write */
73329   const void *zBuf,      /* Take data to be written from here */
73330   int iAmt,              /* Number of bytes to write */
73331   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
73332 ){
73333   int rc = SQLITE_OK;
73334   JournalFile *p = (JournalFile *)pJfd;
73335   if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
73336     rc = createFile(p);
73337   }
73338   if( rc==SQLITE_OK ){
73339     if( p->pReal ){
73340       rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
73341     }else{
73342       memcpy(&p->zBuf[iOfst], zBuf, iAmt);
73343       if( p->iSize<(iOfst+iAmt) ){
73344         p->iSize = (iOfst+iAmt);
73345       }
73346     }
73347   }
73348   return rc;
73349 }
73350
73351 /*
73352 ** Truncate the file.
73353 */
73354 static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
73355   int rc = SQLITE_OK;
73356   JournalFile *p = (JournalFile *)pJfd;
73357   if( p->pReal ){
73358     rc = sqlite3OsTruncate(p->pReal, size);
73359   }else if( size<p->iSize ){
73360     p->iSize = size;
73361   }
73362   return rc;
73363 }
73364
73365 /*
73366 ** Sync the file.
73367 */
73368 static int jrnlSync(sqlite3_file *pJfd, int flags){
73369   int rc;
73370   JournalFile *p = (JournalFile *)pJfd;
73371   if( p->pReal ){
73372     rc = sqlite3OsSync(p->pReal, flags);
73373   }else{
73374     rc = SQLITE_OK;
73375   }
73376   return rc;
73377 }
73378
73379 /*
73380 ** Query the size of the file in bytes.
73381 */
73382 static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
73383   int rc = SQLITE_OK;
73384   JournalFile *p = (JournalFile *)pJfd;
73385   if( p->pReal ){
73386     rc = sqlite3OsFileSize(p->pReal, pSize);
73387   }else{
73388     *pSize = (sqlite_int64) p->iSize;
73389   }
73390   return rc;
73391 }
73392
73393 /*
73394 ** Table of methods for JournalFile sqlite3_file object.
73395 */
73396 static struct sqlite3_io_methods JournalFileMethods = {
73397   1,             /* iVersion */
73398   jrnlClose,     /* xClose */
73399   jrnlRead,      /* xRead */
73400   jrnlWrite,     /* xWrite */
73401   jrnlTruncate,  /* xTruncate */
73402   jrnlSync,      /* xSync */
73403   jrnlFileSize,  /* xFileSize */
73404   0,             /* xLock */
73405   0,             /* xUnlock */
73406   0,             /* xCheckReservedLock */
73407   0,             /* xFileControl */
73408   0,             /* xSectorSize */
73409   0,             /* xDeviceCharacteristics */
73410   0,             /* xShmMap */
73411   0,             /* xShmLock */
73412   0,             /* xShmBarrier */
73413   0              /* xShmUnmap */
73414 };
73415
73416 /* 
73417 ** Open a journal file.
73418 */
73419 SQLITE_PRIVATE int sqlite3JournalOpen(
73420   sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
73421   const char *zName,         /* Name of the journal file */
73422   sqlite3_file *pJfd,        /* Preallocated, blank file handle */
73423   int flags,                 /* Opening flags */
73424   int nBuf                   /* Bytes buffered before opening the file */
73425 ){
73426   JournalFile *p = (JournalFile *)pJfd;
73427   memset(p, 0, sqlite3JournalSize(pVfs));
73428   if( nBuf>0 ){
73429     p->zBuf = sqlite3MallocZero(nBuf);
73430     if( !p->zBuf ){
73431       return SQLITE_NOMEM;
73432     }
73433   }else{
73434     return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
73435   }
73436   p->pMethod = &JournalFileMethods;
73437   p->nBuf = nBuf;
73438   p->flags = flags;
73439   p->zJournal = zName;
73440   p->pVfs = pVfs;
73441   return SQLITE_OK;
73442 }
73443
73444 /*
73445 ** If the argument p points to a JournalFile structure, and the underlying
73446 ** file has not yet been created, create it now.
73447 */
73448 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
73449   if( p->pMethods!=&JournalFileMethods ){
73450     return SQLITE_OK;
73451   }
73452   return createFile((JournalFile *)p);
73453 }
73454
73455 /*
73456 ** The file-handle passed as the only argument is guaranteed to be an open
73457 ** file. It may or may not be of class JournalFile. If the file is a
73458 ** JournalFile, and the underlying file on disk has not yet been opened,
73459 ** return 0. Otherwise, return 1.
73460 */
73461 SQLITE_PRIVATE int sqlite3JournalExists(sqlite3_file *p){
73462   return (p->pMethods!=&JournalFileMethods || ((JournalFile *)p)->pReal!=0);
73463 }
73464
73465 /* 
73466 ** Return the number of bytes required to store a JournalFile that uses vfs
73467 ** pVfs to create the underlying on-disk files.
73468 */
73469 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
73470   return (pVfs->szOsFile+sizeof(JournalFile));
73471 }
73472 #endif
73473
73474 /************** End of journal.c *********************************************/
73475 /************** Begin file memjournal.c **************************************/
73476 /*
73477 ** 2008 October 7
73478 **
73479 ** The author disclaims copyright to this source code.  In place of
73480 ** a legal notice, here is a blessing:
73481 **
73482 **    May you do good and not evil.
73483 **    May you find forgiveness for yourself and forgive others.
73484 **    May you share freely, never taking more than you give.
73485 **
73486 *************************************************************************
73487 **
73488 ** This file contains code use to implement an in-memory rollback journal.
73489 ** The in-memory rollback journal is used to journal transactions for
73490 ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
73491 */
73492
73493 /* Forward references to internal structures */
73494 typedef struct MemJournal MemJournal;
73495 typedef struct FilePoint FilePoint;
73496 typedef struct FileChunk FileChunk;
73497
73498 /* Space to hold the rollback journal is allocated in increments of
73499 ** this many bytes.
73500 **
73501 ** The size chosen is a little less than a power of two.  That way,
73502 ** the FileChunk object will have a size that almost exactly fills
73503 ** a power-of-two allocation.  This mimimizes wasted space in power-of-two
73504 ** memory allocators.
73505 */
73506 #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
73507
73508 /* Macro to find the minimum of two numeric values.
73509 */
73510 #ifndef MIN
73511 # define MIN(x,y) ((x)<(y)?(x):(y))
73512 #endif
73513
73514 /*
73515 ** The rollback journal is composed of a linked list of these structures.
73516 */
73517 struct FileChunk {
73518   FileChunk *pNext;               /* Next chunk in the journal */
73519   u8 zChunk[JOURNAL_CHUNKSIZE];   /* Content of this chunk */
73520 };
73521
73522 /*
73523 ** An instance of this object serves as a cursor into the rollback journal.
73524 ** The cursor can be either for reading or writing.
73525 */
73526 struct FilePoint {
73527   sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
73528   FileChunk *pChunk;              /* Specific chunk into which cursor points */
73529 };
73530
73531 /*
73532 ** This subclass is a subclass of sqlite3_file.  Each open memory-journal
73533 ** is an instance of this class.
73534 */
73535 struct MemJournal {
73536   sqlite3_io_methods *pMethod;    /* Parent class. MUST BE FIRST */
73537   FileChunk *pFirst;              /* Head of in-memory chunk-list */
73538   FilePoint endpoint;             /* Pointer to the end of the file */
73539   FilePoint readpoint;            /* Pointer to the end of the last xRead() */
73540 };
73541
73542 /*
73543 ** Read data from the in-memory journal file.  This is the implementation
73544 ** of the sqlite3_vfs.xRead method.
73545 */
73546 static int memjrnlRead(
73547   sqlite3_file *pJfd,    /* The journal file from which to read */
73548   void *zBuf,            /* Put the results here */
73549   int iAmt,              /* Number of bytes to read */
73550   sqlite_int64 iOfst     /* Begin reading at this offset */
73551 ){
73552   MemJournal *p = (MemJournal *)pJfd;
73553   u8 *zOut = zBuf;
73554   int nRead = iAmt;
73555   int iChunkOffset;
73556   FileChunk *pChunk;
73557
73558   /* SQLite never tries to read past the end of a rollback journal file */
73559   assert( iOfst+iAmt<=p->endpoint.iOffset );
73560
73561   if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
73562     sqlite3_int64 iOff = 0;
73563     for(pChunk=p->pFirst; 
73564         ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
73565         pChunk=pChunk->pNext
73566     ){
73567       iOff += JOURNAL_CHUNKSIZE;
73568     }
73569   }else{
73570     pChunk = p->readpoint.pChunk;
73571   }
73572
73573   iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
73574   do {
73575     int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
73576     int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
73577     memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
73578     zOut += nCopy;
73579     nRead -= iSpace;
73580     iChunkOffset = 0;
73581   } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
73582   p->readpoint.iOffset = iOfst+iAmt;
73583   p->readpoint.pChunk = pChunk;
73584
73585   return SQLITE_OK;
73586 }
73587
73588 /*
73589 ** Write data to the file.
73590 */
73591 static int memjrnlWrite(
73592   sqlite3_file *pJfd,    /* The journal file into which to write */
73593   const void *zBuf,      /* Take data to be written from here */
73594   int iAmt,              /* Number of bytes to write */
73595   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
73596 ){
73597   MemJournal *p = (MemJournal *)pJfd;
73598   int nWrite = iAmt;
73599   u8 *zWrite = (u8 *)zBuf;
73600
73601   /* An in-memory journal file should only ever be appended to. Random
73602   ** access writes are not required by sqlite.
73603   */
73604   assert( iOfst==p->endpoint.iOffset );
73605   UNUSED_PARAMETER(iOfst);
73606
73607   while( nWrite>0 ){
73608     FileChunk *pChunk = p->endpoint.pChunk;
73609     int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
73610     int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
73611
73612     if( iChunkOffset==0 ){
73613       /* New chunk is required to extend the file. */
73614       FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
73615       if( !pNew ){
73616         return SQLITE_IOERR_NOMEM;
73617       }
73618       pNew->pNext = 0;
73619       if( pChunk ){
73620         assert( p->pFirst );
73621         pChunk->pNext = pNew;
73622       }else{
73623         assert( !p->pFirst );
73624         p->pFirst = pNew;
73625       }
73626       p->endpoint.pChunk = pNew;
73627     }
73628
73629     memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
73630     zWrite += iSpace;
73631     nWrite -= iSpace;
73632     p->endpoint.iOffset += iSpace;
73633   }
73634
73635   return SQLITE_OK;
73636 }
73637
73638 /*
73639 ** Truncate the file.
73640 */
73641 static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
73642   MemJournal *p = (MemJournal *)pJfd;
73643   FileChunk *pChunk;
73644   assert(size==0);
73645   UNUSED_PARAMETER(size);
73646   pChunk = p->pFirst;
73647   while( pChunk ){
73648     FileChunk *pTmp = pChunk;
73649     pChunk = pChunk->pNext;
73650     sqlite3_free(pTmp);
73651   }
73652   sqlite3MemJournalOpen(pJfd);
73653   return SQLITE_OK;
73654 }
73655
73656 /*
73657 ** Close the file.
73658 */
73659 static int memjrnlClose(sqlite3_file *pJfd){
73660   memjrnlTruncate(pJfd, 0);
73661   return SQLITE_OK;
73662 }
73663
73664
73665 /*
73666 ** Sync the file.
73667 **
73668 ** Syncing an in-memory journal is a no-op.  And, in fact, this routine
73669 ** is never called in a working implementation.  This implementation
73670 ** exists purely as a contingency, in case some malfunction in some other
73671 ** part of SQLite causes Sync to be called by mistake.
73672 */
73673 static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
73674   UNUSED_PARAMETER2(NotUsed, NotUsed2);
73675   return SQLITE_OK;
73676 }
73677
73678 /*
73679 ** Query the size of the file in bytes.
73680 */
73681 static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
73682   MemJournal *p = (MemJournal *)pJfd;
73683   *pSize = (sqlite_int64) p->endpoint.iOffset;
73684   return SQLITE_OK;
73685 }
73686
73687 /*
73688 ** Table of methods for MemJournal sqlite3_file object.
73689 */
73690 static const struct sqlite3_io_methods MemJournalMethods = {
73691   1,                /* iVersion */
73692   memjrnlClose,     /* xClose */
73693   memjrnlRead,      /* xRead */
73694   memjrnlWrite,     /* xWrite */
73695   memjrnlTruncate,  /* xTruncate */
73696   memjrnlSync,      /* xSync */
73697   memjrnlFileSize,  /* xFileSize */
73698   0,                /* xLock */
73699   0,                /* xUnlock */
73700   0,                /* xCheckReservedLock */
73701   0,                /* xFileControl */
73702   0,                /* xSectorSize */
73703   0,                /* xDeviceCharacteristics */
73704   0,                /* xShmMap */
73705   0,                /* xShmLock */
73706   0,                /* xShmBarrier */
73707   0,                /* xShmUnmap */
73708   0,                /* xFetch */
73709   0                 /* xUnfetch */
73710 };
73711
73712 /* 
73713 ** Open a journal file.
73714 */
73715 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
73716   MemJournal *p = (MemJournal *)pJfd;
73717   assert( EIGHT_BYTE_ALIGNMENT(p) );
73718   memset(p, 0, sqlite3MemJournalSize());
73719   p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
73720 }
73721
73722 /*
73723 ** Return true if the file-handle passed as an argument is 
73724 ** an in-memory journal 
73725 */
73726 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
73727   return pJfd->pMethods==&MemJournalMethods;
73728 }
73729
73730 /* 
73731 ** Return the number of bytes required to store a MemJournal file descriptor.
73732 */
73733 SQLITE_PRIVATE int sqlite3MemJournalSize(void){
73734   return sizeof(MemJournal);
73735 }
73736
73737 /************** End of memjournal.c ******************************************/
73738 /************** Begin file walker.c ******************************************/
73739 /*
73740 ** 2008 August 16
73741 **
73742 ** The author disclaims copyright to this source code.  In place of
73743 ** a legal notice, here is a blessing:
73744 **
73745 **    May you do good and not evil.
73746 **    May you find forgiveness for yourself and forgive others.
73747 **    May you share freely, never taking more than you give.
73748 **
73749 *************************************************************************
73750 ** This file contains routines used for walking the parser tree for
73751 ** an SQL statement.
73752 */
73753 /* #include <stdlib.h> */
73754 /* #include <string.h> */
73755
73756
73757 /*
73758 ** Walk an expression tree.  Invoke the callback once for each node
73759 ** of the expression, while decending.  (In other words, the callback
73760 ** is invoked before visiting children.)
73761 **
73762 ** The return value from the callback should be one of the WRC_*
73763 ** constants to specify how to proceed with the walk.
73764 **
73765 **    WRC_Continue      Continue descending down the tree.
73766 **
73767 **    WRC_Prune         Do not descend into child nodes.  But allow
73768 **                      the walk to continue with sibling nodes.
73769 **
73770 **    WRC_Abort         Do no more callbacks.  Unwind the stack and
73771 **                      return the top-level walk call.
73772 **
73773 ** The return value from this routine is WRC_Abort to abandon the tree walk
73774 ** and WRC_Continue to continue.
73775 */
73776 SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
73777   int rc;
73778   if( pExpr==0 ) return WRC_Continue;
73779   testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
73780   testcase( ExprHasProperty(pExpr, EP_Reduced) );
73781   rc = pWalker->xExprCallback(pWalker, pExpr);
73782   if( rc==WRC_Continue
73783               && !ExprHasAnyProperty(pExpr,EP_TokenOnly) ){
73784     if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
73785     if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
73786     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
73787       if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
73788     }else{
73789       if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
73790     }
73791   }
73792   return rc & WRC_Abort;
73793 }
73794
73795 /*
73796 ** Call sqlite3WalkExpr() for every expression in list p or until
73797 ** an abort request is seen.
73798 */
73799 SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
73800   int i;
73801   struct ExprList_item *pItem;
73802   if( p ){
73803     for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
73804       if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
73805     }
73806   }
73807   return WRC_Continue;
73808 }
73809
73810 /*
73811 ** Walk all expressions associated with SELECT statement p.  Do
73812 ** not invoke the SELECT callback on p, but do (of course) invoke
73813 ** any expr callbacks and SELECT callbacks that come from subqueries.
73814 ** Return WRC_Abort or WRC_Continue.
73815 */
73816 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
73817   if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
73818   if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
73819   if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
73820   if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
73821   if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
73822   if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
73823   if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
73824   return WRC_Continue;
73825 }
73826
73827 /*
73828 ** Walk the parse trees associated with all subqueries in the
73829 ** FROM clause of SELECT statement p.  Do not invoke the select
73830 ** callback on p, but do invoke it on each FROM clause subquery
73831 ** and on any subqueries further down in the tree.  Return 
73832 ** WRC_Abort or WRC_Continue;
73833 */
73834 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
73835   SrcList *pSrc;
73836   int i;
73837   struct SrcList_item *pItem;
73838
73839   pSrc = p->pSrc;
73840   if( ALWAYS(pSrc) ){
73841     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
73842       if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
73843         return WRC_Abort;
73844       }
73845     }
73846   }
73847   return WRC_Continue;
73848
73849
73850 /*
73851 ** Call sqlite3WalkExpr() for every expression in Select statement p.
73852 ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
73853 ** on the compound select chain, p->pPrior.  Invoke the xSelectCallback()
73854 ** either before or after the walk of expressions and FROM clause, depending
73855 ** on whether pWalker->bSelectDepthFirst is false or true, respectively.
73856 **
73857 ** Return WRC_Continue under normal conditions.  Return WRC_Abort if
73858 ** there is an abort request.
73859 **
73860 ** If the Walker does not have an xSelectCallback() then this routine
73861 ** is a no-op returning WRC_Continue.
73862 */
73863 SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
73864   int rc;
73865   if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
73866   rc = WRC_Continue;
73867   pWalker->walkerDepth++;
73868   while( p ){
73869     if( !pWalker->bSelectDepthFirst ){
73870        rc = pWalker->xSelectCallback(pWalker, p);
73871        if( rc ) break;
73872     }
73873     if( sqlite3WalkSelectExpr(pWalker, p)
73874      || sqlite3WalkSelectFrom(pWalker, p)
73875     ){
73876       pWalker->walkerDepth--;
73877       return WRC_Abort;
73878     }
73879     if( pWalker->bSelectDepthFirst ){
73880       rc = pWalker->xSelectCallback(pWalker, p);
73881       /* Depth-first search is currently only used for
73882       ** selectAddSubqueryTypeInfo() and that routine always returns
73883       ** WRC_Continue (0).  So the following branch is never taken. */
73884       if( NEVER(rc) ) break;
73885     }
73886     p = p->pPrior;
73887   }
73888   pWalker->walkerDepth--;
73889   return rc & WRC_Abort;
73890 }
73891
73892 /************** End of walker.c **********************************************/
73893 /************** Begin file resolve.c *****************************************/
73894 /*
73895 ** 2008 August 18
73896 **
73897 ** The author disclaims copyright to this source code.  In place of
73898 ** a legal notice, here is a blessing:
73899 **
73900 **    May you do good and not evil.
73901 **    May you find forgiveness for yourself and forgive others.
73902 **    May you share freely, never taking more than you give.
73903 **
73904 *************************************************************************
73905 **
73906 ** This file contains routines used for walking the parser tree and
73907 ** resolve all identifiers by associating them with a particular
73908 ** table and column.
73909 */
73910 /* #include <stdlib.h> */
73911 /* #include <string.h> */
73912
73913 /*
73914 ** Walk the expression tree pExpr and increase the aggregate function
73915 ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
73916 ** This needs to occur when copying a TK_AGG_FUNCTION node from an
73917 ** outer query into an inner subquery.
73918 **
73919 ** incrAggFunctionDepth(pExpr,n) is the main routine.  incrAggDepth(..)
73920 ** is a helper function - a callback for the tree walker.
73921 */
73922 static int incrAggDepth(Walker *pWalker, Expr *pExpr){
73923   if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.i;
73924   return WRC_Continue;
73925 }
73926 static void incrAggFunctionDepth(Expr *pExpr, int N){
73927   if( N>0 ){
73928     Walker w;
73929     memset(&w, 0, sizeof(w));
73930     w.xExprCallback = incrAggDepth;
73931     w.u.i = N;
73932     sqlite3WalkExpr(&w, pExpr);
73933   }
73934 }
73935
73936 /*
73937 ** Turn the pExpr expression into an alias for the iCol-th column of the
73938 ** result set in pEList.
73939 **
73940 ** If the result set column is a simple column reference, then this routine
73941 ** makes an exact copy.  But for any other kind of expression, this
73942 ** routine make a copy of the result set column as the argument to the
73943 ** TK_AS operator.  The TK_AS operator causes the expression to be
73944 ** evaluated just once and then reused for each alias.
73945 **
73946 ** The reason for suppressing the TK_AS term when the expression is a simple
73947 ** column reference is so that the column reference will be recognized as
73948 ** usable by indices within the WHERE clause processing logic. 
73949 **
73950 ** Hack:  The TK_AS operator is inhibited if zType[0]=='G'.  This means
73951 ** that in a GROUP BY clause, the expression is evaluated twice.  Hence:
73952 **
73953 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
73954 **
73955 ** Is equivalent to:
73956 **
73957 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
73958 **
73959 ** The result of random()%5 in the GROUP BY clause is probably different
73960 ** from the result in the result-set.  We might fix this someday.  Or
73961 ** then again, we might not...
73962 **
73963 ** If the reference is followed by a COLLATE operator, then make sure
73964 ** the COLLATE operator is preserved.  For example:
73965 **
73966 **     SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
73967 **
73968 ** Should be transformed into:
73969 **
73970 **     SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
73971 **
73972 ** The nSubquery parameter specifies how many levels of subquery the
73973 ** alias is removed from the original expression.  The usually value is
73974 ** zero but it might be more if the alias is contained within a subquery
73975 ** of the original expression.  The Expr.op2 field of TK_AGG_FUNCTION
73976 ** structures must be increased by the nSubquery amount.
73977 */
73978 static void resolveAlias(
73979   Parse *pParse,         /* Parsing context */
73980   ExprList *pEList,      /* A result set */
73981   int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
73982   Expr *pExpr,           /* Transform this into an alias to the result set */
73983   const char *zType,     /* "GROUP" or "ORDER" or "" */
73984   int nSubquery          /* Number of subqueries that the label is moving */
73985 ){
73986   Expr *pOrig;           /* The iCol-th column of the result set */
73987   Expr *pDup;            /* Copy of pOrig */
73988   sqlite3 *db;           /* The database connection */
73989
73990   assert( iCol>=0 && iCol<pEList->nExpr );
73991   pOrig = pEList->a[iCol].pExpr;
73992   assert( pOrig!=0 );
73993   assert( pOrig->flags & EP_Resolved );
73994   db = pParse->db;
73995   pDup = sqlite3ExprDup(db, pOrig, 0);
73996   if( pDup==0 ) return;
73997   if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
73998     incrAggFunctionDepth(pDup, nSubquery);
73999     pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
74000     if( pDup==0 ) return;
74001     if( pEList->a[iCol].iAlias==0 ){
74002       pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
74003     }
74004     pDup->iTable = pEList->a[iCol].iAlias;
74005   }
74006   if( pExpr->op==TK_COLLATE ){
74007     pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
74008   }
74009
74010   /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This 
74011   ** prevents ExprDelete() from deleting the Expr structure itself,
74012   ** allowing it to be repopulated by the memcpy() on the following line.
74013   ** The pExpr->u.zToken might point into memory that will be freed by the
74014   ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
74015   ** make a copy of the token before doing the sqlite3DbFree().
74016   */
74017   ExprSetProperty(pExpr, EP_Static);
74018   sqlite3ExprDelete(db, pExpr);
74019   memcpy(pExpr, pDup, sizeof(*pExpr));
74020   if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
74021     assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
74022     pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
74023     pExpr->flags2 |= EP2_MallocedToken;
74024   }
74025   sqlite3DbFree(db, pDup);
74026 }
74027
74028
74029 /*
74030 ** Return TRUE if the name zCol occurs anywhere in the USING clause.
74031 **
74032 ** Return FALSE if the USING clause is NULL or if it does not contain
74033 ** zCol.
74034 */
74035 static int nameInUsingClause(IdList *pUsing, const char *zCol){
74036   if( pUsing ){
74037     int k;
74038     for(k=0; k<pUsing->nId; k++){
74039       if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
74040     }
74041   }
74042   return 0;
74043 }
74044
74045 /*
74046 ** Subqueries stores the original database, table and column names for their
74047 ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
74048 ** Check to see if the zSpan given to this routine matches the zDb, zTab,
74049 ** and zCol.  If any of zDb, zTab, and zCol are NULL then those fields will
74050 ** match anything.
74051 */
74052 SQLITE_PRIVATE int sqlite3MatchSpanName(
74053   const char *zSpan,
74054   const char *zCol,
74055   const char *zTab,
74056   const char *zDb
74057 ){
74058   int n;
74059   for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
74060   if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
74061     return 0;
74062   }
74063   zSpan += n+1;
74064   for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
74065   if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
74066     return 0;
74067   }
74068   zSpan += n+1;
74069   if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
74070     return 0;
74071   }
74072   return 1;
74073 }
74074
74075 /*
74076 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
74077 ** that name in the set of source tables in pSrcList and make the pExpr 
74078 ** expression node refer back to that source column.  The following changes
74079 ** are made to pExpr:
74080 **
74081 **    pExpr->iDb           Set the index in db->aDb[] of the database X
74082 **                         (even if X is implied).
74083 **    pExpr->iTable        Set to the cursor number for the table obtained
74084 **                         from pSrcList.
74085 **    pExpr->pTab          Points to the Table structure of X.Y (even if
74086 **                         X and/or Y are implied.)
74087 **    pExpr->iColumn       Set to the column number within the table.
74088 **    pExpr->op            Set to TK_COLUMN.
74089 **    pExpr->pLeft         Any expression this points to is deleted
74090 **    pExpr->pRight        Any expression this points to is deleted.
74091 **
74092 ** The zDb variable is the name of the database (the "X").  This value may be
74093 ** NULL meaning that name is of the form Y.Z or Z.  Any available database
74094 ** can be used.  The zTable variable is the name of the table (the "Y").  This
74095 ** value can be NULL if zDb is also NULL.  If zTable is NULL it
74096 ** means that the form of the name is Z and that columns from any table
74097 ** can be used.
74098 **
74099 ** If the name cannot be resolved unambiguously, leave an error message
74100 ** in pParse and return WRC_Abort.  Return WRC_Prune on success.
74101 */
74102 static int lookupName(
74103   Parse *pParse,       /* The parsing context */
74104   const char *zDb,     /* Name of the database containing table, or NULL */
74105   const char *zTab,    /* Name of table containing column, or NULL */
74106   const char *zCol,    /* Name of the column. */
74107   NameContext *pNC,    /* The name context used to resolve the name */
74108   Expr *pExpr          /* Make this EXPR node point to the selected column */
74109 ){
74110   int i, j;                         /* Loop counters */
74111   int cnt = 0;                      /* Number of matching column names */
74112   int cntTab = 0;                   /* Number of matching table names */
74113   int nSubquery = 0;                /* How many levels of subquery */
74114   sqlite3 *db = pParse->db;         /* The database connection */
74115   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
74116   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
74117   NameContext *pTopNC = pNC;        /* First namecontext in the list */
74118   Schema *pSchema = 0;              /* Schema of the expression */
74119   int isTrigger = 0;
74120
74121   assert( pNC );     /* the name context cannot be NULL. */
74122   assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
74123   assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
74124
74125   /* Initialize the node to no-match */
74126   pExpr->iTable = -1;
74127   pExpr->pTab = 0;
74128   ExprSetIrreducible(pExpr);
74129
74130   /* Translate the schema name in zDb into a pointer to the corresponding
74131   ** schema.  If not found, pSchema will remain NULL and nothing will match
74132   ** resulting in an appropriate error message toward the end of this routine
74133   */
74134   if( zDb ){
74135     for(i=0; i<db->nDb; i++){
74136       assert( db->aDb[i].zName );
74137       if( sqlite3StrICmp(db->aDb[i].zName,zDb)==0 ){
74138         pSchema = db->aDb[i].pSchema;
74139         break;
74140       }
74141     }
74142   }
74143
74144   /* Start at the inner-most context and move outward until a match is found */
74145   while( pNC && cnt==0 ){
74146     ExprList *pEList;
74147     SrcList *pSrcList = pNC->pSrcList;
74148
74149     if( pSrcList ){
74150       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
74151         Table *pTab;
74152         Column *pCol;
74153   
74154         pTab = pItem->pTab;
74155         assert( pTab!=0 && pTab->zName!=0 );
74156         assert( pTab->nCol>0 );
74157         if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
74158           int hit = 0;
74159           pEList = pItem->pSelect->pEList;
74160           for(j=0; j<pEList->nExpr; j++){
74161             if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
74162               cnt++;
74163               cntTab = 2;
74164               pMatch = pItem;
74165               pExpr->iColumn = j;
74166               hit = 1;
74167             }
74168           }
74169           if( hit || zTab==0 ) continue;
74170         }
74171         if( zDb && pTab->pSchema!=pSchema ){
74172           continue;
74173         }
74174         if( zTab ){
74175           const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
74176           assert( zTabName!=0 );
74177           if( sqlite3StrICmp(zTabName, zTab)!=0 ){
74178             continue;
74179           }
74180         }
74181         if( 0==(cntTab++) ){
74182           pMatch = pItem;
74183         }
74184         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
74185           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
74186             /* If there has been exactly one prior match and this match
74187             ** is for the right-hand table of a NATURAL JOIN or is in a 
74188             ** USING clause, then skip this match.
74189             */
74190             if( cnt==1 ){
74191               if( pItem->jointype & JT_NATURAL ) continue;
74192               if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
74193             }
74194             cnt++;
74195             pMatch = pItem;
74196             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
74197             pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
74198             break;
74199           }
74200         }
74201       }
74202       if( pMatch ){
74203         pExpr->iTable = pMatch->iCursor;
74204         pExpr->pTab = pMatch->pTab;
74205         pSchema = pExpr->pTab->pSchema;
74206       }
74207     } /* if( pSrcList ) */
74208
74209 #ifndef SQLITE_OMIT_TRIGGER
74210     /* If we have not already resolved the name, then maybe 
74211     ** it is a new.* or old.* trigger argument reference
74212     */
74213     if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
74214       int op = pParse->eTriggerOp;
74215       Table *pTab = 0;
74216       assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
74217       if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
74218         pExpr->iTable = 1;
74219         pTab = pParse->pTriggerTab;
74220       }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
74221         pExpr->iTable = 0;
74222         pTab = pParse->pTriggerTab;
74223       }
74224
74225       if( pTab ){ 
74226         int iCol;
74227         pSchema = pTab->pSchema;
74228         cntTab++;
74229         for(iCol=0; iCol<pTab->nCol; iCol++){
74230           Column *pCol = &pTab->aCol[iCol];
74231           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
74232             if( iCol==pTab->iPKey ){
74233               iCol = -1;
74234             }
74235             break;
74236           }
74237         }
74238         if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
74239           iCol = -1;        /* IMP: R-44911-55124 */
74240         }
74241         if( iCol<pTab->nCol ){
74242           cnt++;
74243           if( iCol<0 ){
74244             pExpr->affinity = SQLITE_AFF_INTEGER;
74245           }else if( pExpr->iTable==0 ){
74246             testcase( iCol==31 );
74247             testcase( iCol==32 );
74248             pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
74249           }else{
74250             testcase( iCol==31 );
74251             testcase( iCol==32 );
74252             pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
74253           }
74254           pExpr->iColumn = (i16)iCol;
74255           pExpr->pTab = pTab;
74256           isTrigger = 1;
74257         }
74258       }
74259     }
74260 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
74261
74262     /*
74263     ** Perhaps the name is a reference to the ROWID
74264     */
74265     if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
74266       cnt = 1;
74267       pExpr->iColumn = -1;     /* IMP: R-44911-55124 */
74268       pExpr->affinity = SQLITE_AFF_INTEGER;
74269     }
74270
74271     /*
74272     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
74273     ** might refer to an result-set alias.  This happens, for example, when
74274     ** we are resolving names in the WHERE clause of the following command:
74275     **
74276     **     SELECT a+b AS x FROM table WHERE x<10;
74277     **
74278     ** In cases like this, replace pExpr with a copy of the expression that
74279     ** forms the result set entry ("a+b" in the example) and return immediately.
74280     ** Note that the expression in the result set should have already been
74281     ** resolved by the time the WHERE clause is resolved.
74282     */
74283     if( (pEList = pNC->pEList)!=0
74284      && zTab==0
74285      && ((pNC->ncFlags & NC_AsMaybe)==0 || cnt==0)
74286     ){
74287       for(j=0; j<pEList->nExpr; j++){
74288         char *zAs = pEList->a[j].zName;
74289         if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
74290           Expr *pOrig;
74291           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
74292           assert( pExpr->x.pList==0 );
74293           assert( pExpr->x.pSelect==0 );
74294           pOrig = pEList->a[j].pExpr;
74295           if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
74296             sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
74297             return WRC_Abort;
74298           }
74299           resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
74300           cnt = 1;
74301           pMatch = 0;
74302           assert( zTab==0 && zDb==0 );
74303           goto lookupname_end;
74304         }
74305       } 
74306     }
74307
74308     /* Advance to the next name context.  The loop will exit when either
74309     ** we have a match (cnt>0) or when we run out of name contexts.
74310     */
74311     if( cnt==0 ){
74312       pNC = pNC->pNext;
74313       nSubquery++;
74314     }
74315   }
74316
74317   /*
74318   ** If X and Y are NULL (in other words if only the column name Z is
74319   ** supplied) and the value of Z is enclosed in double-quotes, then
74320   ** Z is a string literal if it doesn't match any column names.  In that
74321   ** case, we need to return right away and not make any changes to
74322   ** pExpr.
74323   **
74324   ** Because no reference was made to outer contexts, the pNC->nRef
74325   ** fields are not changed in any context.
74326   */
74327   if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
74328     pExpr->op = TK_STRING;
74329     pExpr->pTab = 0;
74330     return WRC_Prune;
74331   }
74332
74333   /*
74334   ** cnt==0 means there was not match.  cnt>1 means there were two or
74335   ** more matches.  Either way, we have an error.
74336   */
74337   if( cnt!=1 ){
74338     const char *zErr;
74339     zErr = cnt==0 ? "no such column" : "ambiguous column name";
74340     if( zDb ){
74341       sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
74342     }else if( zTab ){
74343       sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
74344     }else{
74345       sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
74346     }
74347     pParse->checkSchema = 1;
74348     pTopNC->nErr++;
74349   }
74350
74351   /* If a column from a table in pSrcList is referenced, then record
74352   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
74353   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
74354   ** column number is greater than the number of bits in the bitmask
74355   ** then set the high-order bit of the bitmask.
74356   */
74357   if( pExpr->iColumn>=0 && pMatch!=0 ){
74358     int n = pExpr->iColumn;
74359     testcase( n==BMS-1 );
74360     if( n>=BMS ){
74361       n = BMS-1;
74362     }
74363     assert( pMatch->iCursor==pExpr->iTable );
74364     pMatch->colUsed |= ((Bitmask)1)<<n;
74365   }
74366
74367   /* Clean up and return
74368   */
74369   sqlite3ExprDelete(db, pExpr->pLeft);
74370   pExpr->pLeft = 0;
74371   sqlite3ExprDelete(db, pExpr->pRight);
74372   pExpr->pRight = 0;
74373   pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
74374 lookupname_end:
74375   if( cnt==1 ){
74376     assert( pNC!=0 );
74377     if( pExpr->op!=TK_AS ){
74378       sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
74379     }
74380     /* Increment the nRef value on all name contexts from TopNC up to
74381     ** the point where the name matched. */
74382     for(;;){
74383       assert( pTopNC!=0 );
74384       pTopNC->nRef++;
74385       if( pTopNC==pNC ) break;
74386       pTopNC = pTopNC->pNext;
74387     }
74388     return WRC_Prune;
74389   } else {
74390     return WRC_Abort;
74391   }
74392 }
74393
74394 /*
74395 ** Allocate and return a pointer to an expression to load the column iCol
74396 ** from datasource iSrc in SrcList pSrc.
74397 */
74398 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
74399   Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
74400   if( p ){
74401     struct SrcList_item *pItem = &pSrc->a[iSrc];
74402     p->pTab = pItem->pTab;
74403     p->iTable = pItem->iCursor;
74404     if( p->pTab->iPKey==iCol ){
74405       p->iColumn = -1;
74406     }else{
74407       p->iColumn = (ynVar)iCol;
74408       testcase( iCol==BMS );
74409       testcase( iCol==BMS-1 );
74410       pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
74411     }
74412     ExprSetProperty(p, EP_Resolved);
74413   }
74414   return p;
74415 }
74416
74417 /*
74418 ** This routine is callback for sqlite3WalkExpr().
74419 **
74420 ** Resolve symbolic names into TK_COLUMN operators for the current
74421 ** node in the expression tree.  Return 0 to continue the search down
74422 ** the tree or 2 to abort the tree walk.
74423 **
74424 ** This routine also does error checking and name resolution for
74425 ** function names.  The operator for aggregate functions is changed
74426 ** to TK_AGG_FUNCTION.
74427 */
74428 static int resolveExprStep(Walker *pWalker, Expr *pExpr){
74429   NameContext *pNC;
74430   Parse *pParse;
74431
74432   pNC = pWalker->u.pNC;
74433   assert( pNC!=0 );
74434   pParse = pNC->pParse;
74435   assert( pParse==pWalker->pParse );
74436
74437   if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
74438   ExprSetProperty(pExpr, EP_Resolved);
74439 #ifndef NDEBUG
74440   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
74441     SrcList *pSrcList = pNC->pSrcList;
74442     int i;
74443     for(i=0; i<pNC->pSrcList->nSrc; i++){
74444       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
74445     }
74446   }
74447 #endif
74448   switch( pExpr->op ){
74449
74450 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
74451     /* The special operator TK_ROW means use the rowid for the first
74452     ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
74453     ** clause processing on UPDATE and DELETE statements.
74454     */
74455     case TK_ROW: {
74456       SrcList *pSrcList = pNC->pSrcList;
74457       struct SrcList_item *pItem;
74458       assert( pSrcList && pSrcList->nSrc==1 );
74459       pItem = pSrcList->a; 
74460       pExpr->op = TK_COLUMN;
74461       pExpr->pTab = pItem->pTab;
74462       pExpr->iTable = pItem->iCursor;
74463       pExpr->iColumn = -1;
74464       pExpr->affinity = SQLITE_AFF_INTEGER;
74465       break;
74466     }
74467 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
74468
74469     /* A lone identifier is the name of a column.
74470     */
74471     case TK_ID: {
74472       return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
74473     }
74474   
74475     /* A table name and column name:     ID.ID
74476     ** Or a database, table and column:  ID.ID.ID
74477     */
74478     case TK_DOT: {
74479       const char *zColumn;
74480       const char *zTable;
74481       const char *zDb;
74482       Expr *pRight;
74483
74484       /* if( pSrcList==0 ) break; */
74485       pRight = pExpr->pRight;
74486       if( pRight->op==TK_ID ){
74487         zDb = 0;
74488         zTable = pExpr->pLeft->u.zToken;
74489         zColumn = pRight->u.zToken;
74490       }else{
74491         assert( pRight->op==TK_DOT );
74492         zDb = pExpr->pLeft->u.zToken;
74493         zTable = pRight->pLeft->u.zToken;
74494         zColumn = pRight->pRight->u.zToken;
74495       }
74496       return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
74497     }
74498
74499     /* Resolve function names
74500     */
74501     case TK_CONST_FUNC:
74502     case TK_FUNCTION: {
74503       ExprList *pList = pExpr->x.pList;    /* The argument list */
74504       int n = pList ? pList->nExpr : 0;    /* Number of arguments */
74505       int no_such_func = 0;       /* True if no such function exists */
74506       int wrong_num_args = 0;     /* True if wrong number of arguments */
74507       int is_agg = 0;             /* True if is an aggregate function */
74508       int auth;                   /* Authorization to use the function */
74509       int nId;                    /* Number of characters in function name */
74510       const char *zId;            /* The function name. */
74511       FuncDef *pDef;              /* Information about the function */
74512       u8 enc = ENC(pParse->db);   /* The database encoding */
74513
74514       testcase( pExpr->op==TK_CONST_FUNC );
74515       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
74516       zId = pExpr->u.zToken;
74517       nId = sqlite3Strlen30(zId);
74518       pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
74519       if( pDef==0 ){
74520         pDef = sqlite3FindFunction(pParse->db, zId, nId, -2, enc, 0);
74521         if( pDef==0 ){
74522           no_such_func = 1;
74523         }else{
74524           wrong_num_args = 1;
74525         }
74526       }else{
74527         is_agg = pDef->xFunc==0;
74528       }
74529 #ifndef SQLITE_OMIT_AUTHORIZATION
74530       if( pDef ){
74531         auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
74532         if( auth!=SQLITE_OK ){
74533           if( auth==SQLITE_DENY ){
74534             sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
74535                                     pDef->zName);
74536             pNC->nErr++;
74537           }
74538           pExpr->op = TK_NULL;
74539           return WRC_Prune;
74540         }
74541       }
74542 #endif
74543       if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
74544         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
74545         pNC->nErr++;
74546         is_agg = 0;
74547       }else if( no_such_func && pParse->db->init.busy==0 ){
74548         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
74549         pNC->nErr++;
74550       }else if( wrong_num_args ){
74551         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
74552              nId, zId);
74553         pNC->nErr++;
74554       }
74555       if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
74556       sqlite3WalkExprList(pWalker, pList);
74557       if( is_agg ){
74558         NameContext *pNC2 = pNC;
74559         pExpr->op = TK_AGG_FUNCTION;
74560         pExpr->op2 = 0;
74561         while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
74562           pExpr->op2++;
74563           pNC2 = pNC2->pNext;
74564         }
74565         if( pNC2 ) pNC2->ncFlags |= NC_HasAgg;
74566         pNC->ncFlags |= NC_AllowAgg;
74567       }
74568       /* FIX ME:  Compute pExpr->affinity based on the expected return
74569       ** type of the function 
74570       */
74571       return WRC_Prune;
74572     }
74573 #ifndef SQLITE_OMIT_SUBQUERY
74574     case TK_SELECT:
74575     case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
74576 #endif
74577     case TK_IN: {
74578       testcase( pExpr->op==TK_IN );
74579       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
74580         int nRef = pNC->nRef;
74581 #ifndef SQLITE_OMIT_CHECK
74582         if( (pNC->ncFlags & NC_IsCheck)!=0 ){
74583           sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
74584         }
74585 #endif
74586         sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
74587         assert( pNC->nRef>=nRef );
74588         if( nRef!=pNC->nRef ){
74589           ExprSetProperty(pExpr, EP_VarSelect);
74590         }
74591       }
74592       break;
74593     }
74594 #ifndef SQLITE_OMIT_CHECK
74595     case TK_VARIABLE: {
74596       if( (pNC->ncFlags & NC_IsCheck)!=0 ){
74597         sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
74598       }
74599       break;
74600     }
74601 #endif
74602   }
74603   return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
74604 }
74605
74606 /*
74607 ** pEList is a list of expressions which are really the result set of the
74608 ** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
74609 ** This routine checks to see if pE is a simple identifier which corresponds
74610 ** to the AS-name of one of the terms of the expression list.  If it is,
74611 ** this routine return an integer between 1 and N where N is the number of
74612 ** elements in pEList, corresponding to the matching entry.  If there is
74613 ** no match, or if pE is not a simple identifier, then this routine
74614 ** return 0.
74615 **
74616 ** pEList has been resolved.  pE has not.
74617 */
74618 static int resolveAsName(
74619   Parse *pParse,     /* Parsing context for error messages */
74620   ExprList *pEList,  /* List of expressions to scan */
74621   Expr *pE           /* Expression we are trying to match */
74622 ){
74623   int i;             /* Loop counter */
74624
74625   UNUSED_PARAMETER(pParse);
74626
74627   if( pE->op==TK_ID ){
74628     char *zCol = pE->u.zToken;
74629     for(i=0; i<pEList->nExpr; i++){
74630       char *zAs = pEList->a[i].zName;
74631       if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
74632         return i+1;
74633       }
74634     }
74635   }
74636   return 0;
74637 }
74638
74639 /*
74640 ** pE is a pointer to an expression which is a single term in the
74641 ** ORDER BY of a compound SELECT.  The expression has not been
74642 ** name resolved.
74643 **
74644 ** At the point this routine is called, we already know that the
74645 ** ORDER BY term is not an integer index into the result set.  That
74646 ** case is handled by the calling routine.
74647 **
74648 ** Attempt to match pE against result set columns in the left-most
74649 ** SELECT statement.  Return the index i of the matching column,
74650 ** as an indication to the caller that it should sort by the i-th column.
74651 ** The left-most column is 1.  In other words, the value returned is the
74652 ** same integer value that would be used in the SQL statement to indicate
74653 ** the column.
74654 **
74655 ** If there is no match, return 0.  Return -1 if an error occurs.
74656 */
74657 static int resolveOrderByTermToExprList(
74658   Parse *pParse,     /* Parsing context for error messages */
74659   Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
74660   Expr *pE           /* The specific ORDER BY term */
74661 ){
74662   int i;             /* Loop counter */
74663   ExprList *pEList;  /* The columns of the result set */
74664   NameContext nc;    /* Name context for resolving pE */
74665   sqlite3 *db;       /* Database connection */
74666   int rc;            /* Return code from subprocedures */
74667   u8 savedSuppErr;   /* Saved value of db->suppressErr */
74668
74669   assert( sqlite3ExprIsInteger(pE, &i)==0 );
74670   pEList = pSelect->pEList;
74671
74672   /* Resolve all names in the ORDER BY term expression
74673   */
74674   memset(&nc, 0, sizeof(nc));
74675   nc.pParse = pParse;
74676   nc.pSrcList = pSelect->pSrc;
74677   nc.pEList = pEList;
74678   nc.ncFlags = NC_AllowAgg;
74679   nc.nErr = 0;
74680   db = pParse->db;
74681   savedSuppErr = db->suppressErr;
74682   db->suppressErr = 1;
74683   rc = sqlite3ResolveExprNames(&nc, pE);
74684   db->suppressErr = savedSuppErr;
74685   if( rc ) return 0;
74686
74687   /* Try to match the ORDER BY expression against an expression
74688   ** in the result set.  Return an 1-based index of the matching
74689   ** result-set entry.
74690   */
74691   for(i=0; i<pEList->nExpr; i++){
74692     if( sqlite3ExprCompare(pEList->a[i].pExpr, pE)<2 ){
74693       return i+1;
74694     }
74695   }
74696
74697   /* If no match, return 0. */
74698   return 0;
74699 }
74700
74701 /*
74702 ** Generate an ORDER BY or GROUP BY term out-of-range error.
74703 */
74704 static void resolveOutOfRangeError(
74705   Parse *pParse,         /* The error context into which to write the error */
74706   const char *zType,     /* "ORDER" or "GROUP" */
74707   int i,                 /* The index (1-based) of the term out of range */
74708   int mx                 /* Largest permissible value of i */
74709 ){
74710   sqlite3ErrorMsg(pParse, 
74711     "%r %s BY term out of range - should be "
74712     "between 1 and %d", i, zType, mx);
74713 }
74714
74715 /*
74716 ** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
74717 ** each term of the ORDER BY clause is a constant integer between 1
74718 ** and N where N is the number of columns in the compound SELECT.
74719 **
74720 ** ORDER BY terms that are already an integer between 1 and N are
74721 ** unmodified.  ORDER BY terms that are integers outside the range of
74722 ** 1 through N generate an error.  ORDER BY terms that are expressions
74723 ** are matched against result set expressions of compound SELECT
74724 ** beginning with the left-most SELECT and working toward the right.
74725 ** At the first match, the ORDER BY expression is transformed into
74726 ** the integer column number.
74727 **
74728 ** Return the number of errors seen.
74729 */
74730 static int resolveCompoundOrderBy(
74731   Parse *pParse,        /* Parsing context.  Leave error messages here */
74732   Select *pSelect       /* The SELECT statement containing the ORDER BY */
74733 ){
74734   int i;
74735   ExprList *pOrderBy;
74736   ExprList *pEList;
74737   sqlite3 *db;
74738   int moreToDo = 1;
74739
74740   pOrderBy = pSelect->pOrderBy;
74741   if( pOrderBy==0 ) return 0;
74742   db = pParse->db;
74743 #if SQLITE_MAX_COLUMN
74744   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
74745     sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
74746     return 1;
74747   }
74748 #endif
74749   for(i=0; i<pOrderBy->nExpr; i++){
74750     pOrderBy->a[i].done = 0;
74751   }
74752   pSelect->pNext = 0;
74753   while( pSelect->pPrior ){
74754     pSelect->pPrior->pNext = pSelect;
74755     pSelect = pSelect->pPrior;
74756   }
74757   while( pSelect && moreToDo ){
74758     struct ExprList_item *pItem;
74759     moreToDo = 0;
74760     pEList = pSelect->pEList;
74761     assert( pEList!=0 );
74762     for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
74763       int iCol = -1;
74764       Expr *pE, *pDup;
74765       if( pItem->done ) continue;
74766       pE = sqlite3ExprSkipCollate(pItem->pExpr);
74767       if( sqlite3ExprIsInteger(pE, &iCol) ){
74768         if( iCol<=0 || iCol>pEList->nExpr ){
74769           resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
74770           return 1;
74771         }
74772       }else{
74773         iCol = resolveAsName(pParse, pEList, pE);
74774         if( iCol==0 ){
74775           pDup = sqlite3ExprDup(db, pE, 0);
74776           if( !db->mallocFailed ){
74777             assert(pDup);
74778             iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
74779           }
74780           sqlite3ExprDelete(db, pDup);
74781         }
74782       }
74783       if( iCol>0 ){
74784         /* Convert the ORDER BY term into an integer column number iCol,
74785         ** taking care to preserve the COLLATE clause if it exists */
74786         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
74787         if( pNew==0 ) return 1;
74788         pNew->flags |= EP_IntValue;
74789         pNew->u.iValue = iCol;
74790         if( pItem->pExpr==pE ){
74791           pItem->pExpr = pNew;
74792         }else{
74793           assert( pItem->pExpr->op==TK_COLLATE );
74794           assert( pItem->pExpr->pLeft==pE );
74795           pItem->pExpr->pLeft = pNew;
74796         }
74797         sqlite3ExprDelete(db, pE);
74798         pItem->iOrderByCol = (u16)iCol;
74799         pItem->done = 1;
74800       }else{
74801         moreToDo = 1;
74802       }
74803     }
74804     pSelect = pSelect->pNext;
74805   }
74806   for(i=0; i<pOrderBy->nExpr; i++){
74807     if( pOrderBy->a[i].done==0 ){
74808       sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
74809             "column in the result set", i+1);
74810       return 1;
74811     }
74812   }
74813   return 0;
74814 }
74815
74816 /*
74817 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
74818 ** the SELECT statement pSelect.  If any term is reference to a
74819 ** result set expression (as determined by the ExprList.a.iCol field)
74820 ** then convert that term into a copy of the corresponding result set
74821 ** column.
74822 **
74823 ** If any errors are detected, add an error message to pParse and
74824 ** return non-zero.  Return zero if no errors are seen.
74825 */
74826 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
74827   Parse *pParse,        /* Parsing context.  Leave error messages here */
74828   Select *pSelect,      /* The SELECT statement containing the clause */
74829   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
74830   const char *zType     /* "ORDER" or "GROUP" */
74831 ){
74832   int i;
74833   sqlite3 *db = pParse->db;
74834   ExprList *pEList;
74835   struct ExprList_item *pItem;
74836
74837   if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
74838 #if SQLITE_MAX_COLUMN
74839   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
74840     sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
74841     return 1;
74842   }
74843 #endif
74844   pEList = pSelect->pEList;
74845   assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
74846   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
74847     if( pItem->iOrderByCol ){
74848       if( pItem->iOrderByCol>pEList->nExpr ){
74849         resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
74850         return 1;
74851       }
74852       resolveAlias(pParse, pEList, pItem->iOrderByCol-1, pItem->pExpr, zType,0);
74853     }
74854   }
74855   return 0;
74856 }
74857
74858 /*
74859 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
74860 ** The Name context of the SELECT statement is pNC.  zType is either
74861 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
74862 **
74863 ** This routine resolves each term of the clause into an expression.
74864 ** If the order-by term is an integer I between 1 and N (where N is the
74865 ** number of columns in the result set of the SELECT) then the expression
74866 ** in the resolution is a copy of the I-th result-set expression.  If
74867 ** the order-by term is an identify that corresponds to the AS-name of
74868 ** a result-set expression, then the term resolves to a copy of the
74869 ** result-set expression.  Otherwise, the expression is resolved in
74870 ** the usual way - using sqlite3ResolveExprNames().
74871 **
74872 ** This routine returns the number of errors.  If errors occur, then
74873 ** an appropriate error message might be left in pParse.  (OOM errors
74874 ** excepted.)
74875 */
74876 static int resolveOrderGroupBy(
74877   NameContext *pNC,     /* The name context of the SELECT statement */
74878   Select *pSelect,      /* The SELECT statement holding pOrderBy */
74879   ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
74880   const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
74881 ){
74882   int i, j;                      /* Loop counters */
74883   int iCol;                      /* Column number */
74884   struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
74885   Parse *pParse;                 /* Parsing context */
74886   int nResult;                   /* Number of terms in the result set */
74887
74888   if( pOrderBy==0 ) return 0;
74889   nResult = pSelect->pEList->nExpr;
74890   pParse = pNC->pParse;
74891   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
74892     Expr *pE = pItem->pExpr;
74893     iCol = resolveAsName(pParse, pSelect->pEList, pE);
74894     if( iCol>0 ){
74895       /* If an AS-name match is found, mark this ORDER BY column as being
74896       ** a copy of the iCol-th result-set column.  The subsequent call to
74897       ** sqlite3ResolveOrderGroupBy() will convert the expression to a
74898       ** copy of the iCol-th result-set expression. */
74899       pItem->iOrderByCol = (u16)iCol;
74900       continue;
74901     }
74902     if( sqlite3ExprIsInteger(sqlite3ExprSkipCollate(pE), &iCol) ){
74903       /* The ORDER BY term is an integer constant.  Again, set the column
74904       ** number so that sqlite3ResolveOrderGroupBy() will convert the
74905       ** order-by term to a copy of the result-set expression */
74906       if( iCol<1 || iCol>0xffff ){
74907         resolveOutOfRangeError(pParse, zType, i+1, nResult);
74908         return 1;
74909       }
74910       pItem->iOrderByCol = (u16)iCol;
74911       continue;
74912     }
74913
74914     /* Otherwise, treat the ORDER BY term as an ordinary expression */
74915     pItem->iOrderByCol = 0;
74916     if( sqlite3ResolveExprNames(pNC, pE) ){
74917       return 1;
74918     }
74919     for(j=0; j<pSelect->pEList->nExpr; j++){
74920       if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr)==0 ){
74921         pItem->iOrderByCol = j+1;
74922       }
74923     }
74924   }
74925   return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
74926 }
74927
74928 /*
74929 ** Resolve names in the SELECT statement p and all of its descendents.
74930 */
74931 static int resolveSelectStep(Walker *pWalker, Select *p){
74932   NameContext *pOuterNC;  /* Context that contains this SELECT */
74933   NameContext sNC;        /* Name context of this SELECT */
74934   int isCompound;         /* True if p is a compound select */
74935   int nCompound;          /* Number of compound terms processed so far */
74936   Parse *pParse;          /* Parsing context */
74937   ExprList *pEList;       /* Result set expression list */
74938   int i;                  /* Loop counter */
74939   ExprList *pGroupBy;     /* The GROUP BY clause */
74940   Select *pLeftmost;      /* Left-most of SELECT of a compound */
74941   sqlite3 *db;            /* Database connection */
74942   
74943
74944   assert( p!=0 );
74945   if( p->selFlags & SF_Resolved ){
74946     return WRC_Prune;
74947   }
74948   pOuterNC = pWalker->u.pNC;
74949   pParse = pWalker->pParse;
74950   db = pParse->db;
74951
74952   /* Normally sqlite3SelectExpand() will be called first and will have
74953   ** already expanded this SELECT.  However, if this is a subquery within
74954   ** an expression, sqlite3ResolveExprNames() will be called without a
74955   ** prior call to sqlite3SelectExpand().  When that happens, let
74956   ** sqlite3SelectPrep() do all of the processing for this SELECT.
74957   ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
74958   ** this routine in the correct order.
74959   */
74960   if( (p->selFlags & SF_Expanded)==0 ){
74961     sqlite3SelectPrep(pParse, p, pOuterNC);
74962     return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
74963   }
74964
74965   isCompound = p->pPrior!=0;
74966   nCompound = 0;
74967   pLeftmost = p;
74968   while( p ){
74969     assert( (p->selFlags & SF_Expanded)!=0 );
74970     assert( (p->selFlags & SF_Resolved)==0 );
74971     p->selFlags |= SF_Resolved;
74972
74973     /* Resolve the expressions in the LIMIT and OFFSET clauses. These
74974     ** are not allowed to refer to any names, so pass an empty NameContext.
74975     */
74976     memset(&sNC, 0, sizeof(sNC));
74977     sNC.pParse = pParse;
74978     if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
74979         sqlite3ResolveExprNames(&sNC, p->pOffset) ){
74980       return WRC_Abort;
74981     }
74982   
74983     /* Recursively resolve names in all subqueries
74984     */
74985     for(i=0; i<p->pSrc->nSrc; i++){
74986       struct SrcList_item *pItem = &p->pSrc->a[i];
74987       if( pItem->pSelect ){
74988         NameContext *pNC;         /* Used to iterate name contexts */
74989         int nRef = 0;             /* Refcount for pOuterNC and outer contexts */
74990         const char *zSavedContext = pParse->zAuthContext;
74991
74992         /* Count the total number of references to pOuterNC and all of its
74993         ** parent contexts. After resolving references to expressions in
74994         ** pItem->pSelect, check if this value has changed. If so, then
74995         ** SELECT statement pItem->pSelect must be correlated. Set the
74996         ** pItem->isCorrelated flag if this is the case. */
74997         for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
74998
74999         if( pItem->zName ) pParse->zAuthContext = pItem->zName;
75000         sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
75001         pParse->zAuthContext = zSavedContext;
75002         if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
75003
75004         for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
75005         assert( pItem->isCorrelated==0 && nRef<=0 );
75006         pItem->isCorrelated = (nRef!=0);
75007       }
75008     }
75009   
75010     /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
75011     ** resolve the result-set expression list.
75012     */
75013     sNC.ncFlags = NC_AllowAgg;
75014     sNC.pSrcList = p->pSrc;
75015     sNC.pNext = pOuterNC;
75016   
75017     /* Resolve names in the result set. */
75018     pEList = p->pEList;
75019     assert( pEList!=0 );
75020     for(i=0; i<pEList->nExpr; i++){
75021       Expr *pX = pEList->a[i].pExpr;
75022       if( sqlite3ResolveExprNames(&sNC, pX) ){
75023         return WRC_Abort;
75024       }
75025     }
75026   
75027     /* If there are no aggregate functions in the result-set, and no GROUP BY 
75028     ** expression, do not allow aggregates in any of the other expressions.
75029     */
75030     assert( (p->selFlags & SF_Aggregate)==0 );
75031     pGroupBy = p->pGroupBy;
75032     if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
75033       p->selFlags |= SF_Aggregate;
75034     }else{
75035       sNC.ncFlags &= ~NC_AllowAgg;
75036     }
75037   
75038     /* If a HAVING clause is present, then there must be a GROUP BY clause.
75039     */
75040     if( p->pHaving && !pGroupBy ){
75041       sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
75042       return WRC_Abort;
75043     }
75044   
75045     /* Add the expression list to the name-context before parsing the
75046     ** other expressions in the SELECT statement. This is so that
75047     ** expressions in the WHERE clause (etc.) can refer to expressions by
75048     ** aliases in the result set.
75049     **
75050     ** Minor point: If this is the case, then the expression will be
75051     ** re-evaluated for each reference to it.
75052     */
75053     sNC.pEList = p->pEList;
75054     sNC.ncFlags |= NC_AsMaybe;
75055     if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
75056     if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
75057     sNC.ncFlags &= ~NC_AsMaybe;
75058
75059     /* The ORDER BY and GROUP BY clauses may not refer to terms in
75060     ** outer queries 
75061     */
75062     sNC.pNext = 0;
75063     sNC.ncFlags |= NC_AllowAgg;
75064
75065     /* Process the ORDER BY clause for singleton SELECT statements.
75066     ** The ORDER BY clause for compounds SELECT statements is handled
75067     ** below, after all of the result-sets for all of the elements of
75068     ** the compound have been resolved.
75069     */
75070     if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
75071       return WRC_Abort;
75072     }
75073     if( db->mallocFailed ){
75074       return WRC_Abort;
75075     }
75076   
75077     /* Resolve the GROUP BY clause.  At the same time, make sure 
75078     ** the GROUP BY clause does not contain aggregate functions.
75079     */
75080     if( pGroupBy ){
75081       struct ExprList_item *pItem;
75082     
75083       if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
75084         return WRC_Abort;
75085       }
75086       for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
75087         if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
75088           sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
75089               "the GROUP BY clause");
75090           return WRC_Abort;
75091         }
75092       }
75093     }
75094
75095     /* Advance to the next term of the compound
75096     */
75097     p = p->pPrior;
75098     nCompound++;
75099   }
75100
75101   /* Resolve the ORDER BY on a compound SELECT after all terms of
75102   ** the compound have been resolved.
75103   */
75104   if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
75105     return WRC_Abort;
75106   }
75107
75108   return WRC_Prune;
75109 }
75110
75111 /*
75112 ** This routine walks an expression tree and resolves references to
75113 ** table columns and result-set columns.  At the same time, do error
75114 ** checking on function usage and set a flag if any aggregate functions
75115 ** are seen.
75116 **
75117 ** To resolve table columns references we look for nodes (or subtrees) of the 
75118 ** form X.Y.Z or Y.Z or just Z where
75119 **
75120 **      X:   The name of a database.  Ex:  "main" or "temp" or
75121 **           the symbolic name assigned to an ATTACH-ed database.
75122 **
75123 **      Y:   The name of a table in a FROM clause.  Or in a trigger
75124 **           one of the special names "old" or "new".
75125 **
75126 **      Z:   The name of a column in table Y.
75127 **
75128 ** The node at the root of the subtree is modified as follows:
75129 **
75130 **    Expr.op        Changed to TK_COLUMN
75131 **    Expr.pTab      Points to the Table object for X.Y
75132 **    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
75133 **    Expr.iTable    The VDBE cursor number for X.Y
75134 **
75135 **
75136 ** To resolve result-set references, look for expression nodes of the
75137 ** form Z (with no X and Y prefix) where the Z matches the right-hand
75138 ** size of an AS clause in the result-set of a SELECT.  The Z expression
75139 ** is replaced by a copy of the left-hand side of the result-set expression.
75140 ** Table-name and function resolution occurs on the substituted expression
75141 ** tree.  For example, in:
75142 **
75143 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
75144 **
75145 ** The "x" term of the order by is replaced by "a+b" to render:
75146 **
75147 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
75148 **
75149 ** Function calls are checked to make sure that the function is 
75150 ** defined and that the correct number of arguments are specified.
75151 ** If the function is an aggregate function, then the NC_HasAgg flag is
75152 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
75153 ** If an expression contains aggregate functions then the EP_Agg
75154 ** property on the expression is set.
75155 **
75156 ** An error message is left in pParse if anything is amiss.  The number
75157 ** if errors is returned.
75158 */
75159 SQLITE_PRIVATE int sqlite3ResolveExprNames( 
75160   NameContext *pNC,       /* Namespace to resolve expressions in. */
75161   Expr *pExpr             /* The expression to be analyzed. */
75162 ){
75163   u8 savedHasAgg;
75164   Walker w;
75165
75166   if( pExpr==0 ) return 0;
75167 #if SQLITE_MAX_EXPR_DEPTH>0
75168   {
75169     Parse *pParse = pNC->pParse;
75170     if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
75171       return 1;
75172     }
75173     pParse->nHeight += pExpr->nHeight;
75174   }
75175 #endif
75176   savedHasAgg = pNC->ncFlags & NC_HasAgg;
75177   pNC->ncFlags &= ~NC_HasAgg;
75178   memset(&w, 0, sizeof(w));
75179   w.xExprCallback = resolveExprStep;
75180   w.xSelectCallback = resolveSelectStep;
75181   w.pParse = pNC->pParse;
75182   w.u.pNC = pNC;
75183   sqlite3WalkExpr(&w, pExpr);
75184 #if SQLITE_MAX_EXPR_DEPTH>0
75185   pNC->pParse->nHeight -= pExpr->nHeight;
75186 #endif
75187   if( pNC->nErr>0 || w.pParse->nErr>0 ){
75188     ExprSetProperty(pExpr, EP_Error);
75189   }
75190   if( pNC->ncFlags & NC_HasAgg ){
75191     ExprSetProperty(pExpr, EP_Agg);
75192   }else if( savedHasAgg ){
75193     pNC->ncFlags |= NC_HasAgg;
75194   }
75195   return ExprHasProperty(pExpr, EP_Error);
75196 }
75197
75198
75199 /*
75200 ** Resolve all names in all expressions of a SELECT and in all
75201 ** decendents of the SELECT, including compounds off of p->pPrior,
75202 ** subqueries in expressions, and subqueries used as FROM clause
75203 ** terms.
75204 **
75205 ** See sqlite3ResolveExprNames() for a description of the kinds of
75206 ** transformations that occur.
75207 **
75208 ** All SELECT statements should have been expanded using
75209 ** sqlite3SelectExpand() prior to invoking this routine.
75210 */
75211 SQLITE_PRIVATE void sqlite3ResolveSelectNames(
75212   Parse *pParse,         /* The parser context */
75213   Select *p,             /* The SELECT statement being coded. */
75214   NameContext *pOuterNC  /* Name context for parent SELECT statement */
75215 ){
75216   Walker w;
75217
75218   assert( p!=0 );
75219   memset(&w, 0, sizeof(w));
75220   w.xExprCallback = resolveExprStep;
75221   w.xSelectCallback = resolveSelectStep;
75222   w.pParse = pParse;
75223   w.u.pNC = pOuterNC;
75224   sqlite3WalkSelect(&w, p);
75225 }
75226
75227 /************** End of resolve.c *********************************************/
75228 /************** Begin file expr.c ********************************************/
75229 /*
75230 ** 2001 September 15
75231 **
75232 ** The author disclaims copyright to this source code.  In place of
75233 ** a legal notice, here is a blessing:
75234 **
75235 **    May you do good and not evil.
75236 **    May you find forgiveness for yourself and forgive others.
75237 **    May you share freely, never taking more than you give.
75238 **
75239 *************************************************************************
75240 ** This file contains routines used for analyzing expressions and
75241 ** for generating VDBE code that evaluates expressions in SQLite.
75242 */
75243
75244 /*
75245 ** Return the 'affinity' of the expression pExpr if any.
75246 **
75247 ** If pExpr is a column, a reference to a column via an 'AS' alias,
75248 ** or a sub-select with a column as the return value, then the 
75249 ** affinity of that column is returned. Otherwise, 0x00 is returned,
75250 ** indicating no affinity for the expression.
75251 **
75252 ** i.e. the WHERE clause expresssions in the following statements all
75253 ** have an affinity:
75254 **
75255 ** CREATE TABLE t1(a);
75256 ** SELECT * FROM t1 WHERE a;
75257 ** SELECT a AS b FROM t1 WHERE b;
75258 ** SELECT * FROM t1 WHERE (select a from t1);
75259 */
75260 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
75261   int op;
75262   pExpr = sqlite3ExprSkipCollate(pExpr);
75263   op = pExpr->op;
75264   if( op==TK_SELECT ){
75265     assert( pExpr->flags&EP_xIsSelect );
75266     return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
75267   }
75268 #ifndef SQLITE_OMIT_CAST
75269   if( op==TK_CAST ){
75270     assert( !ExprHasProperty(pExpr, EP_IntValue) );
75271     return sqlite3AffinityType(pExpr->u.zToken);
75272   }
75273 #endif
75274   if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER) 
75275    && pExpr->pTab!=0
75276   ){
75277     /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
75278     ** a TK_COLUMN but was previously evaluated and cached in a register */
75279     int j = pExpr->iColumn;
75280     if( j<0 ) return SQLITE_AFF_INTEGER;
75281     assert( pExpr->pTab && j<pExpr->pTab->nCol );
75282     return pExpr->pTab->aCol[j].affinity;
75283   }
75284   return pExpr->affinity;
75285 }
75286
75287 /*
75288 ** Set the collating sequence for expression pExpr to be the collating
75289 ** sequence named by pToken.   Return a pointer to a new Expr node that
75290 ** implements the COLLATE operator.
75291 **
75292 ** If a memory allocation error occurs, that fact is recorded in pParse->db
75293 ** and the pExpr parameter is returned unchanged.
75294 */
75295 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr *pExpr, Token *pCollName){
75296   if( pCollName->n>0 ){
75297     Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, 1);
75298     if( pNew ){
75299       pNew->pLeft = pExpr;
75300       pNew->flags |= EP_Collate;
75301       pExpr = pNew;
75302     }
75303   }
75304   return pExpr;
75305 }
75306 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
75307   Token s;
75308   assert( zC!=0 );
75309   s.z = zC;
75310   s.n = sqlite3Strlen30(s.z);
75311   return sqlite3ExprAddCollateToken(pParse, pExpr, &s);
75312 }
75313
75314 /*
75315 ** Skip over any TK_COLLATE and/or TK_AS operators at the root of
75316 ** an expression.
75317 */
75318 SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
75319   while( pExpr && (pExpr->op==TK_COLLATE || pExpr->op==TK_AS) ){
75320     pExpr = pExpr->pLeft;
75321   }
75322   return pExpr;
75323 }
75324
75325 /*
75326 ** Return the collation sequence for the expression pExpr. If
75327 ** there is no defined collating sequence, return NULL.
75328 **
75329 ** The collating sequence might be determined by a COLLATE operator
75330 ** or by the presence of a column with a defined collating sequence.
75331 ** COLLATE operators take first precedence.  Left operands take
75332 ** precedence over right operands.
75333 */
75334 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
75335   sqlite3 *db = pParse->db;
75336   CollSeq *pColl = 0;
75337   Expr *p = pExpr;
75338   while( p ){
75339     int op = p->op;
75340     if( op==TK_CAST || op==TK_UPLUS ){
75341       p = p->pLeft;
75342       continue;
75343     }
75344     assert( op!=TK_REGISTER || p->op2!=TK_COLLATE );
75345     if( op==TK_COLLATE ){
75346       pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
75347       break;
75348     }
75349     if( p->pTab!=0
75350      && (op==TK_AGG_COLUMN || op==TK_COLUMN
75351           || op==TK_REGISTER || op==TK_TRIGGER)
75352     ){
75353       /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
75354       ** a TK_COLUMN but was previously evaluated and cached in a register */
75355       int j = p->iColumn;
75356       if( j>=0 ){
75357         const char *zColl = p->pTab->aCol[j].zColl;
75358         pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
75359       }
75360       break;
75361     }
75362     if( p->flags & EP_Collate ){
75363       if( ALWAYS(p->pLeft) && (p->pLeft->flags & EP_Collate)!=0 ){
75364         p = p->pLeft;
75365       }else{
75366         p = p->pRight;
75367       }
75368     }else{
75369       break;
75370     }
75371   }
75372   if( sqlite3CheckCollSeq(pParse, pColl) ){ 
75373     pColl = 0;
75374   }
75375   return pColl;
75376 }
75377
75378 /*
75379 ** pExpr is an operand of a comparison operator.  aff2 is the
75380 ** type affinity of the other operand.  This routine returns the
75381 ** type affinity that should be used for the comparison operator.
75382 */
75383 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
75384   char aff1 = sqlite3ExprAffinity(pExpr);
75385   if( aff1 && aff2 ){
75386     /* Both sides of the comparison are columns. If one has numeric
75387     ** affinity, use that. Otherwise use no affinity.
75388     */
75389     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
75390       return SQLITE_AFF_NUMERIC;
75391     }else{
75392       return SQLITE_AFF_NONE;
75393     }
75394   }else if( !aff1 && !aff2 ){
75395     /* Neither side of the comparison is a column.  Compare the
75396     ** results directly.
75397     */
75398     return SQLITE_AFF_NONE;
75399   }else{
75400     /* One side is a column, the other is not. Use the columns affinity. */
75401     assert( aff1==0 || aff2==0 );
75402     return (aff1 + aff2);
75403   }
75404 }
75405
75406 /*
75407 ** pExpr is a comparison operator.  Return the type affinity that should
75408 ** be applied to both operands prior to doing the comparison.
75409 */
75410 static char comparisonAffinity(Expr *pExpr){
75411   char aff;
75412   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
75413           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
75414           pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
75415   assert( pExpr->pLeft );
75416   aff = sqlite3ExprAffinity(pExpr->pLeft);
75417   if( pExpr->pRight ){
75418     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
75419   }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
75420     aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
75421   }else if( !aff ){
75422     aff = SQLITE_AFF_NONE;
75423   }
75424   return aff;
75425 }
75426
75427 /*
75428 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
75429 ** idx_affinity is the affinity of an indexed column. Return true
75430 ** if the index with affinity idx_affinity may be used to implement
75431 ** the comparison in pExpr.
75432 */
75433 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
75434   char aff = comparisonAffinity(pExpr);
75435   switch( aff ){
75436     case SQLITE_AFF_NONE:
75437       return 1;
75438     case SQLITE_AFF_TEXT:
75439       return idx_affinity==SQLITE_AFF_TEXT;
75440     default:
75441       return sqlite3IsNumericAffinity(idx_affinity);
75442   }
75443 }
75444
75445 /*
75446 ** Return the P5 value that should be used for a binary comparison
75447 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
75448 */
75449 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
75450   u8 aff = (char)sqlite3ExprAffinity(pExpr2);
75451   aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
75452   return aff;
75453 }
75454
75455 /*
75456 ** Return a pointer to the collation sequence that should be used by
75457 ** a binary comparison operator comparing pLeft and pRight.
75458 **
75459 ** If the left hand expression has a collating sequence type, then it is
75460 ** used. Otherwise the collation sequence for the right hand expression
75461 ** is used, or the default (BINARY) if neither expression has a collating
75462 ** type.
75463 **
75464 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
75465 ** it is not considered.
75466 */
75467 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
75468   Parse *pParse, 
75469   Expr *pLeft, 
75470   Expr *pRight
75471 ){
75472   CollSeq *pColl;
75473   assert( pLeft );
75474   if( pLeft->flags & EP_Collate ){
75475     pColl = sqlite3ExprCollSeq(pParse, pLeft);
75476   }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
75477     pColl = sqlite3ExprCollSeq(pParse, pRight);
75478   }else{
75479     pColl = sqlite3ExprCollSeq(pParse, pLeft);
75480     if( !pColl ){
75481       pColl = sqlite3ExprCollSeq(pParse, pRight);
75482     }
75483   }
75484   return pColl;
75485 }
75486
75487 /*
75488 ** Generate code for a comparison operator.
75489 */
75490 static int codeCompare(
75491   Parse *pParse,    /* The parsing (and code generating) context */
75492   Expr *pLeft,      /* The left operand */
75493   Expr *pRight,     /* The right operand */
75494   int opcode,       /* The comparison opcode */
75495   int in1, int in2, /* Register holding operands */
75496   int dest,         /* Jump here if true.  */
75497   int jumpIfNull    /* If true, jump if either operand is NULL */
75498 ){
75499   int p5;
75500   int addr;
75501   CollSeq *p4;
75502
75503   p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
75504   p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
75505   addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
75506                            (void*)p4, P4_COLLSEQ);
75507   sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
75508   return addr;
75509 }
75510
75511 #if SQLITE_MAX_EXPR_DEPTH>0
75512 /*
75513 ** Check that argument nHeight is less than or equal to the maximum
75514 ** expression depth allowed. If it is not, leave an error message in
75515 ** pParse.
75516 */
75517 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
75518   int rc = SQLITE_OK;
75519   int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
75520   if( nHeight>mxHeight ){
75521     sqlite3ErrorMsg(pParse, 
75522        "Expression tree is too large (maximum depth %d)", mxHeight
75523     );
75524     rc = SQLITE_ERROR;
75525   }
75526   return rc;
75527 }
75528
75529 /* The following three functions, heightOfExpr(), heightOfExprList()
75530 ** and heightOfSelect(), are used to determine the maximum height
75531 ** of any expression tree referenced by the structure passed as the
75532 ** first argument.
75533 **
75534 ** If this maximum height is greater than the current value pointed
75535 ** to by pnHeight, the second parameter, then set *pnHeight to that
75536 ** value.
75537 */
75538 static void heightOfExpr(Expr *p, int *pnHeight){
75539   if( p ){
75540     if( p->nHeight>*pnHeight ){
75541       *pnHeight = p->nHeight;
75542     }
75543   }
75544 }
75545 static void heightOfExprList(ExprList *p, int *pnHeight){
75546   if( p ){
75547     int i;
75548     for(i=0; i<p->nExpr; i++){
75549       heightOfExpr(p->a[i].pExpr, pnHeight);
75550     }
75551   }
75552 }
75553 static void heightOfSelect(Select *p, int *pnHeight){
75554   if( p ){
75555     heightOfExpr(p->pWhere, pnHeight);
75556     heightOfExpr(p->pHaving, pnHeight);
75557     heightOfExpr(p->pLimit, pnHeight);
75558     heightOfExpr(p->pOffset, pnHeight);
75559     heightOfExprList(p->pEList, pnHeight);
75560     heightOfExprList(p->pGroupBy, pnHeight);
75561     heightOfExprList(p->pOrderBy, pnHeight);
75562     heightOfSelect(p->pPrior, pnHeight);
75563   }
75564 }
75565
75566 /*
75567 ** Set the Expr.nHeight variable in the structure passed as an 
75568 ** argument. An expression with no children, Expr.pList or 
75569 ** Expr.pSelect member has a height of 1. Any other expression
75570 ** has a height equal to the maximum height of any other 
75571 ** referenced Expr plus one.
75572 */
75573 static void exprSetHeight(Expr *p){
75574   int nHeight = 0;
75575   heightOfExpr(p->pLeft, &nHeight);
75576   heightOfExpr(p->pRight, &nHeight);
75577   if( ExprHasProperty(p, EP_xIsSelect) ){
75578     heightOfSelect(p->x.pSelect, &nHeight);
75579   }else{
75580     heightOfExprList(p->x.pList, &nHeight);
75581   }
75582   p->nHeight = nHeight + 1;
75583 }
75584
75585 /*
75586 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
75587 ** the height is greater than the maximum allowed expression depth,
75588 ** leave an error in pParse.
75589 */
75590 SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
75591   exprSetHeight(p);
75592   sqlite3ExprCheckHeight(pParse, p->nHeight);
75593 }
75594
75595 /*
75596 ** Return the maximum height of any expression tree referenced
75597 ** by the select statement passed as an argument.
75598 */
75599 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
75600   int nHeight = 0;
75601   heightOfSelect(p, &nHeight);
75602   return nHeight;
75603 }
75604 #else
75605   #define exprSetHeight(y)
75606 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
75607
75608 /*
75609 ** This routine is the core allocator for Expr nodes.
75610 **
75611 ** Construct a new expression node and return a pointer to it.  Memory
75612 ** for this node and for the pToken argument is a single allocation
75613 ** obtained from sqlite3DbMalloc().  The calling function
75614 ** is responsible for making sure the node eventually gets freed.
75615 **
75616 ** If dequote is true, then the token (if it exists) is dequoted.
75617 ** If dequote is false, no dequoting is performance.  The deQuote
75618 ** parameter is ignored if pToken is NULL or if the token does not
75619 ** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
75620 ** then the EP_DblQuoted flag is set on the expression node.
75621 **
75622 ** Special case:  If op==TK_INTEGER and pToken points to a string that
75623 ** can be translated into a 32-bit integer, then the token is not
75624 ** stored in u.zToken.  Instead, the integer values is written
75625 ** into u.iValue and the EP_IntValue flag is set.  No extra storage
75626 ** is allocated to hold the integer text and the dequote flag is ignored.
75627 */
75628 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
75629   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
75630   int op,                 /* Expression opcode */
75631   const Token *pToken,    /* Token argument.  Might be NULL */
75632   int dequote             /* True to dequote */
75633 ){
75634   Expr *pNew;
75635   int nExtra = 0;
75636   int iValue = 0;
75637
75638   if( pToken ){
75639     if( op!=TK_INTEGER || pToken->z==0
75640           || sqlite3GetInt32(pToken->z, &iValue)==0 ){
75641       nExtra = pToken->n+1;
75642       assert( iValue>=0 );
75643     }
75644   }
75645   pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
75646   if( pNew ){
75647     pNew->op = (u8)op;
75648     pNew->iAgg = -1;
75649     if( pToken ){
75650       if( nExtra==0 ){
75651         pNew->flags |= EP_IntValue;
75652         pNew->u.iValue = iValue;
75653       }else{
75654         int c;
75655         pNew->u.zToken = (char*)&pNew[1];
75656         assert( pToken->z!=0 || pToken->n==0 );
75657         if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
75658         pNew->u.zToken[pToken->n] = 0;
75659         if( dequote && nExtra>=3 
75660              && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
75661           sqlite3Dequote(pNew->u.zToken);
75662           if( c=='"' ) pNew->flags |= EP_DblQuoted;
75663         }
75664       }
75665     }
75666 #if SQLITE_MAX_EXPR_DEPTH>0
75667     pNew->nHeight = 1;
75668 #endif  
75669   }
75670   return pNew;
75671 }
75672
75673 /*
75674 ** Allocate a new expression node from a zero-terminated token that has
75675 ** already been dequoted.
75676 */
75677 SQLITE_PRIVATE Expr *sqlite3Expr(
75678   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
75679   int op,                 /* Expression opcode */
75680   const char *zToken      /* Token argument.  Might be NULL */
75681 ){
75682   Token x;
75683   x.z = zToken;
75684   x.n = zToken ? sqlite3Strlen30(zToken) : 0;
75685   return sqlite3ExprAlloc(db, op, &x, 0);
75686 }
75687
75688 /*
75689 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
75690 **
75691 ** If pRoot==NULL that means that a memory allocation error has occurred.
75692 ** In that case, delete the subtrees pLeft and pRight.
75693 */
75694 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
75695   sqlite3 *db,
75696   Expr *pRoot,
75697   Expr *pLeft,
75698   Expr *pRight
75699 ){
75700   if( pRoot==0 ){
75701     assert( db->mallocFailed );
75702     sqlite3ExprDelete(db, pLeft);
75703     sqlite3ExprDelete(db, pRight);
75704   }else{
75705     if( pRight ){
75706       pRoot->pRight = pRight;
75707       pRoot->flags |= EP_Collate & pRight->flags;
75708     }
75709     if( pLeft ){
75710       pRoot->pLeft = pLeft;
75711       pRoot->flags |= EP_Collate & pLeft->flags;
75712     }
75713     exprSetHeight(pRoot);
75714   }
75715 }
75716
75717 /*
75718 ** Allocate a Expr node which joins as many as two subtrees.
75719 **
75720 ** One or both of the subtrees can be NULL.  Return a pointer to the new
75721 ** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
75722 ** free the subtrees and return NULL.
75723 */
75724 SQLITE_PRIVATE Expr *sqlite3PExpr(
75725   Parse *pParse,          /* Parsing context */
75726   int op,                 /* Expression opcode */
75727   Expr *pLeft,            /* Left operand */
75728   Expr *pRight,           /* Right operand */
75729   const Token *pToken     /* Argument token */
75730 ){
75731   Expr *p;
75732   if( op==TK_AND && pLeft && pRight ){
75733     /* Take advantage of short-circuit false optimization for AND */
75734     p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
75735   }else{
75736     p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
75737     sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
75738   }
75739   if( p ) {
75740     sqlite3ExprCheckHeight(pParse, p->nHeight);
75741   }
75742   return p;
75743 }
75744
75745 /*
75746 ** Return 1 if an expression must be FALSE in all cases and 0 if the
75747 ** expression might be true.  This is an optimization.  If is OK to
75748 ** return 0 here even if the expression really is always false (a 
75749 ** false negative).  But it is a bug to return 1 if the expression
75750 ** might be true in some rare circumstances (a false positive.)
75751 **
75752 ** Note that if the expression is part of conditional for a
75753 ** LEFT JOIN, then we cannot determine at compile-time whether or not
75754 ** is it true or false, so always return 0.
75755 */
75756 static int exprAlwaysFalse(Expr *p){
75757   int v = 0;
75758   if( ExprHasProperty(p, EP_FromJoin) ) return 0;
75759   if( !sqlite3ExprIsInteger(p, &v) ) return 0;
75760   return v==0;
75761 }
75762
75763 /*
75764 ** Join two expressions using an AND operator.  If either expression is
75765 ** NULL, then just return the other expression.
75766 **
75767 ** If one side or the other of the AND is known to be false, then instead
75768 ** of returning an AND expression, just return a constant expression with
75769 ** a value of false.
75770 */
75771 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
75772   if( pLeft==0 ){
75773     return pRight;
75774   }else if( pRight==0 ){
75775     return pLeft;
75776   }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
75777     sqlite3ExprDelete(db, pLeft);
75778     sqlite3ExprDelete(db, pRight);
75779     return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
75780   }else{
75781     Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
75782     sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
75783     return pNew;
75784   }
75785 }
75786
75787 /*
75788 ** Construct a new expression node for a function with multiple
75789 ** arguments.
75790 */
75791 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
75792   Expr *pNew;
75793   sqlite3 *db = pParse->db;
75794   assert( pToken );
75795   pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
75796   if( pNew==0 ){
75797     sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
75798     return 0;
75799   }
75800   pNew->x.pList = pList;
75801   assert( !ExprHasProperty(pNew, EP_xIsSelect) );
75802   sqlite3ExprSetHeight(pParse, pNew);
75803   return pNew;
75804 }
75805
75806 /*
75807 ** Assign a variable number to an expression that encodes a wildcard
75808 ** in the original SQL statement.  
75809 **
75810 ** Wildcards consisting of a single "?" are assigned the next sequential
75811 ** variable number.
75812 **
75813 ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
75814 ** sure "nnn" is not too be to avoid a denial of service attack when
75815 ** the SQL statement comes from an external source.
75816 **
75817 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
75818 ** as the previous instance of the same wildcard.  Or if this is the first
75819 ** instance of the wildcard, the next sequenial variable number is
75820 ** assigned.
75821 */
75822 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
75823   sqlite3 *db = pParse->db;
75824   const char *z;
75825
75826   if( pExpr==0 ) return;
75827   assert( !ExprHasAnyProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
75828   z = pExpr->u.zToken;
75829   assert( z!=0 );
75830   assert( z[0]!=0 );
75831   if( z[1]==0 ){
75832     /* Wildcard of the form "?".  Assign the next variable number */
75833     assert( z[0]=='?' );
75834     pExpr->iColumn = (ynVar)(++pParse->nVar);
75835   }else{
75836     ynVar x = 0;
75837     u32 n = sqlite3Strlen30(z);
75838     if( z[0]=='?' ){
75839       /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
75840       ** use it as the variable number */
75841       i64 i;
75842       int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
75843       pExpr->iColumn = x = (ynVar)i;
75844       testcase( i==0 );
75845       testcase( i==1 );
75846       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
75847       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
75848       if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
75849         sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
75850             db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
75851         x = 0;
75852       }
75853       if( i>pParse->nVar ){
75854         pParse->nVar = (int)i;
75855       }
75856     }else{
75857       /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
75858       ** number as the prior appearance of the same name, or if the name
75859       ** has never appeared before, reuse the same variable number
75860       */
75861       ynVar i;
75862       for(i=0; i<pParse->nzVar; i++){
75863         if( pParse->azVar[i] && strcmp(pParse->azVar[i],z)==0 ){
75864           pExpr->iColumn = x = (ynVar)i+1;
75865           break;
75866         }
75867       }
75868       if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
75869     }
75870     if( x>0 ){
75871       if( x>pParse->nzVar ){
75872         char **a;
75873         a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
75874         if( a==0 ) return;  /* Error reported through db->mallocFailed */
75875         pParse->azVar = a;
75876         memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
75877         pParse->nzVar = x;
75878       }
75879       if( z[0]!='?' || pParse->azVar[x-1]==0 ){
75880         sqlite3DbFree(db, pParse->azVar[x-1]);
75881         pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
75882       }
75883     }
75884   } 
75885   if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
75886     sqlite3ErrorMsg(pParse, "too many SQL variables");
75887   }
75888 }
75889
75890 /*
75891 ** Recursively delete an expression tree.
75892 */
75893 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
75894   if( p==0 ) return;
75895   /* Sanity check: Assert that the IntValue is non-negative if it exists */
75896   assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
75897   if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
75898     sqlite3ExprDelete(db, p->pLeft);
75899     sqlite3ExprDelete(db, p->pRight);
75900     if( !ExprHasProperty(p, EP_Reduced) && (p->flags2 & EP2_MallocedToken)!=0 ){
75901       sqlite3DbFree(db, p->u.zToken);
75902     }
75903     if( ExprHasProperty(p, EP_xIsSelect) ){
75904       sqlite3SelectDelete(db, p->x.pSelect);
75905     }else{
75906       sqlite3ExprListDelete(db, p->x.pList);
75907     }
75908   }
75909   if( !ExprHasProperty(p, EP_Static) ){
75910     sqlite3DbFree(db, p);
75911   }
75912 }
75913
75914 /*
75915 ** Return the number of bytes allocated for the expression structure 
75916 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
75917 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
75918 */
75919 static int exprStructSize(Expr *p){
75920   if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
75921   if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
75922   return EXPR_FULLSIZE;
75923 }
75924
75925 /*
75926 ** The dupedExpr*Size() routines each return the number of bytes required
75927 ** to store a copy of an expression or expression tree.  They differ in
75928 ** how much of the tree is measured.
75929 **
75930 **     dupedExprStructSize()     Size of only the Expr structure 
75931 **     dupedExprNodeSize()       Size of Expr + space for token
75932 **     dupedExprSize()           Expr + token + subtree components
75933 **
75934 ***************************************************************************
75935 **
75936 ** The dupedExprStructSize() function returns two values OR-ed together:  
75937 ** (1) the space required for a copy of the Expr structure only and 
75938 ** (2) the EP_xxx flags that indicate what the structure size should be.
75939 ** The return values is always one of:
75940 **
75941 **      EXPR_FULLSIZE
75942 **      EXPR_REDUCEDSIZE   | EP_Reduced
75943 **      EXPR_TOKENONLYSIZE | EP_TokenOnly
75944 **
75945 ** The size of the structure can be found by masking the return value
75946 ** of this routine with 0xfff.  The flags can be found by masking the
75947 ** return value with EP_Reduced|EP_TokenOnly.
75948 **
75949 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
75950 ** (unreduced) Expr objects as they or originally constructed by the parser.
75951 ** During expression analysis, extra information is computed and moved into
75952 ** later parts of teh Expr object and that extra information might get chopped
75953 ** off if the expression is reduced.  Note also that it does not work to
75954 ** make a EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
75955 ** to reduce a pristine expression tree from the parser.  The implementation
75956 ** of dupedExprStructSize() contain multiple assert() statements that attempt
75957 ** to enforce this constraint.
75958 */
75959 static int dupedExprStructSize(Expr *p, int flags){
75960   int nSize;
75961   assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
75962   if( 0==(flags&EXPRDUP_REDUCE) ){
75963     nSize = EXPR_FULLSIZE;
75964   }else{
75965     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
75966     assert( !ExprHasProperty(p, EP_FromJoin) ); 
75967     assert( (p->flags2 & EP2_MallocedToken)==0 );
75968     assert( (p->flags2 & EP2_Irreducible)==0 );
75969     if( p->pLeft || p->pRight || p->x.pList ){
75970       nSize = EXPR_REDUCEDSIZE | EP_Reduced;
75971     }else{
75972       nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
75973     }
75974   }
75975   return nSize;
75976 }
75977
75978 /*
75979 ** This function returns the space in bytes required to store the copy 
75980 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
75981 ** string is defined.)
75982 */
75983 static int dupedExprNodeSize(Expr *p, int flags){
75984   int nByte = dupedExprStructSize(p, flags) & 0xfff;
75985   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
75986     nByte += sqlite3Strlen30(p->u.zToken)+1;
75987   }
75988   return ROUND8(nByte);
75989 }
75990
75991 /*
75992 ** Return the number of bytes required to create a duplicate of the 
75993 ** expression passed as the first argument. The second argument is a
75994 ** mask containing EXPRDUP_XXX flags.
75995 **
75996 ** The value returned includes space to create a copy of the Expr struct
75997 ** itself and the buffer referred to by Expr.u.zToken, if any.
75998 **
75999 ** If the EXPRDUP_REDUCE flag is set, then the return value includes 
76000 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft 
76001 ** and Expr.pRight variables (but not for any structures pointed to or 
76002 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
76003 */
76004 static int dupedExprSize(Expr *p, int flags){
76005   int nByte = 0;
76006   if( p ){
76007     nByte = dupedExprNodeSize(p, flags);
76008     if( flags&EXPRDUP_REDUCE ){
76009       nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
76010     }
76011   }
76012   return nByte;
76013 }
76014
76015 /*
76016 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer 
76017 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough 
76018 ** to store the copy of expression p, the copies of p->u.zToken
76019 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
76020 ** if any. Before returning, *pzBuffer is set to the first byte passed the
76021 ** portion of the buffer copied into by this function.
76022 */
76023 static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
76024   Expr *pNew = 0;                      /* Value to return */
76025   if( p ){
76026     const int isReduced = (flags&EXPRDUP_REDUCE);
76027     u8 *zAlloc;
76028     u32 staticFlag = 0;
76029
76030     assert( pzBuffer==0 || isReduced );
76031
76032     /* Figure out where to write the new Expr structure. */
76033     if( pzBuffer ){
76034       zAlloc = *pzBuffer;
76035       staticFlag = EP_Static;
76036     }else{
76037       zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
76038     }
76039     pNew = (Expr *)zAlloc;
76040
76041     if( pNew ){
76042       /* Set nNewSize to the size allocated for the structure pointed to
76043       ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
76044       ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
76045       ** by the copy of the p->u.zToken string (if any).
76046       */
76047       const unsigned nStructSize = dupedExprStructSize(p, flags);
76048       const int nNewSize = nStructSize & 0xfff;
76049       int nToken;
76050       if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
76051         nToken = sqlite3Strlen30(p->u.zToken) + 1;
76052       }else{
76053         nToken = 0;
76054       }
76055       if( isReduced ){
76056         assert( ExprHasProperty(p, EP_Reduced)==0 );
76057         memcpy(zAlloc, p, nNewSize);
76058       }else{
76059         int nSize = exprStructSize(p);
76060         memcpy(zAlloc, p, nSize);
76061         memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
76062       }
76063
76064       /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
76065       pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
76066       pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
76067       pNew->flags |= staticFlag;
76068
76069       /* Copy the p->u.zToken string, if any. */
76070       if( nToken ){
76071         char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
76072         memcpy(zToken, p->u.zToken, nToken);
76073       }
76074
76075       if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
76076         /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
76077         if( ExprHasProperty(p, EP_xIsSelect) ){
76078           pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
76079         }else{
76080           pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
76081         }
76082       }
76083
76084       /* Fill in pNew->pLeft and pNew->pRight. */
76085       if( ExprHasAnyProperty(pNew, EP_Reduced|EP_TokenOnly) ){
76086         zAlloc += dupedExprNodeSize(p, flags);
76087         if( ExprHasProperty(pNew, EP_Reduced) ){
76088           pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
76089           pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
76090         }
76091         if( pzBuffer ){
76092           *pzBuffer = zAlloc;
76093         }
76094       }else{
76095         pNew->flags2 = 0;
76096         if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
76097           pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
76098           pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
76099         }
76100       }
76101
76102     }
76103   }
76104   return pNew;
76105 }
76106
76107 /*
76108 ** The following group of routines make deep copies of expressions,
76109 ** expression lists, ID lists, and select statements.  The copies can
76110 ** be deleted (by being passed to their respective ...Delete() routines)
76111 ** without effecting the originals.
76112 **
76113 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
76114 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded 
76115 ** by subsequent calls to sqlite*ListAppend() routines.
76116 **
76117 ** Any tables that the SrcList might point to are not duplicated.
76118 **
76119 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
76120 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
76121 ** truncated version of the usual Expr structure that will be stored as
76122 ** part of the in-memory representation of the database schema.
76123 */
76124 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
76125   return exprDup(db, p, flags, 0);
76126 }
76127 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
76128   ExprList *pNew;
76129   struct ExprList_item *pItem, *pOldItem;
76130   int i;
76131   if( p==0 ) return 0;
76132   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
76133   if( pNew==0 ) return 0;
76134   pNew->iECursor = 0;
76135   pNew->nExpr = i = p->nExpr;
76136   if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
76137   pNew->a = pItem = sqlite3DbMallocRaw(db,  i*sizeof(p->a[0]) );
76138   if( pItem==0 ){
76139     sqlite3DbFree(db, pNew);
76140     return 0;
76141   } 
76142   pOldItem = p->a;
76143   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
76144     Expr *pOldExpr = pOldItem->pExpr;
76145     pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
76146     pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
76147     pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
76148     pItem->sortOrder = pOldItem->sortOrder;
76149     pItem->done = 0;
76150     pItem->iOrderByCol = pOldItem->iOrderByCol;
76151     pItem->iAlias = pOldItem->iAlias;
76152   }
76153   return pNew;
76154 }
76155
76156 /*
76157 ** If cursors, triggers, views and subqueries are all omitted from
76158 ** the build, then none of the following routines, except for 
76159 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
76160 ** called with a NULL argument.
76161 */
76162 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
76163  || !defined(SQLITE_OMIT_SUBQUERY)
76164 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
76165   SrcList *pNew;
76166   int i;
76167   int nByte;
76168   if( p==0 ) return 0;
76169   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
76170   pNew = sqlite3DbMallocRaw(db, nByte );
76171   if( pNew==0 ) return 0;
76172   pNew->nSrc = pNew->nAlloc = p->nSrc;
76173   for(i=0; i<p->nSrc; i++){
76174     struct SrcList_item *pNewItem = &pNew->a[i];
76175     struct SrcList_item *pOldItem = &p->a[i];
76176     Table *pTab;
76177     pNewItem->pSchema = pOldItem->pSchema;
76178     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
76179     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
76180     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
76181     pNewItem->jointype = pOldItem->jointype;
76182     pNewItem->iCursor = pOldItem->iCursor;
76183     pNewItem->addrFillSub = pOldItem->addrFillSub;
76184     pNewItem->regReturn = pOldItem->regReturn;
76185     pNewItem->isCorrelated = pOldItem->isCorrelated;
76186     pNewItem->viaCoroutine = pOldItem->viaCoroutine;
76187     pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
76188     pNewItem->notIndexed = pOldItem->notIndexed;
76189     pNewItem->pIndex = pOldItem->pIndex;
76190     pTab = pNewItem->pTab = pOldItem->pTab;
76191     if( pTab ){
76192       pTab->nRef++;
76193     }
76194     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
76195     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
76196     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
76197     pNewItem->colUsed = pOldItem->colUsed;
76198   }
76199   return pNew;
76200 }
76201 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
76202   IdList *pNew;
76203   int i;
76204   if( p==0 ) return 0;
76205   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
76206   if( pNew==0 ) return 0;
76207   pNew->nId = p->nId;
76208   pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
76209   if( pNew->a==0 ){
76210     sqlite3DbFree(db, pNew);
76211     return 0;
76212   }
76213   /* Note that because the size of the allocation for p->a[] is not
76214   ** necessarily a power of two, sqlite3IdListAppend() may not be called
76215   ** on the duplicate created by this function. */
76216   for(i=0; i<p->nId; i++){
76217     struct IdList_item *pNewItem = &pNew->a[i];
76218     struct IdList_item *pOldItem = &p->a[i];
76219     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
76220     pNewItem->idx = pOldItem->idx;
76221   }
76222   return pNew;
76223 }
76224 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
76225   Select *pNew, *pPrior;
76226   if( p==0 ) return 0;
76227   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
76228   if( pNew==0 ) return 0;
76229   pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
76230   pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
76231   pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
76232   pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
76233   pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
76234   pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
76235   pNew->op = p->op;
76236   pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
76237   if( pPrior ) pPrior->pNext = pNew;
76238   pNew->pNext = 0;
76239   pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
76240   pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
76241   pNew->iLimit = 0;
76242   pNew->iOffset = 0;
76243   pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
76244   pNew->pRightmost = 0;
76245   pNew->addrOpenEphm[0] = -1;
76246   pNew->addrOpenEphm[1] = -1;
76247   pNew->addrOpenEphm[2] = -1;
76248   return pNew;
76249 }
76250 #else
76251 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
76252   assert( p==0 );
76253   return 0;
76254 }
76255 #endif
76256
76257
76258 /*
76259 ** Add a new element to the end of an expression list.  If pList is
76260 ** initially NULL, then create a new expression list.
76261 **
76262 ** If a memory allocation error occurs, the entire list is freed and
76263 ** NULL is returned.  If non-NULL is returned, then it is guaranteed
76264 ** that the new entry was successfully appended.
76265 */
76266 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
76267   Parse *pParse,          /* Parsing context */
76268   ExprList *pList,        /* List to which to append. Might be NULL */
76269   Expr *pExpr             /* Expression to be appended. Might be NULL */
76270 ){
76271   sqlite3 *db = pParse->db;
76272   if( pList==0 ){
76273     pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
76274     if( pList==0 ){
76275       goto no_mem;
76276     }
76277     pList->a = sqlite3DbMallocRaw(db, sizeof(pList->a[0]));
76278     if( pList->a==0 ) goto no_mem;
76279   }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
76280     struct ExprList_item *a;
76281     assert( pList->nExpr>0 );
76282     a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
76283     if( a==0 ){
76284       goto no_mem;
76285     }
76286     pList->a = a;
76287   }
76288   assert( pList->a!=0 );
76289   if( 1 ){
76290     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
76291     memset(pItem, 0, sizeof(*pItem));
76292     pItem->pExpr = pExpr;
76293   }
76294   return pList;
76295
76296 no_mem:     
76297   /* Avoid leaking memory if malloc has failed. */
76298   sqlite3ExprDelete(db, pExpr);
76299   sqlite3ExprListDelete(db, pList);
76300   return 0;
76301 }
76302
76303 /*
76304 ** Set the ExprList.a[].zName element of the most recently added item
76305 ** on the expression list.
76306 **
76307 ** pList might be NULL following an OOM error.  But pName should never be
76308 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
76309 ** is set.
76310 */
76311 SQLITE_PRIVATE void sqlite3ExprListSetName(
76312   Parse *pParse,          /* Parsing context */
76313   ExprList *pList,        /* List to which to add the span. */
76314   Token *pName,           /* Name to be added */
76315   int dequote             /* True to cause the name to be dequoted */
76316 ){
76317   assert( pList!=0 || pParse->db->mallocFailed!=0 );
76318   if( pList ){
76319     struct ExprList_item *pItem;
76320     assert( pList->nExpr>0 );
76321     pItem = &pList->a[pList->nExpr-1];
76322     assert( pItem->zName==0 );
76323     pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
76324     if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
76325   }
76326 }
76327
76328 /*
76329 ** Set the ExprList.a[].zSpan element of the most recently added item
76330 ** on the expression list.
76331 **
76332 ** pList might be NULL following an OOM error.  But pSpan should never be
76333 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
76334 ** is set.
76335 */
76336 SQLITE_PRIVATE void sqlite3ExprListSetSpan(
76337   Parse *pParse,          /* Parsing context */
76338   ExprList *pList,        /* List to which to add the span. */
76339   ExprSpan *pSpan         /* The span to be added */
76340 ){
76341   sqlite3 *db = pParse->db;
76342   assert( pList!=0 || db->mallocFailed!=0 );
76343   if( pList ){
76344     struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
76345     assert( pList->nExpr>0 );
76346     assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
76347     sqlite3DbFree(db, pItem->zSpan);
76348     pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
76349                                     (int)(pSpan->zEnd - pSpan->zStart));
76350   }
76351 }
76352
76353 /*
76354 ** If the expression list pEList contains more than iLimit elements,
76355 ** leave an error message in pParse.
76356 */
76357 SQLITE_PRIVATE void sqlite3ExprListCheckLength(
76358   Parse *pParse,
76359   ExprList *pEList,
76360   const char *zObject
76361 ){
76362   int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
76363   testcase( pEList && pEList->nExpr==mx );
76364   testcase( pEList && pEList->nExpr==mx+1 );
76365   if( pEList && pEList->nExpr>mx ){
76366     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
76367   }
76368 }
76369
76370 /*
76371 ** Delete an entire expression list.
76372 */
76373 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
76374   int i;
76375   struct ExprList_item *pItem;
76376   if( pList==0 ) return;
76377   assert( pList->a!=0 || pList->nExpr==0 );
76378   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
76379     sqlite3ExprDelete(db, pItem->pExpr);
76380     sqlite3DbFree(db, pItem->zName);
76381     sqlite3DbFree(db, pItem->zSpan);
76382   }
76383   sqlite3DbFree(db, pList->a);
76384   sqlite3DbFree(db, pList);
76385 }
76386
76387 /*
76388 ** These routines are Walker callbacks.  Walker.u.pi is a pointer
76389 ** to an integer.  These routines are checking an expression to see
76390 ** if it is a constant.  Set *Walker.u.pi to 0 if the expression is
76391 ** not constant.
76392 **
76393 ** These callback routines are used to implement the following:
76394 **
76395 **     sqlite3ExprIsConstant()
76396 **     sqlite3ExprIsConstantNotJoin()
76397 **     sqlite3ExprIsConstantOrFunction()
76398 **
76399 */
76400 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
76401
76402   /* If pWalker->u.i is 3 then any term of the expression that comes from
76403   ** the ON or USING clauses of a join disqualifies the expression
76404   ** from being considered constant. */
76405   if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
76406     pWalker->u.i = 0;
76407     return WRC_Abort;
76408   }
76409
76410   switch( pExpr->op ){
76411     /* Consider functions to be constant if all their arguments are constant
76412     ** and pWalker->u.i==2 */
76413     case TK_FUNCTION:
76414       if( pWalker->u.i==2 ) return 0;
76415       /* Fall through */
76416     case TK_ID:
76417     case TK_COLUMN:
76418     case TK_AGG_FUNCTION:
76419     case TK_AGG_COLUMN:
76420       testcase( pExpr->op==TK_ID );
76421       testcase( pExpr->op==TK_COLUMN );
76422       testcase( pExpr->op==TK_AGG_FUNCTION );
76423       testcase( pExpr->op==TK_AGG_COLUMN );
76424       pWalker->u.i = 0;
76425       return WRC_Abort;
76426     default:
76427       testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
76428       testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
76429       return WRC_Continue;
76430   }
76431 }
76432 static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
76433   UNUSED_PARAMETER(NotUsed);
76434   pWalker->u.i = 0;
76435   return WRC_Abort;
76436 }
76437 static int exprIsConst(Expr *p, int initFlag){
76438   Walker w;
76439   memset(&w, 0, sizeof(w));
76440   w.u.i = initFlag;
76441   w.xExprCallback = exprNodeIsConstant;
76442   w.xSelectCallback = selectNodeIsConstant;
76443   sqlite3WalkExpr(&w, p);
76444   return w.u.i;
76445 }
76446
76447 /*
76448 ** Walk an expression tree.  Return 1 if the expression is constant
76449 ** and 0 if it involves variables or function calls.
76450 **
76451 ** For the purposes of this function, a double-quoted string (ex: "abc")
76452 ** is considered a variable but a single-quoted string (ex: 'abc') is
76453 ** a constant.
76454 */
76455 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
76456   return exprIsConst(p, 1);
76457 }
76458
76459 /*
76460 ** Walk an expression tree.  Return 1 if the expression is constant
76461 ** that does no originate from the ON or USING clauses of a join.
76462 ** Return 0 if it involves variables or function calls or terms from
76463 ** an ON or USING clause.
76464 */
76465 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
76466   return exprIsConst(p, 3);
76467 }
76468
76469 /*
76470 ** Walk an expression tree.  Return 1 if the expression is constant
76471 ** or a function call with constant arguments.  Return and 0 if there
76472 ** are any variables.
76473 **
76474 ** For the purposes of this function, a double-quoted string (ex: "abc")
76475 ** is considered a variable but a single-quoted string (ex: 'abc') is
76476 ** a constant.
76477 */
76478 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
76479   return exprIsConst(p, 2);
76480 }
76481
76482 /*
76483 ** If the expression p codes a constant integer that is small enough
76484 ** to fit in a 32-bit integer, return 1 and put the value of the integer
76485 ** in *pValue.  If the expression is not an integer or if it is too big
76486 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
76487 */
76488 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
76489   int rc = 0;
76490
76491   /* If an expression is an integer literal that fits in a signed 32-bit
76492   ** integer, then the EP_IntValue flag will have already been set */
76493   assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
76494            || sqlite3GetInt32(p->u.zToken, &rc)==0 );
76495
76496   if( p->flags & EP_IntValue ){
76497     *pValue = p->u.iValue;
76498     return 1;
76499   }
76500   switch( p->op ){
76501     case TK_UPLUS: {
76502       rc = sqlite3ExprIsInteger(p->pLeft, pValue);
76503       break;
76504     }
76505     case TK_UMINUS: {
76506       int v;
76507       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
76508         *pValue = -v;
76509         rc = 1;
76510       }
76511       break;
76512     }
76513     default: break;
76514   }
76515   return rc;
76516 }
76517
76518 /*
76519 ** Return FALSE if there is no chance that the expression can be NULL.
76520 **
76521 ** If the expression might be NULL or if the expression is too complex
76522 ** to tell return TRUE.  
76523 **
76524 ** This routine is used as an optimization, to skip OP_IsNull opcodes
76525 ** when we know that a value cannot be NULL.  Hence, a false positive
76526 ** (returning TRUE when in fact the expression can never be NULL) might
76527 ** be a small performance hit but is otherwise harmless.  On the other
76528 ** hand, a false negative (returning FALSE when the result could be NULL)
76529 ** will likely result in an incorrect answer.  So when in doubt, return
76530 ** TRUE.
76531 */
76532 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
76533   u8 op;
76534   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
76535   op = p->op;
76536   if( op==TK_REGISTER ) op = p->op2;
76537   switch( op ){
76538     case TK_INTEGER:
76539     case TK_STRING:
76540     case TK_FLOAT:
76541     case TK_BLOB:
76542       return 0;
76543     default:
76544       return 1;
76545   }
76546 }
76547
76548 /*
76549 ** Generate an OP_IsNull instruction that tests register iReg and jumps
76550 ** to location iDest if the value in iReg is NULL.  The value in iReg 
76551 ** was computed by pExpr.  If we can look at pExpr at compile-time and
76552 ** determine that it can never generate a NULL, then the OP_IsNull operation
76553 ** can be omitted.
76554 */
76555 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(
76556   Vdbe *v,            /* The VDBE under construction */
76557   const Expr *pExpr,  /* Only generate OP_IsNull if this expr can be NULL */
76558   int iReg,           /* Test the value in this register for NULL */
76559   int iDest           /* Jump here if the value is null */
76560 ){
76561   if( sqlite3ExprCanBeNull(pExpr) ){
76562     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
76563   }
76564 }
76565
76566 /*
76567 ** Return TRUE if the given expression is a constant which would be
76568 ** unchanged by OP_Affinity with the affinity given in the second
76569 ** argument.
76570 **
76571 ** This routine is used to determine if the OP_Affinity operation
76572 ** can be omitted.  When in doubt return FALSE.  A false negative
76573 ** is harmless.  A false positive, however, can result in the wrong
76574 ** answer.
76575 */
76576 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
76577   u8 op;
76578   if( aff==SQLITE_AFF_NONE ) return 1;
76579   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
76580   op = p->op;
76581   if( op==TK_REGISTER ) op = p->op2;
76582   switch( op ){
76583     case TK_INTEGER: {
76584       return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
76585     }
76586     case TK_FLOAT: {
76587       return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
76588     }
76589     case TK_STRING: {
76590       return aff==SQLITE_AFF_TEXT;
76591     }
76592     case TK_BLOB: {
76593       return 1;
76594     }
76595     case TK_COLUMN: {
76596       assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
76597       return p->iColumn<0
76598           && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
76599     }
76600     default: {
76601       return 0;
76602     }
76603   }
76604 }
76605
76606 /*
76607 ** Return TRUE if the given string is a row-id column name.
76608 */
76609 SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
76610   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
76611   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
76612   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
76613   return 0;
76614 }
76615
76616 /*
76617 ** Return true if we are able to the IN operator optimization on a
76618 ** query of the form
76619 **
76620 **       x IN (SELECT ...)
76621 **
76622 ** Where the SELECT... clause is as specified by the parameter to this
76623 ** routine.
76624 **
76625 ** The Select object passed in has already been preprocessed and no
76626 ** errors have been found.
76627 */
76628 #ifndef SQLITE_OMIT_SUBQUERY
76629 static int isCandidateForInOpt(Select *p){
76630   SrcList *pSrc;
76631   ExprList *pEList;
76632   Table *pTab;
76633   if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
76634   if( p->pPrior ) return 0;              /* Not a compound SELECT */
76635   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
76636     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
76637     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
76638     return 0; /* No DISTINCT keyword and no aggregate functions */
76639   }
76640   assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
76641   if( p->pLimit ) return 0;              /* Has no LIMIT clause */
76642   assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
76643   if( p->pWhere ) return 0;              /* Has no WHERE clause */
76644   pSrc = p->pSrc;
76645   assert( pSrc!=0 );
76646   if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
76647   if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
76648   pTab = pSrc->a[0].pTab;
76649   if( NEVER(pTab==0) ) return 0;
76650   assert( pTab->pSelect==0 );            /* FROM clause is not a view */
76651   if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
76652   pEList = p->pEList;
76653   if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
76654   if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
76655   return 1;
76656 }
76657 #endif /* SQLITE_OMIT_SUBQUERY */
76658
76659 /*
76660 ** Code an OP_Once instruction and allocate space for its flag. Return the 
76661 ** address of the new instruction.
76662 */
76663 SQLITE_PRIVATE int sqlite3CodeOnce(Parse *pParse){
76664   Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
76665   return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
76666 }
76667
76668 /*
76669 ** This function is used by the implementation of the IN (...) operator.
76670 ** The pX parameter is the expression on the RHS of the IN operator, which
76671 ** might be either a list of expressions or a subquery.
76672 **
76673 ** The job of this routine is to find or create a b-tree object that can
76674 ** be used either to test for membership in the RHS set or to iterate through
76675 ** all members of the RHS set, skipping duplicates.
76676 **
76677 ** A cursor is opened on the b-tree object that the RHS of the IN operator
76678 ** and pX->iTable is set to the index of that cursor.
76679 **
76680 ** The returned value of this function indicates the b-tree type, as follows:
76681 **
76682 **   IN_INDEX_ROWID      - The cursor was opened on a database table.
76683 **   IN_INDEX_INDEX_ASC  - The cursor was opened on an ascending index.
76684 **   IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
76685 **   IN_INDEX_EPH        - The cursor was opened on a specially created and
76686 **                         populated epheremal table.
76687 **
76688 ** An existing b-tree might be used if the RHS expression pX is a simple
76689 ** subquery such as:
76690 **
76691 **     SELECT <column> FROM <table>
76692 **
76693 ** If the RHS of the IN operator is a list or a more complex subquery, then
76694 ** an ephemeral table might need to be generated from the RHS and then
76695 ** pX->iTable made to point to the ephermeral table instead of an
76696 ** existing table.  
76697 **
76698 ** If the prNotFound parameter is 0, then the b-tree will be used to iterate
76699 ** through the set members, skipping any duplicates. In this case an
76700 ** epheremal table must be used unless the selected <column> is guaranteed
76701 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
76702 ** has a UNIQUE constraint or UNIQUE index.
76703 **
76704 ** If the prNotFound parameter is not 0, then the b-tree will be used 
76705 ** for fast set membership tests. In this case an epheremal table must 
76706 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can 
76707 ** be found with <column> as its left-most column.
76708 **
76709 ** When the b-tree is being used for membership tests, the calling function
76710 ** needs to know whether or not the structure contains an SQL NULL 
76711 ** value in order to correctly evaluate expressions like "X IN (Y, Z)".
76712 ** If there is any chance that the (...) might contain a NULL value at
76713 ** runtime, then a register is allocated and the register number written
76714 ** to *prNotFound. If there is no chance that the (...) contains a
76715 ** NULL value, then *prNotFound is left unchanged.
76716 **
76717 ** If a register is allocated and its location stored in *prNotFound, then
76718 ** its initial value is NULL.  If the (...) does not remain constant
76719 ** for the duration of the query (i.e. the SELECT within the (...)
76720 ** is a correlated subquery) then the value of the allocated register is
76721 ** reset to NULL each time the subquery is rerun. This allows the
76722 ** caller to use vdbe code equivalent to the following:
76723 **
76724 **   if( register==NULL ){
76725 **     has_null = <test if data structure contains null>
76726 **     register = 1
76727 **   }
76728 **
76729 ** in order to avoid running the <test if data structure contains null>
76730 ** test more often than is necessary.
76731 */
76732 #ifndef SQLITE_OMIT_SUBQUERY
76733 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
76734   Select *p;                            /* SELECT to the right of IN operator */
76735   int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
76736   int iTab = pParse->nTab++;            /* Cursor of the RHS table */
76737   int mustBeUnique = (prNotFound==0);   /* True if RHS must be unique */
76738   Vdbe *v = sqlite3GetVdbe(pParse);     /* Virtual machine being coded */
76739
76740   assert( pX->op==TK_IN );
76741
76742   /* Check to see if an existing table or index can be used to
76743   ** satisfy the query.  This is preferable to generating a new 
76744   ** ephemeral table.
76745   */
76746   p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
76747   if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
76748     sqlite3 *db = pParse->db;              /* Database connection */
76749     Table *pTab;                           /* Table <table>. */
76750     Expr *pExpr;                           /* Expression <column> */
76751     int iCol;                              /* Index of column <column> */
76752     int iDb;                               /* Database idx for pTab */
76753
76754     assert( p );                        /* Because of isCandidateForInOpt(p) */
76755     assert( p->pEList!=0 );             /* Because of isCandidateForInOpt(p) */
76756     assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
76757     assert( p->pSrc!=0 );               /* Because of isCandidateForInOpt(p) */
76758     pTab = p->pSrc->a[0].pTab;
76759     pExpr = p->pEList->a[0].pExpr;
76760     iCol = pExpr->iColumn;
76761    
76762     /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
76763     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
76764     sqlite3CodeVerifySchema(pParse, iDb);
76765     sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
76766
76767     /* This function is only called from two places. In both cases the vdbe
76768     ** has already been allocated. So assume sqlite3GetVdbe() is always
76769     ** successful here.
76770     */
76771     assert(v);
76772     if( iCol<0 ){
76773       int iAddr;
76774
76775       iAddr = sqlite3CodeOnce(pParse);
76776
76777       sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
76778       eType = IN_INDEX_ROWID;
76779
76780       sqlite3VdbeJumpHere(v, iAddr);
76781     }else{
76782       Index *pIdx;                         /* Iterator variable */
76783
76784       /* The collation sequence used by the comparison. If an index is to
76785       ** be used in place of a temp-table, it must be ordered according
76786       ** to this collation sequence.  */
76787       CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
76788
76789       /* Check that the affinity that will be used to perform the 
76790       ** comparison is the same as the affinity of the column. If
76791       ** it is not, it is not possible to use any index.
76792       */
76793       int affinity_ok = sqlite3IndexAffinityOk(pX, pTab->aCol[iCol].affinity);
76794
76795       for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
76796         if( (pIdx->aiColumn[0]==iCol)
76797          && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
76798          && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
76799         ){
76800           int iAddr;
76801           char *pKey;
76802   
76803           pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
76804           iAddr = sqlite3CodeOnce(pParse);
76805   
76806           sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
76807                                pKey,P4_KEYINFO_HANDOFF);
76808           VdbeComment((v, "%s", pIdx->zName));
76809           assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
76810           eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
76811
76812           sqlite3VdbeJumpHere(v, iAddr);
76813           if( prNotFound && !pTab->aCol[iCol].notNull ){
76814             *prNotFound = ++pParse->nMem;
76815             sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
76816           }
76817         }
76818       }
76819     }
76820   }
76821
76822   if( eType==0 ){
76823     /* Could not found an existing table or index to use as the RHS b-tree.
76824     ** We will have to generate an ephemeral table to do the job.
76825     */
76826     double savedNQueryLoop = pParse->nQueryLoop;
76827     int rMayHaveNull = 0;
76828     eType = IN_INDEX_EPH;
76829     if( prNotFound ){
76830       *prNotFound = rMayHaveNull = ++pParse->nMem;
76831       sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
76832     }else{
76833       testcase( pParse->nQueryLoop>(double)1 );
76834       pParse->nQueryLoop = (double)1;
76835       if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
76836         eType = IN_INDEX_ROWID;
76837       }
76838     }
76839     sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
76840     pParse->nQueryLoop = savedNQueryLoop;
76841   }else{
76842     pX->iTable = iTab;
76843   }
76844   return eType;
76845 }
76846 #endif
76847
76848 /*
76849 ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
76850 ** or IN operators.  Examples:
76851 **
76852 **     (SELECT a FROM b)          -- subquery
76853 **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
76854 **     x IN (4,5,11)              -- IN operator with list on right-hand side
76855 **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
76856 **
76857 ** The pExpr parameter describes the expression that contains the IN
76858 ** operator or subquery.
76859 **
76860 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
76861 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
76862 ** to some integer key column of a table B-Tree. In this case, use an
76863 ** intkey B-Tree to store the set of IN(...) values instead of the usual
76864 ** (slower) variable length keys B-Tree.
76865 **
76866 ** If rMayHaveNull is non-zero, that means that the operation is an IN
76867 ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
76868 ** Furthermore, the IN is in a WHERE clause and that we really want
76869 ** to iterate over the RHS of the IN operator in order to quickly locate
76870 ** all corresponding LHS elements.  All this routine does is initialize
76871 ** the register given by rMayHaveNull to NULL.  Calling routines will take
76872 ** care of changing this register value to non-NULL if the RHS is NULL-free.
76873 **
76874 ** If rMayHaveNull is zero, that means that the subquery is being used
76875 ** for membership testing only.  There is no need to initialize any
76876 ** registers to indicate the presense or absence of NULLs on the RHS.
76877 **
76878 ** For a SELECT or EXISTS operator, return the register that holds the
76879 ** result.  For IN operators or if an error occurs, the return value is 0.
76880 */
76881 #ifndef SQLITE_OMIT_SUBQUERY
76882 SQLITE_PRIVATE int sqlite3CodeSubselect(
76883   Parse *pParse,          /* Parsing context */
76884   Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
76885   int rMayHaveNull,       /* Register that records whether NULLs exist in RHS */
76886   int isRowid             /* If true, LHS of IN operator is a rowid */
76887 ){
76888   int testAddr = -1;                      /* One-time test address */
76889   int rReg = 0;                           /* Register storing resulting */
76890   Vdbe *v = sqlite3GetVdbe(pParse);
76891   if( NEVER(v==0) ) return 0;
76892   sqlite3ExprCachePush(pParse);
76893
76894   /* This code must be run in its entirety every time it is encountered
76895   ** if any of the following is true:
76896   **
76897   **    *  The right-hand side is a correlated subquery
76898   **    *  The right-hand side is an expression list containing variables
76899   **    *  We are inside a trigger
76900   **
76901   ** If all of the above are false, then we can run this code just once
76902   ** save the results, and reuse the same result on subsequent invocations.
76903   */
76904   if( !ExprHasAnyProperty(pExpr, EP_VarSelect) ){
76905     testAddr = sqlite3CodeOnce(pParse);
76906   }
76907
76908 #ifndef SQLITE_OMIT_EXPLAIN
76909   if( pParse->explain==2 ){
76910     char *zMsg = sqlite3MPrintf(
76911         pParse->db, "EXECUTE %s%s SUBQUERY %d", testAddr>=0?"":"CORRELATED ",
76912         pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
76913     );
76914     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
76915   }
76916 #endif
76917
76918   switch( pExpr->op ){
76919     case TK_IN: {
76920       char affinity;              /* Affinity of the LHS of the IN */
76921       KeyInfo keyInfo;            /* Keyinfo for the generated table */
76922       static u8 sortOrder = 0;    /* Fake aSortOrder for keyInfo */
76923       int addr;                   /* Address of OP_OpenEphemeral instruction */
76924       Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
76925
76926       if( rMayHaveNull ){
76927         sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
76928       }
76929
76930       affinity = sqlite3ExprAffinity(pLeft);
76931
76932       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
76933       ** expression it is handled the same way.  An ephemeral table is 
76934       ** filled with single-field index keys representing the results
76935       ** from the SELECT or the <exprlist>.
76936       **
76937       ** If the 'x' expression is a column value, or the SELECT...
76938       ** statement returns a column value, then the affinity of that
76939       ** column is used to build the index keys. If both 'x' and the
76940       ** SELECT... statement are columns, then numeric affinity is used
76941       ** if either column has NUMERIC or INTEGER affinity. If neither
76942       ** 'x' nor the SELECT... statement are columns, then numeric affinity
76943       ** is used.
76944       */
76945       pExpr->iTable = pParse->nTab++;
76946       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
76947       if( rMayHaveNull==0 ) sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
76948       memset(&keyInfo, 0, sizeof(keyInfo));
76949       keyInfo.nField = 1;
76950       keyInfo.aSortOrder = &sortOrder;
76951
76952       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
76953         /* Case 1:     expr IN (SELECT ...)
76954         **
76955         ** Generate code to write the results of the select into the temporary
76956         ** table allocated and opened above.
76957         */
76958         SelectDest dest;
76959         ExprList *pEList;
76960
76961         assert( !isRowid );
76962         sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
76963         dest.affSdst = (u8)affinity;
76964         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
76965         pExpr->x.pSelect->iLimit = 0;
76966         if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
76967           return 0;
76968         }
76969         pEList = pExpr->x.pSelect->pEList;
76970         if( ALWAYS(pEList!=0 && pEList->nExpr>0) ){ 
76971           keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
76972               pEList->a[0].pExpr);
76973         }
76974       }else if( ALWAYS(pExpr->x.pList!=0) ){
76975         /* Case 2:     expr IN (exprlist)
76976         **
76977         ** For each expression, build an index key from the evaluation and
76978         ** store it in the temporary table. If <expr> is a column, then use
76979         ** that columns affinity when building index keys. If <expr> is not
76980         ** a column, use numeric affinity.
76981         */
76982         int i;
76983         ExprList *pList = pExpr->x.pList;
76984         struct ExprList_item *pItem;
76985         int r1, r2, r3;
76986
76987         if( !affinity ){
76988           affinity = SQLITE_AFF_NONE;
76989         }
76990         keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
76991         keyInfo.aSortOrder = &sortOrder;
76992
76993         /* Loop through each expression in <exprlist>. */
76994         r1 = sqlite3GetTempReg(pParse);
76995         r2 = sqlite3GetTempReg(pParse);
76996         sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
76997         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
76998           Expr *pE2 = pItem->pExpr;
76999           int iValToIns;
77000
77001           /* If the expression is not constant then we will need to
77002           ** disable the test that was generated above that makes sure
77003           ** this code only executes once.  Because for a non-constant
77004           ** expression we need to rerun this code each time.
77005           */
77006           if( testAddr>=0 && !sqlite3ExprIsConstant(pE2) ){
77007             sqlite3VdbeChangeToNoop(v, testAddr);
77008             testAddr = -1;
77009           }
77010
77011           /* Evaluate the expression and insert it into the temp table */
77012           if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
77013             sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
77014           }else{
77015             r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
77016             if( isRowid ){
77017               sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
77018                                 sqlite3VdbeCurrentAddr(v)+2);
77019               sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
77020             }else{
77021               sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
77022               sqlite3ExprCacheAffinityChange(pParse, r3, 1);
77023               sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
77024             }
77025           }
77026         }
77027         sqlite3ReleaseTempReg(pParse, r1);
77028         sqlite3ReleaseTempReg(pParse, r2);
77029       }
77030       if( !isRowid ){
77031         sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
77032       }
77033       break;
77034     }
77035
77036     case TK_EXISTS:
77037     case TK_SELECT:
77038     default: {
77039       /* If this has to be a scalar SELECT.  Generate code to put the
77040       ** value of this select in a memory cell and record the number
77041       ** of the memory cell in iColumn.  If this is an EXISTS, write
77042       ** an integer 0 (not exists) or 1 (exists) into a memory cell
77043       ** and record that memory cell in iColumn.
77044       */
77045       Select *pSel;                         /* SELECT statement to encode */
77046       SelectDest dest;                      /* How to deal with SELECt result */
77047
77048       testcase( pExpr->op==TK_EXISTS );
77049       testcase( pExpr->op==TK_SELECT );
77050       assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
77051
77052       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
77053       pSel = pExpr->x.pSelect;
77054       sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
77055       if( pExpr->op==TK_SELECT ){
77056         dest.eDest = SRT_Mem;
77057         sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iSDParm);
77058         VdbeComment((v, "Init subquery result"));
77059       }else{
77060         dest.eDest = SRT_Exists;
77061         sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
77062         VdbeComment((v, "Init EXISTS result"));
77063       }
77064       sqlite3ExprDelete(pParse->db, pSel->pLimit);
77065       pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
77066                                   &sqlite3IntTokens[1]);
77067       pSel->iLimit = 0;
77068       if( sqlite3Select(pParse, pSel, &dest) ){
77069         return 0;
77070       }
77071       rReg = dest.iSDParm;
77072       ExprSetIrreducible(pExpr);
77073       break;
77074     }
77075   }
77076
77077   if( testAddr>=0 ){
77078     sqlite3VdbeJumpHere(v, testAddr);
77079   }
77080   sqlite3ExprCachePop(pParse, 1);
77081
77082   return rReg;
77083 }
77084 #endif /* SQLITE_OMIT_SUBQUERY */
77085
77086 #ifndef SQLITE_OMIT_SUBQUERY
77087 /*
77088 ** Generate code for an IN expression.
77089 **
77090 **      x IN (SELECT ...)
77091 **      x IN (value, value, ...)
77092 **
77093 ** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)
77094 ** is an array of zero or more values.  The expression is true if the LHS is
77095 ** contained within the RHS.  The value of the expression is unknown (NULL)
77096 ** if the LHS is NULL or if the LHS is not contained within the RHS and the
77097 ** RHS contains one or more NULL values.
77098 **
77099 ** This routine generates code will jump to destIfFalse if the LHS is not 
77100 ** contained within the RHS.  If due to NULLs we cannot determine if the LHS
77101 ** is contained in the RHS then jump to destIfNull.  If the LHS is contained
77102 ** within the RHS then fall through.
77103 */
77104 static void sqlite3ExprCodeIN(
77105   Parse *pParse,        /* Parsing and code generating context */
77106   Expr *pExpr,          /* The IN expression */
77107   int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
77108   int destIfNull        /* Jump here if the results are unknown due to NULLs */
77109 ){
77110   int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
77111   char affinity;        /* Comparison affinity to use */
77112   int eType;            /* Type of the RHS */
77113   int r1;               /* Temporary use register */
77114   Vdbe *v;              /* Statement under construction */
77115
77116   /* Compute the RHS.   After this step, the table with cursor
77117   ** pExpr->iTable will contains the values that make up the RHS.
77118   */
77119   v = pParse->pVdbe;
77120   assert( v!=0 );       /* OOM detected prior to this routine */
77121   VdbeNoopComment((v, "begin IN expr"));
77122   eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);
77123
77124   /* Figure out the affinity to use to create a key from the results
77125   ** of the expression. affinityStr stores a static string suitable for
77126   ** P4 of OP_MakeRecord.
77127   */
77128   affinity = comparisonAffinity(pExpr);
77129
77130   /* Code the LHS, the <expr> from "<expr> IN (...)".
77131   */
77132   sqlite3ExprCachePush(pParse);
77133   r1 = sqlite3GetTempReg(pParse);
77134   sqlite3ExprCode(pParse, pExpr->pLeft, r1);
77135
77136   /* If the LHS is NULL, then the result is either false or NULL depending
77137   ** on whether the RHS is empty or not, respectively.
77138   */
77139   if( destIfNull==destIfFalse ){
77140     /* Shortcut for the common case where the false and NULL outcomes are
77141     ** the same. */
77142     sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
77143   }else{
77144     int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1);
77145     sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
77146     sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
77147     sqlite3VdbeJumpHere(v, addr1);
77148   }
77149
77150   if( eType==IN_INDEX_ROWID ){
77151     /* In this case, the RHS is the ROWID of table b-tree
77152     */
77153     sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
77154     sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
77155   }else{
77156     /* In this case, the RHS is an index b-tree.
77157     */
77158     sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
77159
77160     /* If the set membership test fails, then the result of the 
77161     ** "x IN (...)" expression must be either 0 or NULL. If the set
77162     ** contains no NULL values, then the result is 0. If the set 
77163     ** contains one or more NULL values, then the result of the
77164     ** expression is also NULL.
77165     */
77166     if( rRhsHasNull==0 || destIfFalse==destIfNull ){
77167       /* This branch runs if it is known at compile time that the RHS
77168       ** cannot contain NULL values. This happens as the result
77169       ** of a "NOT NULL" constraint in the database schema.
77170       **
77171       ** Also run this branch if NULL is equivalent to FALSE
77172       ** for this particular IN operator.
77173       */
77174       sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
77175
77176     }else{
77177       /* In this branch, the RHS of the IN might contain a NULL and
77178       ** the presence of a NULL on the RHS makes a difference in the
77179       ** outcome.
77180       */
77181       int j1, j2, j3;
77182
77183       /* First check to see if the LHS is contained in the RHS.  If so,
77184       ** then the presence of NULLs in the RHS does not matter, so jump
77185       ** over all of the code that follows.
77186       */
77187       j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
77188
77189       /* Here we begin generating code that runs if the LHS is not
77190       ** contained within the RHS.  Generate additional code that
77191       ** tests the RHS for NULLs.  If the RHS contains a NULL then
77192       ** jump to destIfNull.  If there are no NULLs in the RHS then
77193       ** jump to destIfFalse.
77194       */
77195       j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
77196       j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
77197       sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
77198       sqlite3VdbeJumpHere(v, j3);
77199       sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
77200       sqlite3VdbeJumpHere(v, j2);
77201
77202       /* Jump to the appropriate target depending on whether or not
77203       ** the RHS contains a NULL
77204       */
77205       sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
77206       sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
77207
77208       /* The OP_Found at the top of this branch jumps here when true, 
77209       ** causing the overall IN expression evaluation to fall through.
77210       */
77211       sqlite3VdbeJumpHere(v, j1);
77212     }
77213   }
77214   sqlite3ReleaseTempReg(pParse, r1);
77215   sqlite3ExprCachePop(pParse, 1);
77216   VdbeComment((v, "end IN expr"));
77217 }
77218 #endif /* SQLITE_OMIT_SUBQUERY */
77219
77220 /*
77221 ** Duplicate an 8-byte value
77222 */
77223 static char *dup8bytes(Vdbe *v, const char *in){
77224   char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
77225   if( out ){
77226     memcpy(out, in, 8);
77227   }
77228   return out;
77229 }
77230
77231 #ifndef SQLITE_OMIT_FLOATING_POINT
77232 /*
77233 ** Generate an instruction that will put the floating point
77234 ** value described by z[0..n-1] into register iMem.
77235 **
77236 ** The z[] string will probably not be zero-terminated.  But the 
77237 ** z[n] character is guaranteed to be something that does not look
77238 ** like the continuation of the number.
77239 */
77240 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
77241   if( ALWAYS(z!=0) ){
77242     double value;
77243     char *zV;
77244     sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
77245     assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
77246     if( negateFlag ) value = -value;
77247     zV = dup8bytes(v, (char*)&value);
77248     sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
77249   }
77250 }
77251 #endif
77252
77253
77254 /*
77255 ** Generate an instruction that will put the integer describe by
77256 ** text z[0..n-1] into register iMem.
77257 **
77258 ** Expr.u.zToken is always UTF8 and zero-terminated.
77259 */
77260 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
77261   Vdbe *v = pParse->pVdbe;
77262   if( pExpr->flags & EP_IntValue ){
77263     int i = pExpr->u.iValue;
77264     assert( i>=0 );
77265     if( negFlag ) i = -i;
77266     sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
77267   }else{
77268     int c;
77269     i64 value;
77270     const char *z = pExpr->u.zToken;
77271     assert( z!=0 );
77272     c = sqlite3Atoi64(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
77273     if( c==0 || (c==2 && negFlag) ){
77274       char *zV;
77275       if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
77276       zV = dup8bytes(v, (char*)&value);
77277       sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
77278     }else{
77279 #ifdef SQLITE_OMIT_FLOATING_POINT
77280       sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
77281 #else
77282       codeReal(v, z, negFlag, iMem);
77283 #endif
77284     }
77285   }
77286 }
77287
77288 /*
77289 ** Clear a cache entry.
77290 */
77291 static void cacheEntryClear(Parse *pParse, struct yColCache *p){
77292   if( p->tempReg ){
77293     if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
77294       pParse->aTempReg[pParse->nTempReg++] = p->iReg;
77295     }
77296     p->tempReg = 0;
77297   }
77298 }
77299
77300
77301 /*
77302 ** Record in the column cache that a particular column from a
77303 ** particular table is stored in a particular register.
77304 */
77305 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
77306   int i;
77307   int minLru;
77308   int idxLru;
77309   struct yColCache *p;
77310
77311   assert( iReg>0 );  /* Register numbers are always positive */
77312   assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
77313
77314   /* The SQLITE_ColumnCache flag disables the column cache.  This is used
77315   ** for testing only - to verify that SQLite always gets the same answer
77316   ** with and without the column cache.
77317   */
77318   if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
77319
77320   /* First replace any existing entry.
77321   **
77322   ** Actually, the way the column cache is currently used, we are guaranteed
77323   ** that the object will never already be in cache.  Verify this guarantee.
77324   */
77325 #ifndef NDEBUG
77326   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
77327     assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
77328   }
77329 #endif
77330
77331   /* Find an empty slot and replace it */
77332   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
77333     if( p->iReg==0 ){
77334       p->iLevel = pParse->iCacheLevel;
77335       p->iTable = iTab;
77336       p->iColumn = iCol;
77337       p->iReg = iReg;
77338       p->tempReg = 0;
77339       p->lru = pParse->iCacheCnt++;
77340       return;
77341     }
77342   }
77343
77344   /* Replace the last recently used */
77345   minLru = 0x7fffffff;
77346   idxLru = -1;
77347   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
77348     if( p->lru<minLru ){
77349       idxLru = i;
77350       minLru = p->lru;
77351     }
77352   }
77353   if( ALWAYS(idxLru>=0) ){
77354     p = &pParse->aColCache[idxLru];
77355     p->iLevel = pParse->iCacheLevel;
77356     p->iTable = iTab;
77357     p->iColumn = iCol;
77358     p->iReg = iReg;
77359     p->tempReg = 0;
77360     p->lru = pParse->iCacheCnt++;
77361     return;
77362   }
77363 }
77364
77365 /*
77366 ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
77367 ** Purge the range of registers from the column cache.
77368 */
77369 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
77370   int i;
77371   int iLast = iReg + nReg - 1;
77372   struct yColCache *p;
77373   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
77374     int r = p->iReg;
77375     if( r>=iReg && r<=iLast ){
77376       cacheEntryClear(pParse, p);
77377       p->iReg = 0;
77378     }
77379   }
77380 }
77381
77382 /*
77383 ** Remember the current column cache context.  Any new entries added
77384 ** added to the column cache after this call are removed when the
77385 ** corresponding pop occurs.
77386 */
77387 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
77388   pParse->iCacheLevel++;
77389 }
77390
77391 /*
77392 ** Remove from the column cache any entries that were added since the
77393 ** the previous N Push operations.  In other words, restore the cache
77394 ** to the state it was in N Pushes ago.
77395 */
77396 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse, int N){
77397   int i;
77398   struct yColCache *p;
77399   assert( N>0 );
77400   assert( pParse->iCacheLevel>=N );
77401   pParse->iCacheLevel -= N;
77402   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
77403     if( p->iReg && p->iLevel>pParse->iCacheLevel ){
77404       cacheEntryClear(pParse, p);
77405       p->iReg = 0;
77406     }
77407   }
77408 }
77409
77410 /*
77411 ** When a cached column is reused, make sure that its register is
77412 ** no longer available as a temp register.  ticket #3879:  that same
77413 ** register might be in the cache in multiple places, so be sure to
77414 ** get them all.
77415 */
77416 static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
77417   int i;
77418   struct yColCache *p;
77419   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
77420     if( p->iReg==iReg ){
77421       p->tempReg = 0;
77422     }
77423   }
77424 }
77425
77426 /*
77427 ** Generate code to extract the value of the iCol-th column of a table.
77428 */
77429 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
77430   Vdbe *v,        /* The VDBE under construction */
77431   Table *pTab,    /* The table containing the value */
77432   int iTabCur,    /* The cursor for this table */
77433   int iCol,       /* Index of the column to extract */
77434   int regOut      /* Extract the valud into this register */
77435 ){
77436   if( iCol<0 || iCol==pTab->iPKey ){
77437     sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
77438   }else{
77439     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
77440     sqlite3VdbeAddOp3(v, op, iTabCur, iCol, regOut);
77441   }
77442   if( iCol>=0 ){
77443     sqlite3ColumnDefault(v, pTab, iCol, regOut);
77444   }
77445 }
77446
77447 /*
77448 ** Generate code that will extract the iColumn-th column from
77449 ** table pTab and store the column value in a register.  An effort
77450 ** is made to store the column value in register iReg, but this is
77451 ** not guaranteed.  The location of the column value is returned.
77452 **
77453 ** There must be an open cursor to pTab in iTable when this routine
77454 ** is called.  If iColumn<0 then code is generated that extracts the rowid.
77455 */
77456 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
77457   Parse *pParse,   /* Parsing and code generating context */
77458   Table *pTab,     /* Description of the table we are reading from */
77459   int iColumn,     /* Index of the table column */
77460   int iTable,      /* The cursor pointing to the table */
77461   int iReg,        /* Store results here */
77462   u8 p5            /* P5 value for OP_Column */
77463 ){
77464   Vdbe *v = pParse->pVdbe;
77465   int i;
77466   struct yColCache *p;
77467
77468   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
77469     if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
77470       p->lru = pParse->iCacheCnt++;
77471       sqlite3ExprCachePinRegister(pParse, p->iReg);
77472       return p->iReg;
77473     }
77474   }  
77475   assert( v!=0 );
77476   sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
77477   if( p5 ){
77478     sqlite3VdbeChangeP5(v, p5);
77479   }else{   
77480     sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
77481   }
77482   return iReg;
77483 }
77484
77485 /*
77486 ** Clear all column cache entries.
77487 */
77488 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
77489   int i;
77490   struct yColCache *p;
77491
77492   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
77493     if( p->iReg ){
77494       cacheEntryClear(pParse, p);
77495       p->iReg = 0;
77496     }
77497   }
77498 }
77499
77500 /*
77501 ** Record the fact that an affinity change has occurred on iCount
77502 ** registers starting with iStart.
77503 */
77504 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
77505   sqlite3ExprCacheRemove(pParse, iStart, iCount);
77506 }
77507
77508 /*
77509 ** Generate code to move content from registers iFrom...iFrom+nReg-1
77510 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
77511 */
77512 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
77513   int i;
77514   struct yColCache *p;
77515   assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
77516   sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg-1);
77517   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
77518     int x = p->iReg;
77519     if( x>=iFrom && x<iFrom+nReg ){
77520       p->iReg += iTo-iFrom;
77521     }
77522   }
77523 }
77524
77525 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
77526 /*
77527 ** Return true if any register in the range iFrom..iTo (inclusive)
77528 ** is used as part of the column cache.
77529 **
77530 ** This routine is used within assert() and testcase() macros only
77531 ** and does not appear in a normal build.
77532 */
77533 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
77534   int i;
77535   struct yColCache *p;
77536   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
77537     int r = p->iReg;
77538     if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
77539   }
77540   return 0;
77541 }
77542 #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
77543
77544 /*
77545 ** Generate code into the current Vdbe to evaluate the given
77546 ** expression.  Attempt to store the results in register "target".
77547 ** Return the register where results are stored.
77548 **
77549 ** With this routine, there is no guarantee that results will
77550 ** be stored in target.  The result might be stored in some other
77551 ** register if it is convenient to do so.  The calling function
77552 ** must check the return code and move the results to the desired
77553 ** register.
77554 */
77555 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
77556   Vdbe *v = pParse->pVdbe;  /* The VM under construction */
77557   int op;                   /* The opcode being coded */
77558   int inReg = target;       /* Results stored in register inReg */
77559   int regFree1 = 0;         /* If non-zero free this temporary register */
77560   int regFree2 = 0;         /* If non-zero free this temporary register */
77561   int r1, r2, r3, r4;       /* Various register numbers */
77562   sqlite3 *db = pParse->db; /* The database connection */
77563
77564   assert( target>0 && target<=pParse->nMem );
77565   if( v==0 ){
77566     assert( pParse->db->mallocFailed );
77567     return 0;
77568   }
77569
77570   if( pExpr==0 ){
77571     op = TK_NULL;
77572   }else{
77573     op = pExpr->op;
77574   }
77575   switch( op ){
77576     case TK_AGG_COLUMN: {
77577       AggInfo *pAggInfo = pExpr->pAggInfo;
77578       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
77579       if( !pAggInfo->directMode ){
77580         assert( pCol->iMem>0 );
77581         inReg = pCol->iMem;
77582         break;
77583       }else if( pAggInfo->useSortingIdx ){
77584         sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
77585                               pCol->iSorterColumn, target);
77586         break;
77587       }
77588       /* Otherwise, fall thru into the TK_COLUMN case */
77589     }
77590     case TK_COLUMN: {
77591       if( pExpr->iTable<0 ){
77592         /* This only happens when coding check constraints */
77593         assert( pParse->ckBase>0 );
77594         inReg = pExpr->iColumn + pParse->ckBase;
77595       }else{
77596         inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
77597                                  pExpr->iColumn, pExpr->iTable, target,
77598                                  pExpr->op2);
77599       }
77600       break;
77601     }
77602     case TK_INTEGER: {
77603       codeInteger(pParse, pExpr, 0, target);
77604       break;
77605     }
77606 #ifndef SQLITE_OMIT_FLOATING_POINT
77607     case TK_FLOAT: {
77608       assert( !ExprHasProperty(pExpr, EP_IntValue) );
77609       codeReal(v, pExpr->u.zToken, 0, target);
77610       break;
77611     }
77612 #endif
77613     case TK_STRING: {
77614       assert( !ExprHasProperty(pExpr, EP_IntValue) );
77615       sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
77616       break;
77617     }
77618     case TK_NULL: {
77619       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
77620       break;
77621     }
77622 #ifndef SQLITE_OMIT_BLOB_LITERAL
77623     case TK_BLOB: {
77624       int n;
77625       const char *z;
77626       char *zBlob;
77627       assert( !ExprHasProperty(pExpr, EP_IntValue) );
77628       assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
77629       assert( pExpr->u.zToken[1]=='\'' );
77630       z = &pExpr->u.zToken[2];
77631       n = sqlite3Strlen30(z) - 1;
77632       assert( z[n]=='\'' );
77633       zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
77634       sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
77635       break;
77636     }
77637 #endif
77638     case TK_VARIABLE: {
77639       assert( !ExprHasProperty(pExpr, EP_IntValue) );
77640       assert( pExpr->u.zToken!=0 );
77641       assert( pExpr->u.zToken[0]!=0 );
77642       sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
77643       if( pExpr->u.zToken[1]!=0 ){
77644         assert( pExpr->u.zToken[0]=='?' 
77645              || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
77646         sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
77647       }
77648       break;
77649     }
77650     case TK_REGISTER: {
77651       inReg = pExpr->iTable;
77652       break;
77653     }
77654     case TK_AS: {
77655       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
77656       break;
77657     }
77658 #ifndef SQLITE_OMIT_CAST
77659     case TK_CAST: {
77660       /* Expressions of the form:   CAST(pLeft AS token) */
77661       int aff, to_op;
77662       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
77663       assert( !ExprHasProperty(pExpr, EP_IntValue) );
77664       aff = sqlite3AffinityType(pExpr->u.zToken);
77665       to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
77666       assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
77667       assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
77668       assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
77669       assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
77670       assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
77671       testcase( to_op==OP_ToText );
77672       testcase( to_op==OP_ToBlob );
77673       testcase( to_op==OP_ToNumeric );
77674       testcase( to_op==OP_ToInt );
77675       testcase( to_op==OP_ToReal );
77676       if( inReg!=target ){
77677         sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
77678         inReg = target;
77679       }
77680       sqlite3VdbeAddOp1(v, to_op, inReg);
77681       testcase( usedAsColumnCache(pParse, inReg, inReg) );
77682       sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
77683       break;
77684     }
77685 #endif /* SQLITE_OMIT_CAST */
77686     case TK_LT:
77687     case TK_LE:
77688     case TK_GT:
77689     case TK_GE:
77690     case TK_NE:
77691     case TK_EQ: {
77692       assert( TK_LT==OP_Lt );
77693       assert( TK_LE==OP_Le );
77694       assert( TK_GT==OP_Gt );
77695       assert( TK_GE==OP_Ge );
77696       assert( TK_EQ==OP_Eq );
77697       assert( TK_NE==OP_Ne );
77698       testcase( op==TK_LT );
77699       testcase( op==TK_LE );
77700       testcase( op==TK_GT );
77701       testcase( op==TK_GE );
77702       testcase( op==TK_EQ );
77703       testcase( op==TK_NE );
77704       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77705       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
77706       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
77707                   r1, r2, inReg, SQLITE_STOREP2);
77708       testcase( regFree1==0 );
77709       testcase( regFree2==0 );
77710       break;
77711     }
77712     case TK_IS:
77713     case TK_ISNOT: {
77714       testcase( op==TK_IS );
77715       testcase( op==TK_ISNOT );
77716       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77717       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
77718       op = (op==TK_IS) ? TK_EQ : TK_NE;
77719       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
77720                   r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
77721       testcase( regFree1==0 );
77722       testcase( regFree2==0 );
77723       break;
77724     }
77725     case TK_AND:
77726     case TK_OR:
77727     case TK_PLUS:
77728     case TK_STAR:
77729     case TK_MINUS:
77730     case TK_REM:
77731     case TK_BITAND:
77732     case TK_BITOR:
77733     case TK_SLASH:
77734     case TK_LSHIFT:
77735     case TK_RSHIFT: 
77736     case TK_CONCAT: {
77737       assert( TK_AND==OP_And );
77738       assert( TK_OR==OP_Or );
77739       assert( TK_PLUS==OP_Add );
77740       assert( TK_MINUS==OP_Subtract );
77741       assert( TK_REM==OP_Remainder );
77742       assert( TK_BITAND==OP_BitAnd );
77743       assert( TK_BITOR==OP_BitOr );
77744       assert( TK_SLASH==OP_Divide );
77745       assert( TK_LSHIFT==OP_ShiftLeft );
77746       assert( TK_RSHIFT==OP_ShiftRight );
77747       assert( TK_CONCAT==OP_Concat );
77748       testcase( op==TK_AND );
77749       testcase( op==TK_OR );
77750       testcase( op==TK_PLUS );
77751       testcase( op==TK_MINUS );
77752       testcase( op==TK_REM );
77753       testcase( op==TK_BITAND );
77754       testcase( op==TK_BITOR );
77755       testcase( op==TK_SLASH );
77756       testcase( op==TK_LSHIFT );
77757       testcase( op==TK_RSHIFT );
77758       testcase( op==TK_CONCAT );
77759       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77760       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
77761       sqlite3VdbeAddOp3(v, op, r2, r1, target);
77762       testcase( regFree1==0 );
77763       testcase( regFree2==0 );
77764       break;
77765     }
77766     case TK_UMINUS: {
77767       Expr *pLeft = pExpr->pLeft;
77768       assert( pLeft );
77769       if( pLeft->op==TK_INTEGER ){
77770         codeInteger(pParse, pLeft, 1, target);
77771 #ifndef SQLITE_OMIT_FLOATING_POINT
77772       }else if( pLeft->op==TK_FLOAT ){
77773         assert( !ExprHasProperty(pExpr, EP_IntValue) );
77774         codeReal(v, pLeft->u.zToken, 1, target);
77775 #endif
77776       }else{
77777         regFree1 = r1 = sqlite3GetTempReg(pParse);
77778         sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
77779         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
77780         sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
77781         testcase( regFree2==0 );
77782       }
77783       inReg = target;
77784       break;
77785     }
77786     case TK_BITNOT:
77787     case TK_NOT: {
77788       assert( TK_BITNOT==OP_BitNot );
77789       assert( TK_NOT==OP_Not );
77790       testcase( op==TK_BITNOT );
77791       testcase( op==TK_NOT );
77792       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77793       testcase( regFree1==0 );
77794       inReg = target;
77795       sqlite3VdbeAddOp2(v, op, r1, inReg);
77796       break;
77797     }
77798     case TK_ISNULL:
77799     case TK_NOTNULL: {
77800       int addr;
77801       assert( TK_ISNULL==OP_IsNull );
77802       assert( TK_NOTNULL==OP_NotNull );
77803       testcase( op==TK_ISNULL );
77804       testcase( op==TK_NOTNULL );
77805       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
77806       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
77807       testcase( regFree1==0 );
77808       addr = sqlite3VdbeAddOp1(v, op, r1);
77809       sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
77810       sqlite3VdbeJumpHere(v, addr);
77811       break;
77812     }
77813     case TK_AGG_FUNCTION: {
77814       AggInfo *pInfo = pExpr->pAggInfo;
77815       if( pInfo==0 ){
77816         assert( !ExprHasProperty(pExpr, EP_IntValue) );
77817         sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
77818       }else{
77819         inReg = pInfo->aFunc[pExpr->iAgg].iMem;
77820       }
77821       break;
77822     }
77823     case TK_CONST_FUNC:
77824     case TK_FUNCTION: {
77825       ExprList *pFarg;       /* List of function arguments */
77826       int nFarg;             /* Number of function arguments */
77827       FuncDef *pDef;         /* The function definition object */
77828       int nId;               /* Length of the function name in bytes */
77829       const char *zId;       /* The function name */
77830       int constMask = 0;     /* Mask of function arguments that are constant */
77831       int i;                 /* Loop counter */
77832       u8 enc = ENC(db);      /* The text encoding used by this database */
77833       CollSeq *pColl = 0;    /* A collating sequence */
77834
77835       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
77836       testcase( op==TK_CONST_FUNC );
77837       testcase( op==TK_FUNCTION );
77838       if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
77839         pFarg = 0;
77840       }else{
77841         pFarg = pExpr->x.pList;
77842       }
77843       nFarg = pFarg ? pFarg->nExpr : 0;
77844       assert( !ExprHasProperty(pExpr, EP_IntValue) );
77845       zId = pExpr->u.zToken;
77846       nId = sqlite3Strlen30(zId);
77847       pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
77848       if( pDef==0 ){
77849         sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
77850         break;
77851       }
77852
77853       /* Attempt a direct implementation of the built-in COALESCE() and
77854       ** IFNULL() functions.  This avoids unnecessary evalation of
77855       ** arguments past the first non-NULL argument.
77856       */
77857       if( pDef->flags & SQLITE_FUNC_COALESCE ){
77858         int endCoalesce = sqlite3VdbeMakeLabel(v);
77859         assert( nFarg>=2 );
77860         sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
77861         for(i=1; i<nFarg; i++){
77862           sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
77863           sqlite3ExprCacheRemove(pParse, target, 1);
77864           sqlite3ExprCachePush(pParse);
77865           sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
77866           sqlite3ExprCachePop(pParse, 1);
77867         }
77868         sqlite3VdbeResolveLabel(v, endCoalesce);
77869         break;
77870       }
77871
77872
77873       if( pFarg ){
77874         r1 = sqlite3GetTempRange(pParse, nFarg);
77875
77876         /* For length() and typeof() functions with a column argument,
77877         ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
77878         ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
77879         ** loading.
77880         */
77881         if( (pDef->flags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
77882           u8 exprOp;
77883           assert( nFarg==1 );
77884           assert( pFarg->a[0].pExpr!=0 );
77885           exprOp = pFarg->a[0].pExpr->op;
77886           if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
77887             assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
77888             assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
77889             testcase( pDef->flags==SQLITE_FUNC_LENGTH );
77890             pFarg->a[0].pExpr->op2 = pDef->flags;
77891           }
77892         }
77893
77894         sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
77895         sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);
77896         sqlite3ExprCachePop(pParse, 1);   /* Ticket 2ea2425d34be */
77897       }else{
77898         r1 = 0;
77899       }
77900 #ifndef SQLITE_OMIT_VIRTUALTABLE
77901       /* Possibly overload the function if the first argument is
77902       ** a virtual table column.
77903       **
77904       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
77905       ** second argument, not the first, as the argument to test to
77906       ** see if it is a column in a virtual table.  This is done because
77907       ** the left operand of infix functions (the operand we want to
77908       ** control overloading) ends up as the second argument to the
77909       ** function.  The expression "A glob B" is equivalent to 
77910       ** "glob(B,A).  We want to use the A in "A glob B" to test
77911       ** for function overloading.  But we use the B term in "glob(B,A)".
77912       */
77913       if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
77914         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
77915       }else if( nFarg>0 ){
77916         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
77917       }
77918 #endif
77919       for(i=0; i<nFarg; i++){
77920         if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
77921           constMask |= (1<<i);
77922         }
77923         if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
77924           pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
77925         }
77926       }
77927       if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){
77928         if( !pColl ) pColl = db->pDfltColl; 
77929         sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
77930       }
77931       sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
77932                         (char*)pDef, P4_FUNCDEF);
77933       sqlite3VdbeChangeP5(v, (u8)nFarg);
77934       if( nFarg ){
77935         sqlite3ReleaseTempRange(pParse, r1, nFarg);
77936       }
77937       break;
77938     }
77939 #ifndef SQLITE_OMIT_SUBQUERY
77940     case TK_EXISTS:
77941     case TK_SELECT: {
77942       testcase( op==TK_EXISTS );
77943       testcase( op==TK_SELECT );
77944       inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
77945       break;
77946     }
77947     case TK_IN: {
77948       int destIfFalse = sqlite3VdbeMakeLabel(v);
77949       int destIfNull = sqlite3VdbeMakeLabel(v);
77950       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
77951       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
77952       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
77953       sqlite3VdbeResolveLabel(v, destIfFalse);
77954       sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
77955       sqlite3VdbeResolveLabel(v, destIfNull);
77956       break;
77957     }
77958 #endif /* SQLITE_OMIT_SUBQUERY */
77959
77960
77961     /*
77962     **    x BETWEEN y AND z
77963     **
77964     ** This is equivalent to
77965     **
77966     **    x>=y AND x<=z
77967     **
77968     ** X is stored in pExpr->pLeft.
77969     ** Y is stored in pExpr->pList->a[0].pExpr.
77970     ** Z is stored in pExpr->pList->a[1].pExpr.
77971     */
77972     case TK_BETWEEN: {
77973       Expr *pLeft = pExpr->pLeft;
77974       struct ExprList_item *pLItem = pExpr->x.pList->a;
77975       Expr *pRight = pLItem->pExpr;
77976
77977       r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
77978       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
77979       testcase( regFree1==0 );
77980       testcase( regFree2==0 );
77981       r3 = sqlite3GetTempReg(pParse);
77982       r4 = sqlite3GetTempReg(pParse);
77983       codeCompare(pParse, pLeft, pRight, OP_Ge,
77984                   r1, r2, r3, SQLITE_STOREP2);
77985       pLItem++;
77986       pRight = pLItem->pExpr;
77987       sqlite3ReleaseTempReg(pParse, regFree2);
77988       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
77989       testcase( regFree2==0 );
77990       codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
77991       sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
77992       sqlite3ReleaseTempReg(pParse, r3);
77993       sqlite3ReleaseTempReg(pParse, r4);
77994       break;
77995     }
77996     case TK_COLLATE: 
77997     case TK_UPLUS: {
77998       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
77999       break;
78000     }
78001
78002     case TK_TRIGGER: {
78003       /* If the opcode is TK_TRIGGER, then the expression is a reference
78004       ** to a column in the new.* or old.* pseudo-tables available to
78005       ** trigger programs. In this case Expr.iTable is set to 1 for the
78006       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
78007       ** is set to the column of the pseudo-table to read, or to -1 to
78008       ** read the rowid field.
78009       **
78010       ** The expression is implemented using an OP_Param opcode. The p1
78011       ** parameter is set to 0 for an old.rowid reference, or to (i+1)
78012       ** to reference another column of the old.* pseudo-table, where 
78013       ** i is the index of the column. For a new.rowid reference, p1 is
78014       ** set to (n+1), where n is the number of columns in each pseudo-table.
78015       ** For a reference to any other column in the new.* pseudo-table, p1
78016       ** is set to (n+2+i), where n and i are as defined previously. For
78017       ** example, if the table on which triggers are being fired is
78018       ** declared as:
78019       **
78020       **   CREATE TABLE t1(a, b);
78021       **
78022       ** Then p1 is interpreted as follows:
78023       **
78024       **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
78025       **   p1==1   ->    old.a         p1==4   ->    new.a
78026       **   p1==2   ->    old.b         p1==5   ->    new.b       
78027       */
78028       Table *pTab = pExpr->pTab;
78029       int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
78030
78031       assert( pExpr->iTable==0 || pExpr->iTable==1 );
78032       assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
78033       assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
78034       assert( p1>=0 && p1<(pTab->nCol*2+2) );
78035
78036       sqlite3VdbeAddOp2(v, OP_Param, p1, target);
78037       VdbeComment((v, "%s.%s -> $%d",
78038         (pExpr->iTable ? "new" : "old"),
78039         (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
78040         target
78041       ));
78042
78043 #ifndef SQLITE_OMIT_FLOATING_POINT
78044       /* If the column has REAL affinity, it may currently be stored as an
78045       ** integer. Use OP_RealAffinity to make sure it is really real.  */
78046       if( pExpr->iColumn>=0 
78047        && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
78048       ){
78049         sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
78050       }
78051 #endif
78052       break;
78053     }
78054
78055
78056     /*
78057     ** Form A:
78058     **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
78059     **
78060     ** Form B:
78061     **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
78062     **
78063     ** Form A is can be transformed into the equivalent form B as follows:
78064     **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
78065     **        WHEN x=eN THEN rN ELSE y END
78066     **
78067     ** X (if it exists) is in pExpr->pLeft.
78068     ** Y is in pExpr->pRight.  The Y is also optional.  If there is no
78069     ** ELSE clause and no other term matches, then the result of the
78070     ** exprssion is NULL.
78071     ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
78072     **
78073     ** The result of the expression is the Ri for the first matching Ei,
78074     ** or if there is no matching Ei, the ELSE term Y, or if there is
78075     ** no ELSE term, NULL.
78076     */
78077     default: assert( op==TK_CASE ); {
78078       int endLabel;                     /* GOTO label for end of CASE stmt */
78079       int nextCase;                     /* GOTO label for next WHEN clause */
78080       int nExpr;                        /* 2x number of WHEN terms */
78081       int i;                            /* Loop counter */
78082       ExprList *pEList;                 /* List of WHEN terms */
78083       struct ExprList_item *aListelem;  /* Array of WHEN terms */
78084       Expr opCompare;                   /* The X==Ei expression */
78085       Expr cacheX;                      /* Cached expression X */
78086       Expr *pX;                         /* The X expression */
78087       Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
78088       VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
78089
78090       assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
78091       assert((pExpr->x.pList->nExpr % 2) == 0);
78092       assert(pExpr->x.pList->nExpr > 0);
78093       pEList = pExpr->x.pList;
78094       aListelem = pEList->a;
78095       nExpr = pEList->nExpr;
78096       endLabel = sqlite3VdbeMakeLabel(v);
78097       if( (pX = pExpr->pLeft)!=0 ){
78098         cacheX = *pX;
78099         testcase( pX->op==TK_COLUMN );
78100         testcase( pX->op==TK_REGISTER );
78101         cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
78102         testcase( regFree1==0 );
78103         cacheX.op = TK_REGISTER;
78104         opCompare.op = TK_EQ;
78105         opCompare.pLeft = &cacheX;
78106         pTest = &opCompare;
78107         /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
78108         ** The value in regFree1 might get SCopy-ed into the file result.
78109         ** So make sure that the regFree1 register is not reused for other
78110         ** purposes and possibly overwritten.  */
78111         regFree1 = 0;
78112       }
78113       for(i=0; i<nExpr; i=i+2){
78114         sqlite3ExprCachePush(pParse);
78115         if( pX ){
78116           assert( pTest!=0 );
78117           opCompare.pRight = aListelem[i].pExpr;
78118         }else{
78119           pTest = aListelem[i].pExpr;
78120         }
78121         nextCase = sqlite3VdbeMakeLabel(v);
78122         testcase( pTest->op==TK_COLUMN );
78123         sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
78124         testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
78125         testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
78126         sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
78127         sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
78128         sqlite3ExprCachePop(pParse, 1);
78129         sqlite3VdbeResolveLabel(v, nextCase);
78130       }
78131       if( pExpr->pRight ){
78132         sqlite3ExprCachePush(pParse);
78133         sqlite3ExprCode(pParse, pExpr->pRight, target);
78134         sqlite3ExprCachePop(pParse, 1);
78135       }else{
78136         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
78137       }
78138       assert( db->mallocFailed || pParse->nErr>0 
78139            || pParse->iCacheLevel==iCacheLevel );
78140       sqlite3VdbeResolveLabel(v, endLabel);
78141       break;
78142     }
78143 #ifndef SQLITE_OMIT_TRIGGER
78144     case TK_RAISE: {
78145       assert( pExpr->affinity==OE_Rollback 
78146            || pExpr->affinity==OE_Abort
78147            || pExpr->affinity==OE_Fail
78148            || pExpr->affinity==OE_Ignore
78149       );
78150       if( !pParse->pTriggerTab ){
78151         sqlite3ErrorMsg(pParse,
78152                        "RAISE() may only be used within a trigger-program");
78153         return 0;
78154       }
78155       if( pExpr->affinity==OE_Abort ){
78156         sqlite3MayAbort(pParse);
78157       }
78158       assert( !ExprHasProperty(pExpr, EP_IntValue) );
78159       if( pExpr->affinity==OE_Ignore ){
78160         sqlite3VdbeAddOp4(
78161             v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
78162       }else{
78163         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
78164                               pExpr->affinity, pExpr->u.zToken, 0);
78165       }
78166
78167       break;
78168     }
78169 #endif
78170   }
78171   sqlite3ReleaseTempReg(pParse, regFree1);
78172   sqlite3ReleaseTempReg(pParse, regFree2);
78173   return inReg;
78174 }
78175
78176 /*
78177 ** Generate code to evaluate an expression and store the results
78178 ** into a register.  Return the register number where the results
78179 ** are stored.
78180 **
78181 ** If the register is a temporary register that can be deallocated,
78182 ** then write its number into *pReg.  If the result register is not
78183 ** a temporary, then set *pReg to zero.
78184 */
78185 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
78186   int r1 = sqlite3GetTempReg(pParse);
78187   int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
78188   if( r2==r1 ){
78189     *pReg = r1;
78190   }else{
78191     sqlite3ReleaseTempReg(pParse, r1);
78192     *pReg = 0;
78193   }
78194   return r2;
78195 }
78196
78197 /*
78198 ** Generate code that will evaluate expression pExpr and store the
78199 ** results in register target.  The results are guaranteed to appear
78200 ** in register target.
78201 */
78202 SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
78203   int inReg;
78204
78205   assert( target>0 && target<=pParse->nMem );
78206   if( pExpr && pExpr->op==TK_REGISTER ){
78207     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
78208   }else{
78209     inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
78210     assert( pParse->pVdbe || pParse->db->mallocFailed );
78211     if( inReg!=target && pParse->pVdbe ){
78212       sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
78213     }
78214   }
78215   return target;
78216 }
78217
78218 /*
78219 ** Generate code that evalutes the given expression and puts the result
78220 ** in register target.
78221 **
78222 ** Also make a copy of the expression results into another "cache" register
78223 ** and modify the expression so that the next time it is evaluated,
78224 ** the result is a copy of the cache register.
78225 **
78226 ** This routine is used for expressions that are used multiple 
78227 ** times.  They are evaluated once and the results of the expression
78228 ** are reused.
78229 */
78230 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
78231   Vdbe *v = pParse->pVdbe;
78232   int inReg;
78233   inReg = sqlite3ExprCode(pParse, pExpr, target);
78234   assert( target>0 );
78235   /* This routine is called for terms to INSERT or UPDATE.  And the only
78236   ** other place where expressions can be converted into TK_REGISTER is
78237   ** in WHERE clause processing.  So as currently implemented, there is
78238   ** no way for a TK_REGISTER to exist here.  But it seems prudent to
78239   ** keep the ALWAYS() in case the conditions above change with future
78240   ** modifications or enhancements. */
78241   if( ALWAYS(pExpr->op!=TK_REGISTER) ){  
78242     int iMem;
78243     iMem = ++pParse->nMem;
78244     sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
78245     pExpr->iTable = iMem;
78246     pExpr->op2 = pExpr->op;
78247     pExpr->op = TK_REGISTER;
78248   }
78249   return inReg;
78250 }
78251
78252 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
78253 /*
78254 ** Generate a human-readable explanation of an expression tree.
78255 */
78256 SQLITE_PRIVATE void sqlite3ExplainExpr(Vdbe *pOut, Expr *pExpr){
78257   int op;                   /* The opcode being coded */
78258   const char *zBinOp = 0;   /* Binary operator */
78259   const char *zUniOp = 0;   /* Unary operator */
78260   if( pExpr==0 ){
78261     op = TK_NULL;
78262   }else{
78263     op = pExpr->op;
78264   }
78265   switch( op ){
78266     case TK_AGG_COLUMN: {
78267       sqlite3ExplainPrintf(pOut, "AGG{%d:%d}",
78268             pExpr->iTable, pExpr->iColumn);
78269       break;
78270     }
78271     case TK_COLUMN: {
78272       if( pExpr->iTable<0 ){
78273         /* This only happens when coding check constraints */
78274         sqlite3ExplainPrintf(pOut, "COLUMN(%d)", pExpr->iColumn);
78275       }else{
78276         sqlite3ExplainPrintf(pOut, "{%d:%d}",
78277                              pExpr->iTable, pExpr->iColumn);
78278       }
78279       break;
78280     }
78281     case TK_INTEGER: {
78282       if( pExpr->flags & EP_IntValue ){
78283         sqlite3ExplainPrintf(pOut, "%d", pExpr->u.iValue);
78284       }else{
78285         sqlite3ExplainPrintf(pOut, "%s", pExpr->u.zToken);
78286       }
78287       break;
78288     }
78289 #ifndef SQLITE_OMIT_FLOATING_POINT
78290     case TK_FLOAT: {
78291       sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
78292       break;
78293     }
78294 #endif
78295     case TK_STRING: {
78296       sqlite3ExplainPrintf(pOut,"%Q", pExpr->u.zToken);
78297       break;
78298     }
78299     case TK_NULL: {
78300       sqlite3ExplainPrintf(pOut,"NULL");
78301       break;
78302     }
78303 #ifndef SQLITE_OMIT_BLOB_LITERAL
78304     case TK_BLOB: {
78305       sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
78306       break;
78307     }
78308 #endif
78309     case TK_VARIABLE: {
78310       sqlite3ExplainPrintf(pOut,"VARIABLE(%s,%d)",
78311                            pExpr->u.zToken, pExpr->iColumn);
78312       break;
78313     }
78314     case TK_REGISTER: {
78315       sqlite3ExplainPrintf(pOut,"REGISTER(%d)", pExpr->iTable);
78316       break;
78317     }
78318     case TK_AS: {
78319       sqlite3ExplainExpr(pOut, pExpr->pLeft);
78320       break;
78321     }
78322 #ifndef SQLITE_OMIT_CAST
78323     case TK_CAST: {
78324       /* Expressions of the form:   CAST(pLeft AS token) */
78325       const char *zAff = "unk";
78326       switch( sqlite3AffinityType(pExpr->u.zToken) ){
78327         case SQLITE_AFF_TEXT:    zAff = "TEXT";     break;
78328         case SQLITE_AFF_NONE:    zAff = "NONE";     break;
78329         case SQLITE_AFF_NUMERIC: zAff = "NUMERIC";  break;
78330         case SQLITE_AFF_INTEGER: zAff = "INTEGER";  break;
78331         case SQLITE_AFF_REAL:    zAff = "REAL";     break;
78332       }
78333       sqlite3ExplainPrintf(pOut, "CAST-%s(", zAff);
78334       sqlite3ExplainExpr(pOut, pExpr->pLeft);
78335       sqlite3ExplainPrintf(pOut, ")");
78336       break;
78337     }
78338 #endif /* SQLITE_OMIT_CAST */
78339     case TK_LT:      zBinOp = "LT";     break;
78340     case TK_LE:      zBinOp = "LE";     break;
78341     case TK_GT:      zBinOp = "GT";     break;
78342     case TK_GE:      zBinOp = "GE";     break;
78343     case TK_NE:      zBinOp = "NE";     break;
78344     case TK_EQ:      zBinOp = "EQ";     break;
78345     case TK_IS:      zBinOp = "IS";     break;
78346     case TK_ISNOT:   zBinOp = "ISNOT";  break;
78347     case TK_AND:     zBinOp = "AND";    break;
78348     case TK_OR:      zBinOp = "OR";     break;
78349     case TK_PLUS:    zBinOp = "ADD";    break;
78350     case TK_STAR:    zBinOp = "MUL";    break;
78351     case TK_MINUS:   zBinOp = "SUB";    break;
78352     case TK_REM:     zBinOp = "REM";    break;
78353     case TK_BITAND:  zBinOp = "BITAND"; break;
78354     case TK_BITOR:   zBinOp = "BITOR";  break;
78355     case TK_SLASH:   zBinOp = "DIV";    break;
78356     case TK_LSHIFT:  zBinOp = "LSHIFT"; break;
78357     case TK_RSHIFT:  zBinOp = "RSHIFT"; break;
78358     case TK_CONCAT:  zBinOp = "CONCAT"; break;
78359
78360     case TK_UMINUS:  zUniOp = "UMINUS"; break;
78361     case TK_UPLUS:   zUniOp = "UPLUS";  break;
78362     case TK_BITNOT:  zUniOp = "BITNOT"; break;
78363     case TK_NOT:     zUniOp = "NOT";    break;
78364     case TK_ISNULL:  zUniOp = "ISNULL"; break;
78365     case TK_NOTNULL: zUniOp = "NOTNULL"; break;
78366
78367     case TK_COLLATE: {
78368       sqlite3ExplainExpr(pOut, pExpr->pLeft);
78369       sqlite3ExplainPrintf(pOut,".COLLATE(%s)",pExpr->u.zToken);
78370       break;
78371     }
78372
78373     case TK_AGG_FUNCTION:
78374     case TK_CONST_FUNC:
78375     case TK_FUNCTION: {
78376       ExprList *pFarg;       /* List of function arguments */
78377       if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
78378         pFarg = 0;
78379       }else{
78380         pFarg = pExpr->x.pList;
78381       }
78382       if( op==TK_AGG_FUNCTION ){
78383         sqlite3ExplainPrintf(pOut, "AGG_FUNCTION%d:%s(",
78384                              pExpr->op2, pExpr->u.zToken);
78385       }else{
78386         sqlite3ExplainPrintf(pOut, "FUNCTION:%s(", pExpr->u.zToken);
78387       }
78388       if( pFarg ){
78389         sqlite3ExplainExprList(pOut, pFarg);
78390       }
78391       sqlite3ExplainPrintf(pOut, ")");
78392       break;
78393     }
78394 #ifndef SQLITE_OMIT_SUBQUERY
78395     case TK_EXISTS: {
78396       sqlite3ExplainPrintf(pOut, "EXISTS(");
78397       sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
78398       sqlite3ExplainPrintf(pOut,")");
78399       break;
78400     }
78401     case TK_SELECT: {
78402       sqlite3ExplainPrintf(pOut, "(");
78403       sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
78404       sqlite3ExplainPrintf(pOut, ")");
78405       break;
78406     }
78407     case TK_IN: {
78408       sqlite3ExplainPrintf(pOut, "IN(");
78409       sqlite3ExplainExpr(pOut, pExpr->pLeft);
78410       sqlite3ExplainPrintf(pOut, ",");
78411       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
78412         sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
78413       }else{
78414         sqlite3ExplainExprList(pOut, pExpr->x.pList);
78415       }
78416       sqlite3ExplainPrintf(pOut, ")");
78417       break;
78418     }
78419 #endif /* SQLITE_OMIT_SUBQUERY */
78420
78421     /*
78422     **    x BETWEEN y AND z
78423     **
78424     ** This is equivalent to
78425     **
78426     **    x>=y AND x<=z
78427     **
78428     ** X is stored in pExpr->pLeft.
78429     ** Y is stored in pExpr->pList->a[0].pExpr.
78430     ** Z is stored in pExpr->pList->a[1].pExpr.
78431     */
78432     case TK_BETWEEN: {
78433       Expr *pX = pExpr->pLeft;
78434       Expr *pY = pExpr->x.pList->a[0].pExpr;
78435       Expr *pZ = pExpr->x.pList->a[1].pExpr;
78436       sqlite3ExplainPrintf(pOut, "BETWEEN(");
78437       sqlite3ExplainExpr(pOut, pX);
78438       sqlite3ExplainPrintf(pOut, ",");
78439       sqlite3ExplainExpr(pOut, pY);
78440       sqlite3ExplainPrintf(pOut, ",");
78441       sqlite3ExplainExpr(pOut, pZ);
78442       sqlite3ExplainPrintf(pOut, ")");
78443       break;
78444     }
78445     case TK_TRIGGER: {
78446       /* If the opcode is TK_TRIGGER, then the expression is a reference
78447       ** to a column in the new.* or old.* pseudo-tables available to
78448       ** trigger programs. In this case Expr.iTable is set to 1 for the
78449       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
78450       ** is set to the column of the pseudo-table to read, or to -1 to
78451       ** read the rowid field.
78452       */
78453       sqlite3ExplainPrintf(pOut, "%s(%d)", 
78454           pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
78455       break;
78456     }
78457     case TK_CASE: {
78458       sqlite3ExplainPrintf(pOut, "CASE(");
78459       sqlite3ExplainExpr(pOut, pExpr->pLeft);
78460       sqlite3ExplainPrintf(pOut, ",");
78461       sqlite3ExplainExprList(pOut, pExpr->x.pList);
78462       break;
78463     }
78464 #ifndef SQLITE_OMIT_TRIGGER
78465     case TK_RAISE: {
78466       const char *zType = "unk";
78467       switch( pExpr->affinity ){
78468         case OE_Rollback:   zType = "rollback";  break;
78469         case OE_Abort:      zType = "abort";     break;
78470         case OE_Fail:       zType = "fail";      break;
78471         case OE_Ignore:     zType = "ignore";    break;
78472       }
78473       sqlite3ExplainPrintf(pOut, "RAISE-%s(%s)", zType, pExpr->u.zToken);
78474       break;
78475     }
78476 #endif
78477   }
78478   if( zBinOp ){
78479     sqlite3ExplainPrintf(pOut,"%s(", zBinOp);
78480     sqlite3ExplainExpr(pOut, pExpr->pLeft);
78481     sqlite3ExplainPrintf(pOut,",");
78482     sqlite3ExplainExpr(pOut, pExpr->pRight);
78483     sqlite3ExplainPrintf(pOut,")");
78484   }else if( zUniOp ){
78485     sqlite3ExplainPrintf(pOut,"%s(", zUniOp);
78486     sqlite3ExplainExpr(pOut, pExpr->pLeft);
78487     sqlite3ExplainPrintf(pOut,")");
78488   }
78489 }
78490 #endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
78491
78492 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
78493 /*
78494 ** Generate a human-readable explanation of an expression list.
78495 */
78496 SQLITE_PRIVATE void sqlite3ExplainExprList(Vdbe *pOut, ExprList *pList){
78497   int i;
78498   if( pList==0 || pList->nExpr==0 ){
78499     sqlite3ExplainPrintf(pOut, "(empty-list)");
78500     return;
78501   }else if( pList->nExpr==1 ){
78502     sqlite3ExplainExpr(pOut, pList->a[0].pExpr);
78503   }else{
78504     sqlite3ExplainPush(pOut);
78505     for(i=0; i<pList->nExpr; i++){
78506       sqlite3ExplainPrintf(pOut, "item[%d] = ", i);
78507       sqlite3ExplainPush(pOut);
78508       sqlite3ExplainExpr(pOut, pList->a[i].pExpr);
78509       sqlite3ExplainPop(pOut);
78510       if( pList->a[i].zName ){
78511         sqlite3ExplainPrintf(pOut, " AS %s", pList->a[i].zName);
78512       }
78513       if( pList->a[i].bSpanIsTab ){
78514         sqlite3ExplainPrintf(pOut, " (%s)", pList->a[i].zSpan);
78515       }
78516       if( i<pList->nExpr-1 ){
78517         sqlite3ExplainNL(pOut);
78518       }
78519     }
78520     sqlite3ExplainPop(pOut);
78521   }
78522 }
78523 #endif /* SQLITE_DEBUG */
78524
78525 /*
78526 ** Return TRUE if pExpr is an constant expression that is appropriate
78527 ** for factoring out of a loop.  Appropriate expressions are:
78528 **
78529 **    *  Any expression that evaluates to two or more opcodes.
78530 **
78531 **    *  Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null, 
78532 **       or OP_Variable that does not need to be placed in a 
78533 **       specific register.
78534 **
78535 ** There is no point in factoring out single-instruction constant
78536 ** expressions that need to be placed in a particular register.  
78537 ** We could factor them out, but then we would end up adding an
78538 ** OP_SCopy instruction to move the value into the correct register
78539 ** later.  We might as well just use the original instruction and
78540 ** avoid the OP_SCopy.
78541 */
78542 static int isAppropriateForFactoring(Expr *p){
78543   if( !sqlite3ExprIsConstantNotJoin(p) ){
78544     return 0;  /* Only constant expressions are appropriate for factoring */
78545   }
78546   if( (p->flags & EP_FixedDest)==0 ){
78547     return 1;  /* Any constant without a fixed destination is appropriate */
78548   }
78549   while( p->op==TK_UPLUS ) p = p->pLeft;
78550   switch( p->op ){
78551 #ifndef SQLITE_OMIT_BLOB_LITERAL
78552     case TK_BLOB:
78553 #endif
78554     case TK_VARIABLE:
78555     case TK_INTEGER:
78556     case TK_FLOAT:
78557     case TK_NULL:
78558     case TK_STRING: {
78559       testcase( p->op==TK_BLOB );
78560       testcase( p->op==TK_VARIABLE );
78561       testcase( p->op==TK_INTEGER );
78562       testcase( p->op==TK_FLOAT );
78563       testcase( p->op==TK_NULL );
78564       testcase( p->op==TK_STRING );
78565       /* Single-instruction constants with a fixed destination are
78566       ** better done in-line.  If we factor them, they will just end
78567       ** up generating an OP_SCopy to move the value to the destination
78568       ** register. */
78569       return 0;
78570     }
78571     case TK_UMINUS: {
78572       if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
78573         return 0;
78574       }
78575       break;
78576     }
78577     default: {
78578       break;
78579     }
78580   }
78581   return 1;
78582 }
78583
78584 /*
78585 ** If pExpr is a constant expression that is appropriate for
78586 ** factoring out of a loop, then evaluate the expression
78587 ** into a register and convert the expression into a TK_REGISTER
78588 ** expression.
78589 */
78590 static int evalConstExpr(Walker *pWalker, Expr *pExpr){
78591   Parse *pParse = pWalker->pParse;
78592   switch( pExpr->op ){
78593     case TK_IN:
78594     case TK_REGISTER: {
78595       return WRC_Prune;
78596     }
78597     case TK_COLLATE: {
78598       return WRC_Continue;
78599     }
78600     case TK_FUNCTION:
78601     case TK_AGG_FUNCTION:
78602     case TK_CONST_FUNC: {
78603       /* The arguments to a function have a fixed destination.
78604       ** Mark them this way to avoid generated unneeded OP_SCopy
78605       ** instructions. 
78606       */
78607       ExprList *pList = pExpr->x.pList;
78608       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
78609       if( pList ){
78610         int i = pList->nExpr;
78611         struct ExprList_item *pItem = pList->a;
78612         for(; i>0; i--, pItem++){
78613           if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
78614         }
78615       }
78616       break;
78617     }
78618   }
78619   if( isAppropriateForFactoring(pExpr) ){
78620     int r1 = ++pParse->nMem;
78621     int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
78622     /* If r2!=r1, it means that register r1 is never used.  That is harmless
78623     ** but suboptimal, so we want to know about the situation to fix it.
78624     ** Hence the following assert: */
78625     assert( r2==r1 );
78626     pExpr->op2 = pExpr->op;
78627     pExpr->op = TK_REGISTER;
78628     pExpr->iTable = r2;
78629     return WRC_Prune;
78630   }
78631   return WRC_Continue;
78632 }
78633
78634 /*
78635 ** Preevaluate constant subexpressions within pExpr and store the
78636 ** results in registers.  Modify pExpr so that the constant subexpresions
78637 ** are TK_REGISTER opcodes that refer to the precomputed values.
78638 **
78639 ** This routine is a no-op if the jump to the cookie-check code has
78640 ** already occur.  Since the cookie-check jump is generated prior to
78641 ** any other serious processing, this check ensures that there is no
78642 ** way to accidently bypass the constant initializations.
78643 **
78644 ** This routine is also a no-op if the SQLITE_FactorOutConst optimization
78645 ** is disabled via the sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS)
78646 ** interface.  This allows test logic to verify that the same answer is
78647 ** obtained for queries regardless of whether or not constants are
78648 ** precomputed into registers or if they are inserted in-line.
78649 */
78650 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
78651   Walker w;
78652   if( pParse->cookieGoto ) return;
78653   if( OptimizationDisabled(pParse->db, SQLITE_FactorOutConst) ) return;
78654   memset(&w, 0, sizeof(w));
78655   w.xExprCallback = evalConstExpr;
78656   w.pParse = pParse;
78657   sqlite3WalkExpr(&w, pExpr);
78658 }
78659
78660
78661 /*
78662 ** Generate code that pushes the value of every element of the given
78663 ** expression list into a sequence of registers beginning at target.
78664 **
78665 ** Return the number of elements evaluated.
78666 */
78667 SQLITE_PRIVATE int sqlite3ExprCodeExprList(
78668   Parse *pParse,     /* Parsing context */
78669   ExprList *pList,   /* The expression list to be coded */
78670   int target,        /* Where to write results */
78671   int doHardCopy     /* Make a hard copy of every element */
78672 ){
78673   struct ExprList_item *pItem;
78674   int i, n;
78675   assert( pList!=0 );
78676   assert( target>0 );
78677   assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */
78678   n = pList->nExpr;
78679   for(pItem=pList->a, i=0; i<n; i++, pItem++){
78680     Expr *pExpr = pItem->pExpr;
78681     int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
78682     if( inReg!=target+i ){
78683       sqlite3VdbeAddOp2(pParse->pVdbe, doHardCopy ? OP_Copy : OP_SCopy,
78684                         inReg, target+i);
78685     }
78686   }
78687   return n;
78688 }
78689
78690 /*
78691 ** Generate code for a BETWEEN operator.
78692 **
78693 **    x BETWEEN y AND z
78694 **
78695 ** The above is equivalent to 
78696 **
78697 **    x>=y AND x<=z
78698 **
78699 ** Code it as such, taking care to do the common subexpression
78700 ** elementation of x.
78701 */
78702 static void exprCodeBetween(
78703   Parse *pParse,    /* Parsing and code generating context */
78704   Expr *pExpr,      /* The BETWEEN expression */
78705   int dest,         /* Jump here if the jump is taken */
78706   int jumpIfTrue,   /* Take the jump if the BETWEEN is true */
78707   int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
78708 ){
78709   Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
78710   Expr compLeft;    /* The  x>=y  term */
78711   Expr compRight;   /* The  x<=z  term */
78712   Expr exprX;       /* The  x  subexpression */
78713   int regFree1 = 0; /* Temporary use register */
78714
78715   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
78716   exprX = *pExpr->pLeft;
78717   exprAnd.op = TK_AND;
78718   exprAnd.pLeft = &compLeft;
78719   exprAnd.pRight = &compRight;
78720   compLeft.op = TK_GE;
78721   compLeft.pLeft = &exprX;
78722   compLeft.pRight = pExpr->x.pList->a[0].pExpr;
78723   compRight.op = TK_LE;
78724   compRight.pLeft = &exprX;
78725   compRight.pRight = pExpr->x.pList->a[1].pExpr;
78726   exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
78727   exprX.op = TK_REGISTER;
78728   if( jumpIfTrue ){
78729     sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
78730   }else{
78731     sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
78732   }
78733   sqlite3ReleaseTempReg(pParse, regFree1);
78734
78735   /* Ensure adequate test coverage */
78736   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
78737   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
78738   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
78739   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
78740   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
78741   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
78742   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
78743   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
78744 }
78745
78746 /*
78747 ** Generate code for a boolean expression such that a jump is made
78748 ** to the label "dest" if the expression is true but execution
78749 ** continues straight thru if the expression is false.
78750 **
78751 ** If the expression evaluates to NULL (neither true nor false), then
78752 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
78753 **
78754 ** This code depends on the fact that certain token values (ex: TK_EQ)
78755 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
78756 ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
78757 ** the make process cause these values to align.  Assert()s in the code
78758 ** below verify that the numbers are aligned correctly.
78759 */
78760 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
78761   Vdbe *v = pParse->pVdbe;
78762   int op = 0;
78763   int regFree1 = 0;
78764   int regFree2 = 0;
78765   int r1, r2;
78766
78767   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
78768   if( NEVER(v==0) )     return;  /* Existence of VDBE checked by caller */
78769   if( NEVER(pExpr==0) ) return;  /* No way this can happen */
78770   op = pExpr->op;
78771   switch( op ){
78772     case TK_AND: {
78773       int d2 = sqlite3VdbeMakeLabel(v);
78774       testcase( jumpIfNull==0 );
78775       sqlite3ExprCachePush(pParse);
78776       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
78777       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
78778       sqlite3VdbeResolveLabel(v, d2);
78779       sqlite3ExprCachePop(pParse, 1);
78780       break;
78781     }
78782     case TK_OR: {
78783       testcase( jumpIfNull==0 );
78784       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
78785       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
78786       break;
78787     }
78788     case TK_NOT: {
78789       testcase( jumpIfNull==0 );
78790       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
78791       break;
78792     }
78793     case TK_LT:
78794     case TK_LE:
78795     case TK_GT:
78796     case TK_GE:
78797     case TK_NE:
78798     case TK_EQ: {
78799       assert( TK_LT==OP_Lt );
78800       assert( TK_LE==OP_Le );
78801       assert( TK_GT==OP_Gt );
78802       assert( TK_GE==OP_Ge );
78803       assert( TK_EQ==OP_Eq );
78804       assert( TK_NE==OP_Ne );
78805       testcase( op==TK_LT );
78806       testcase( op==TK_LE );
78807       testcase( op==TK_GT );
78808       testcase( op==TK_GE );
78809       testcase( op==TK_EQ );
78810       testcase( op==TK_NE );
78811       testcase( jumpIfNull==0 );
78812       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
78813       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
78814       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
78815                   r1, r2, dest, jumpIfNull);
78816       testcase( regFree1==0 );
78817       testcase( regFree2==0 );
78818       break;
78819     }
78820     case TK_IS:
78821     case TK_ISNOT: {
78822       testcase( op==TK_IS );
78823       testcase( op==TK_ISNOT );
78824       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
78825       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
78826       op = (op==TK_IS) ? TK_EQ : TK_NE;
78827       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
78828                   r1, r2, dest, SQLITE_NULLEQ);
78829       testcase( regFree1==0 );
78830       testcase( regFree2==0 );
78831       break;
78832     }
78833     case TK_ISNULL:
78834     case TK_NOTNULL: {
78835       assert( TK_ISNULL==OP_IsNull );
78836       assert( TK_NOTNULL==OP_NotNull );
78837       testcase( op==TK_ISNULL );
78838       testcase( op==TK_NOTNULL );
78839       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
78840       sqlite3VdbeAddOp2(v, op, r1, dest);
78841       testcase( regFree1==0 );
78842       break;
78843     }
78844     case TK_BETWEEN: {
78845       testcase( jumpIfNull==0 );
78846       exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
78847       break;
78848     }
78849 #ifndef SQLITE_OMIT_SUBQUERY
78850     case TK_IN: {
78851       int destIfFalse = sqlite3VdbeMakeLabel(v);
78852       int destIfNull = jumpIfNull ? dest : destIfFalse;
78853       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
78854       sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
78855       sqlite3VdbeResolveLabel(v, destIfFalse);
78856       break;
78857     }
78858 #endif
78859     default: {
78860       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
78861       sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
78862       testcase( regFree1==0 );
78863       testcase( jumpIfNull==0 );
78864       break;
78865     }
78866   }
78867   sqlite3ReleaseTempReg(pParse, regFree1);
78868   sqlite3ReleaseTempReg(pParse, regFree2);  
78869 }
78870
78871 /*
78872 ** Generate code for a boolean expression such that a jump is made
78873 ** to the label "dest" if the expression is false but execution
78874 ** continues straight thru if the expression is true.
78875 **
78876 ** If the expression evaluates to NULL (neither true nor false) then
78877 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
78878 ** is 0.
78879 */
78880 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
78881   Vdbe *v = pParse->pVdbe;
78882   int op = 0;
78883   int regFree1 = 0;
78884   int regFree2 = 0;
78885   int r1, r2;
78886
78887   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
78888   if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
78889   if( pExpr==0 )    return;
78890
78891   /* The value of pExpr->op and op are related as follows:
78892   **
78893   **       pExpr->op            op
78894   **       ---------          ----------
78895   **       TK_ISNULL          OP_NotNull
78896   **       TK_NOTNULL         OP_IsNull
78897   **       TK_NE              OP_Eq
78898   **       TK_EQ              OP_Ne
78899   **       TK_GT              OP_Le
78900   **       TK_LE              OP_Gt
78901   **       TK_GE              OP_Lt
78902   **       TK_LT              OP_Ge
78903   **
78904   ** For other values of pExpr->op, op is undefined and unused.
78905   ** The value of TK_ and OP_ constants are arranged such that we
78906   ** can compute the mapping above using the following expression.
78907   ** Assert()s verify that the computation is correct.
78908   */
78909   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
78910
78911   /* Verify correct alignment of TK_ and OP_ constants
78912   */
78913   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
78914   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
78915   assert( pExpr->op!=TK_NE || op==OP_Eq );
78916   assert( pExpr->op!=TK_EQ || op==OP_Ne );
78917   assert( pExpr->op!=TK_LT || op==OP_Ge );
78918   assert( pExpr->op!=TK_LE || op==OP_Gt );
78919   assert( pExpr->op!=TK_GT || op==OP_Le );
78920   assert( pExpr->op!=TK_GE || op==OP_Lt );
78921
78922   switch( pExpr->op ){
78923     case TK_AND: {
78924       testcase( jumpIfNull==0 );
78925       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
78926       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
78927       break;
78928     }
78929     case TK_OR: {
78930       int d2 = sqlite3VdbeMakeLabel(v);
78931       testcase( jumpIfNull==0 );
78932       sqlite3ExprCachePush(pParse);
78933       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
78934       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
78935       sqlite3VdbeResolveLabel(v, d2);
78936       sqlite3ExprCachePop(pParse, 1);
78937       break;
78938     }
78939     case TK_NOT: {
78940       testcase( jumpIfNull==0 );
78941       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
78942       break;
78943     }
78944     case TK_LT:
78945     case TK_LE:
78946     case TK_GT:
78947     case TK_GE:
78948     case TK_NE:
78949     case TK_EQ: {
78950       testcase( op==TK_LT );
78951       testcase( op==TK_LE );
78952       testcase( op==TK_GT );
78953       testcase( op==TK_GE );
78954       testcase( op==TK_EQ );
78955       testcase( op==TK_NE );
78956       testcase( jumpIfNull==0 );
78957       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
78958       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
78959       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
78960                   r1, r2, dest, jumpIfNull);
78961       testcase( regFree1==0 );
78962       testcase( regFree2==0 );
78963       break;
78964     }
78965     case TK_IS:
78966     case TK_ISNOT: {
78967       testcase( pExpr->op==TK_IS );
78968       testcase( pExpr->op==TK_ISNOT );
78969       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
78970       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
78971       op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
78972       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
78973                   r1, r2, dest, SQLITE_NULLEQ);
78974       testcase( regFree1==0 );
78975       testcase( regFree2==0 );
78976       break;
78977     }
78978     case TK_ISNULL:
78979     case TK_NOTNULL: {
78980       testcase( op==TK_ISNULL );
78981       testcase( op==TK_NOTNULL );
78982       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
78983       sqlite3VdbeAddOp2(v, op, r1, dest);
78984       testcase( regFree1==0 );
78985       break;
78986     }
78987     case TK_BETWEEN: {
78988       testcase( jumpIfNull==0 );
78989       exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
78990       break;
78991     }
78992 #ifndef SQLITE_OMIT_SUBQUERY
78993     case TK_IN: {
78994       if( jumpIfNull ){
78995         sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
78996       }else{
78997         int destIfNull = sqlite3VdbeMakeLabel(v);
78998         sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
78999         sqlite3VdbeResolveLabel(v, destIfNull);
79000       }
79001       break;
79002     }
79003 #endif
79004     default: {
79005       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
79006       sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
79007       testcase( regFree1==0 );
79008       testcase( jumpIfNull==0 );
79009       break;
79010     }
79011   }
79012   sqlite3ReleaseTempReg(pParse, regFree1);
79013   sqlite3ReleaseTempReg(pParse, regFree2);
79014 }
79015
79016 /*
79017 ** Do a deep comparison of two expression trees.  Return 0 if the two
79018 ** expressions are completely identical.  Return 1 if they differ only
79019 ** by a COLLATE operator at the top level.  Return 2 if there are differences
79020 ** other than the top-level COLLATE operator.
79021 **
79022 ** Sometimes this routine will return 2 even if the two expressions
79023 ** really are equivalent.  If we cannot prove that the expressions are
79024 ** identical, we return 2 just to be safe.  So if this routine
79025 ** returns 2, then you do not really know for certain if the two
79026 ** expressions are the same.  But if you get a 0 or 1 return, then you
79027 ** can be sure the expressions are the same.  In the places where
79028 ** this routine is used, it does not hurt to get an extra 2 - that
79029 ** just might result in some slightly slower code.  But returning
79030 ** an incorrect 0 or 1 could lead to a malfunction.
79031 */
79032 SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB){
79033   if( pA==0||pB==0 ){
79034     return pB==pA ? 0 : 2;
79035   }
79036   assert( !ExprHasAnyProperty(pA, EP_TokenOnly|EP_Reduced) );
79037   assert( !ExprHasAnyProperty(pB, EP_TokenOnly|EP_Reduced) );
79038   if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
79039     return 2;
79040   }
79041   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
79042   if( pA->op!=pB->op ){
79043     if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB)<2 ){
79044       return 1;
79045     }
79046     if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft)<2 ){
79047       return 1;
79048     }
79049     return 2;
79050   }
79051   if( sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 2;
79052   if( sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 2;
79053   if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList) ) return 2;
79054   if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 2;
79055   if( ExprHasProperty(pA, EP_IntValue) ){
79056     if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
79057       return 2;
79058     }
79059   }else if( pA->op!=TK_COLUMN && ALWAYS(pA->op!=TK_AGG_COLUMN) && pA->u.zToken){
79060     if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 2;
79061     if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
79062       return pA->op==TK_COLLATE ? 1 : 2;
79063     }
79064   }
79065   return 0;
79066 }
79067
79068 /*
79069 ** Compare two ExprList objects.  Return 0 if they are identical and 
79070 ** non-zero if they differ in any way.
79071 **
79072 ** This routine might return non-zero for equivalent ExprLists.  The
79073 ** only consequence will be disabled optimizations.  But this routine
79074 ** must never return 0 if the two ExprList objects are different, or
79075 ** a malfunction will result.
79076 **
79077 ** Two NULL pointers are considered to be the same.  But a NULL pointer
79078 ** always differs from a non-NULL pointer.
79079 */
79080 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB){
79081   int i;
79082   if( pA==0 && pB==0 ) return 0;
79083   if( pA==0 || pB==0 ) return 1;
79084   if( pA->nExpr!=pB->nExpr ) return 1;
79085   for(i=0; i<pA->nExpr; i++){
79086     Expr *pExprA = pA->a[i].pExpr;
79087     Expr *pExprB = pB->a[i].pExpr;
79088     if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
79089     if( sqlite3ExprCompare(pExprA, pExprB) ) return 1;
79090   }
79091   return 0;
79092 }
79093
79094 /*
79095 ** An instance of the following structure is used by the tree walker
79096 ** to count references to table columns in the arguments of an 
79097 ** aggregate function, in order to implement the
79098 ** sqlite3FunctionThisSrc() routine.
79099 */
79100 struct SrcCount {
79101   SrcList *pSrc;   /* One particular FROM clause in a nested query */
79102   int nThis;       /* Number of references to columns in pSrcList */
79103   int nOther;      /* Number of references to columns in other FROM clauses */
79104 };
79105
79106 /*
79107 ** Count the number of references to columns.
79108 */
79109 static int exprSrcCount(Walker *pWalker, Expr *pExpr){
79110   /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
79111   ** is always called before sqlite3ExprAnalyzeAggregates() and so the
79112   ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN.  If
79113   ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
79114   ** NEVER() will need to be removed. */
79115   if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
79116     int i;
79117     struct SrcCount *p = pWalker->u.pSrcCount;
79118     SrcList *pSrc = p->pSrc;
79119     for(i=0; i<pSrc->nSrc; i++){
79120       if( pExpr->iTable==pSrc->a[i].iCursor ) break;
79121     }
79122     if( i<pSrc->nSrc ){
79123       p->nThis++;
79124     }else{
79125       p->nOther++;
79126     }
79127   }
79128   return WRC_Continue;
79129 }
79130
79131 /*
79132 ** Determine if any of the arguments to the pExpr Function reference
79133 ** pSrcList.  Return true if they do.  Also return true if the function
79134 ** has no arguments or has only constant arguments.  Return false if pExpr
79135 ** references columns but not columns of tables found in pSrcList.
79136 */
79137 SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
79138   Walker w;
79139   struct SrcCount cnt;
79140   assert( pExpr->op==TK_AGG_FUNCTION );
79141   memset(&w, 0, sizeof(w));
79142   w.xExprCallback = exprSrcCount;
79143   w.u.pSrcCount = &cnt;
79144   cnt.pSrc = pSrcList;
79145   cnt.nThis = 0;
79146   cnt.nOther = 0;
79147   sqlite3WalkExprList(&w, pExpr->x.pList);
79148   return cnt.nThis>0 || cnt.nOther==0;
79149 }
79150
79151 /*
79152 ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
79153 ** the new element.  Return a negative number if malloc fails.
79154 */
79155 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
79156   int i;
79157   pInfo->aCol = sqlite3ArrayAllocate(
79158        db,
79159        pInfo->aCol,
79160        sizeof(pInfo->aCol[0]),
79161        &pInfo->nColumn,
79162        &i
79163   );
79164   return i;
79165 }    
79166
79167 /*
79168 ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
79169 ** the new element.  Return a negative number if malloc fails.
79170 */
79171 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
79172   int i;
79173   pInfo->aFunc = sqlite3ArrayAllocate(
79174        db, 
79175        pInfo->aFunc,
79176        sizeof(pInfo->aFunc[0]),
79177        &pInfo->nFunc,
79178        &i
79179   );
79180   return i;
79181 }    
79182
79183 /*
79184 ** This is the xExprCallback for a tree walker.  It is used to
79185 ** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
79186 ** for additional information.
79187 */
79188 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
79189   int i;
79190   NameContext *pNC = pWalker->u.pNC;
79191   Parse *pParse = pNC->pParse;
79192   SrcList *pSrcList = pNC->pSrcList;
79193   AggInfo *pAggInfo = pNC->pAggInfo;
79194
79195   switch( pExpr->op ){
79196     case TK_AGG_COLUMN:
79197     case TK_COLUMN: {
79198       testcase( pExpr->op==TK_AGG_COLUMN );
79199       testcase( pExpr->op==TK_COLUMN );
79200       /* Check to see if the column is in one of the tables in the FROM
79201       ** clause of the aggregate query */
79202       if( ALWAYS(pSrcList!=0) ){
79203         struct SrcList_item *pItem = pSrcList->a;
79204         for(i=0; i<pSrcList->nSrc; i++, pItem++){
79205           struct AggInfo_col *pCol;
79206           assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
79207           if( pExpr->iTable==pItem->iCursor ){
79208             /* If we reach this point, it means that pExpr refers to a table
79209             ** that is in the FROM clause of the aggregate query.  
79210             **
79211             ** Make an entry for the column in pAggInfo->aCol[] if there
79212             ** is not an entry there already.
79213             */
79214             int k;
79215             pCol = pAggInfo->aCol;
79216             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
79217               if( pCol->iTable==pExpr->iTable &&
79218                   pCol->iColumn==pExpr->iColumn ){
79219                 break;
79220               }
79221             }
79222             if( (k>=pAggInfo->nColumn)
79223              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0 
79224             ){
79225               pCol = &pAggInfo->aCol[k];
79226               pCol->pTab = pExpr->pTab;
79227               pCol->iTable = pExpr->iTable;
79228               pCol->iColumn = pExpr->iColumn;
79229               pCol->iMem = ++pParse->nMem;
79230               pCol->iSorterColumn = -1;
79231               pCol->pExpr = pExpr;
79232               if( pAggInfo->pGroupBy ){
79233                 int j, n;
79234                 ExprList *pGB = pAggInfo->pGroupBy;
79235                 struct ExprList_item *pTerm = pGB->a;
79236                 n = pGB->nExpr;
79237                 for(j=0; j<n; j++, pTerm++){
79238                   Expr *pE = pTerm->pExpr;
79239                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
79240                       pE->iColumn==pExpr->iColumn ){
79241                     pCol->iSorterColumn = j;
79242                     break;
79243                   }
79244                 }
79245               }
79246               if( pCol->iSorterColumn<0 ){
79247                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
79248               }
79249             }
79250             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
79251             ** because it was there before or because we just created it).
79252             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
79253             ** pAggInfo->aCol[] entry.
79254             */
79255             ExprSetIrreducible(pExpr);
79256             pExpr->pAggInfo = pAggInfo;
79257             pExpr->op = TK_AGG_COLUMN;
79258             pExpr->iAgg = (i16)k;
79259             break;
79260           } /* endif pExpr->iTable==pItem->iCursor */
79261         } /* end loop over pSrcList */
79262       }
79263       return WRC_Prune;
79264     }
79265     case TK_AGG_FUNCTION: {
79266       if( (pNC->ncFlags & NC_InAggFunc)==0
79267        && pWalker->walkerDepth==pExpr->op2
79268       ){
79269         /* Check to see if pExpr is a duplicate of another aggregate 
79270         ** function that is already in the pAggInfo structure
79271         */
79272         struct AggInfo_func *pItem = pAggInfo->aFunc;
79273         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
79274           if( sqlite3ExprCompare(pItem->pExpr, pExpr)==0 ){
79275             break;
79276           }
79277         }
79278         if( i>=pAggInfo->nFunc ){
79279           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
79280           */
79281           u8 enc = ENC(pParse->db);
79282           i = addAggInfoFunc(pParse->db, pAggInfo);
79283           if( i>=0 ){
79284             assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
79285             pItem = &pAggInfo->aFunc[i];
79286             pItem->pExpr = pExpr;
79287             pItem->iMem = ++pParse->nMem;
79288             assert( !ExprHasProperty(pExpr, EP_IntValue) );
79289             pItem->pFunc = sqlite3FindFunction(pParse->db,
79290                    pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
79291                    pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
79292             if( pExpr->flags & EP_Distinct ){
79293               pItem->iDistinct = pParse->nTab++;
79294             }else{
79295               pItem->iDistinct = -1;
79296             }
79297           }
79298         }
79299         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
79300         */
79301         assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
79302         ExprSetIrreducible(pExpr);
79303         pExpr->iAgg = (i16)i;
79304         pExpr->pAggInfo = pAggInfo;
79305         return WRC_Prune;
79306       }else{
79307         return WRC_Continue;
79308       }
79309     }
79310   }
79311   return WRC_Continue;
79312 }
79313 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
79314   UNUSED_PARAMETER(pWalker);
79315   UNUSED_PARAMETER(pSelect);
79316   return WRC_Continue;
79317 }
79318
79319 /*
79320 ** Analyze the pExpr expression looking for aggregate functions and
79321 ** for variables that need to be added to AggInfo object that pNC->pAggInfo
79322 ** points to.  Additional entries are made on the AggInfo object as
79323 ** necessary.
79324 **
79325 ** This routine should only be called after the expression has been
79326 ** analyzed by sqlite3ResolveExprNames().
79327 */
79328 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
79329   Walker w;
79330   memset(&w, 0, sizeof(w));
79331   w.xExprCallback = analyzeAggregate;
79332   w.xSelectCallback = analyzeAggregatesInSelect;
79333   w.u.pNC = pNC;
79334   assert( pNC->pSrcList!=0 );
79335   sqlite3WalkExpr(&w, pExpr);
79336 }
79337
79338 /*
79339 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
79340 ** expression list.  Return the number of errors.
79341 **
79342 ** If an error is found, the analysis is cut short.
79343 */
79344 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
79345   struct ExprList_item *pItem;
79346   int i;
79347   if( pList ){
79348     for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
79349       sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
79350     }
79351   }
79352 }
79353
79354 /*
79355 ** Allocate a single new register for use to hold some intermediate result.
79356 */
79357 SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
79358   if( pParse->nTempReg==0 ){
79359     return ++pParse->nMem;
79360   }
79361   return pParse->aTempReg[--pParse->nTempReg];
79362 }
79363
79364 /*
79365 ** Deallocate a register, making available for reuse for some other
79366 ** purpose.
79367 **
79368 ** If a register is currently being used by the column cache, then
79369 ** the dallocation is deferred until the column cache line that uses
79370 ** the register becomes stale.
79371 */
79372 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
79373   if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
79374     int i;
79375     struct yColCache *p;
79376     for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
79377       if( p->iReg==iReg ){
79378         p->tempReg = 1;
79379         return;
79380       }
79381     }
79382     pParse->aTempReg[pParse->nTempReg++] = iReg;
79383   }
79384 }
79385
79386 /*
79387 ** Allocate or deallocate a block of nReg consecutive registers
79388 */
79389 SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
79390   int i, n;
79391   i = pParse->iRangeReg;
79392   n = pParse->nRangeReg;
79393   if( nReg<=n ){
79394     assert( !usedAsColumnCache(pParse, i, i+n-1) );
79395     pParse->iRangeReg += nReg;
79396     pParse->nRangeReg -= nReg;
79397   }else{
79398     i = pParse->nMem+1;
79399     pParse->nMem += nReg;
79400   }
79401   return i;
79402 }
79403 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
79404   sqlite3ExprCacheRemove(pParse, iReg, nReg);
79405   if( nReg>pParse->nRangeReg ){
79406     pParse->nRangeReg = nReg;
79407     pParse->iRangeReg = iReg;
79408   }
79409 }
79410
79411 /*
79412 ** Mark all temporary registers as being unavailable for reuse.
79413 */
79414 SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
79415   pParse->nTempReg = 0;
79416   pParse->nRangeReg = 0;
79417 }
79418
79419 /************** End of expr.c ************************************************/
79420 /************** Begin file alter.c *******************************************/
79421 /*
79422 ** 2005 February 15
79423 **
79424 ** The author disclaims copyright to this source code.  In place of
79425 ** a legal notice, here is a blessing:
79426 **
79427 **    May you do good and not evil.
79428 **    May you find forgiveness for yourself and forgive others.
79429 **    May you share freely, never taking more than you give.
79430 **
79431 *************************************************************************
79432 ** This file contains C code routines that used to generate VDBE code
79433 ** that implements the ALTER TABLE command.
79434 */
79435
79436 /*
79437 ** The code in this file only exists if we are not omitting the
79438 ** ALTER TABLE logic from the build.
79439 */
79440 #ifndef SQLITE_OMIT_ALTERTABLE
79441
79442
79443 /*
79444 ** This function is used by SQL generated to implement the 
79445 ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
79446 ** CREATE INDEX command. The second is a table name. The table name in 
79447 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
79448 ** argument and the result returned. Examples:
79449 **
79450 ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
79451 **     -> 'CREATE TABLE def(a, b, c)'
79452 **
79453 ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
79454 **     -> 'CREATE INDEX i ON def(a, b, c)'
79455 */
79456 static void renameTableFunc(
79457   sqlite3_context *context,
79458   int NotUsed,
79459   sqlite3_value **argv
79460 ){
79461   unsigned char const *zSql = sqlite3_value_text(argv[0]);
79462   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
79463
79464   int token;
79465   Token tname;
79466   unsigned char const *zCsr = zSql;
79467   int len = 0;
79468   char *zRet;
79469
79470   sqlite3 *db = sqlite3_context_db_handle(context);
79471
79472   UNUSED_PARAMETER(NotUsed);
79473
79474   /* The principle used to locate the table name in the CREATE TABLE 
79475   ** statement is that the table name is the first non-space token that
79476   ** is immediately followed by a TK_LP or TK_USING token.
79477   */
79478   if( zSql ){
79479     do {
79480       if( !*zCsr ){
79481         /* Ran out of input before finding an opening bracket. Return NULL. */
79482         return;
79483       }
79484
79485       /* Store the token that zCsr points to in tname. */
79486       tname.z = (char*)zCsr;
79487       tname.n = len;
79488
79489       /* Advance zCsr to the next token. Store that token type in 'token',
79490       ** and its length in 'len' (to be used next iteration of this loop).
79491       */
79492       do {
79493         zCsr += len;
79494         len = sqlite3GetToken(zCsr, &token);
79495       } while( token==TK_SPACE );
79496       assert( len>0 );
79497     } while( token!=TK_LP && token!=TK_USING );
79498
79499     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql, 
79500        zTableName, tname.z+tname.n);
79501     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
79502   }
79503 }
79504
79505 /*
79506 ** This C function implements an SQL user function that is used by SQL code
79507 ** generated by the ALTER TABLE ... RENAME command to modify the definition
79508 ** of any foreign key constraints that use the table being renamed as the 
79509 ** parent table. It is passed three arguments:
79510 **
79511 **   1) The complete text of the CREATE TABLE statement being modified,
79512 **   2) The old name of the table being renamed, and
79513 **   3) The new name of the table being renamed.
79514 **
79515 ** It returns the new CREATE TABLE statement. For example:
79516 **
79517 **   sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
79518 **       -> 'CREATE TABLE t1(a REFERENCES t3)'
79519 */
79520 #ifndef SQLITE_OMIT_FOREIGN_KEY
79521 static void renameParentFunc(
79522   sqlite3_context *context,
79523   int NotUsed,
79524   sqlite3_value **argv
79525 ){
79526   sqlite3 *db = sqlite3_context_db_handle(context);
79527   char *zOutput = 0;
79528   char *zResult;
79529   unsigned char const *zInput = sqlite3_value_text(argv[0]);
79530   unsigned char const *zOld = sqlite3_value_text(argv[1]);
79531   unsigned char const *zNew = sqlite3_value_text(argv[2]);
79532
79533   unsigned const char *z;         /* Pointer to token */
79534   int n;                          /* Length of token z */
79535   int token;                      /* Type of token */
79536
79537   UNUSED_PARAMETER(NotUsed);
79538   for(z=zInput; *z; z=z+n){
79539     n = sqlite3GetToken(z, &token);
79540     if( token==TK_REFERENCES ){
79541       char *zParent;
79542       do {
79543         z += n;
79544         n = sqlite3GetToken(z, &token);
79545       }while( token==TK_SPACE );
79546
79547       zParent = sqlite3DbStrNDup(db, (const char *)z, n);
79548       if( zParent==0 ) break;
79549       sqlite3Dequote(zParent);
79550       if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
79551         char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"", 
79552             (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew
79553         );
79554         sqlite3DbFree(db, zOutput);
79555         zOutput = zOut;
79556         zInput = &z[n];
79557       }
79558       sqlite3DbFree(db, zParent);
79559     }
79560   }
79561
79562   zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput), 
79563   sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
79564   sqlite3DbFree(db, zOutput);
79565 }
79566 #endif
79567
79568 #ifndef SQLITE_OMIT_TRIGGER
79569 /* This function is used by SQL generated to implement the
79570 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER 
79571 ** statement. The second is a table name. The table name in the CREATE 
79572 ** TRIGGER statement is replaced with the third argument and the result 
79573 ** returned. This is analagous to renameTableFunc() above, except for CREATE
79574 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
79575 */
79576 static void renameTriggerFunc(
79577   sqlite3_context *context,
79578   int NotUsed,
79579   sqlite3_value **argv
79580 ){
79581   unsigned char const *zSql = sqlite3_value_text(argv[0]);
79582   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
79583
79584   int token;
79585   Token tname;
79586   int dist = 3;
79587   unsigned char const *zCsr = zSql;
79588   int len = 0;
79589   char *zRet;
79590   sqlite3 *db = sqlite3_context_db_handle(context);
79591
79592   UNUSED_PARAMETER(NotUsed);
79593
79594   /* The principle used to locate the table name in the CREATE TRIGGER 
79595   ** statement is that the table name is the first token that is immediatedly
79596   ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
79597   ** of TK_WHEN, TK_BEGIN or TK_FOR.
79598   */
79599   if( zSql ){
79600     do {
79601
79602       if( !*zCsr ){
79603         /* Ran out of input before finding the table name. Return NULL. */
79604         return;
79605       }
79606
79607       /* Store the token that zCsr points to in tname. */
79608       tname.z = (char*)zCsr;
79609       tname.n = len;
79610
79611       /* Advance zCsr to the next token. Store that token type in 'token',
79612       ** and its length in 'len' (to be used next iteration of this loop).
79613       */
79614       do {
79615         zCsr += len;
79616         len = sqlite3GetToken(zCsr, &token);
79617       }while( token==TK_SPACE );
79618       assert( len>0 );
79619
79620       /* Variable 'dist' stores the number of tokens read since the most
79621       ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN 
79622       ** token is read and 'dist' equals 2, the condition stated above
79623       ** to be met.
79624       **
79625       ** Note that ON cannot be a database, table or column name, so
79626       ** there is no need to worry about syntax like 
79627       ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
79628       */
79629       dist++;
79630       if( token==TK_DOT || token==TK_ON ){
79631         dist = 0;
79632       }
79633     } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
79634
79635     /* Variable tname now contains the token that is the old table-name
79636     ** in the CREATE TRIGGER statement.
79637     */
79638     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql, 
79639        zTableName, tname.z+tname.n);
79640     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
79641   }
79642 }
79643 #endif   /* !SQLITE_OMIT_TRIGGER */
79644
79645 /*
79646 ** Register built-in functions used to help implement ALTER TABLE
79647 */
79648 SQLITE_PRIVATE void sqlite3AlterFunctions(void){
79649   static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
79650     FUNCTION(sqlite_rename_table,   2, 0, 0, renameTableFunc),
79651 #ifndef SQLITE_OMIT_TRIGGER
79652     FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
79653 #endif
79654 #ifndef SQLITE_OMIT_FOREIGN_KEY
79655     FUNCTION(sqlite_rename_parent,  3, 0, 0, renameParentFunc),
79656 #endif
79657   };
79658   int i;
79659   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
79660   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
79661
79662   for(i=0; i<ArraySize(aAlterTableFuncs); i++){
79663     sqlite3FuncDefInsert(pHash, &aFunc[i]);
79664   }
79665 }
79666
79667 /*
79668 ** This function is used to create the text of expressions of the form:
79669 **
79670 **   name=<constant1> OR name=<constant2> OR ...
79671 **
79672 ** If argument zWhere is NULL, then a pointer string containing the text 
79673 ** "name=<constant>" is returned, where <constant> is the quoted version
79674 ** of the string passed as argument zConstant. The returned buffer is
79675 ** allocated using sqlite3DbMalloc(). It is the responsibility of the
79676 ** caller to ensure that it is eventually freed.
79677 **
79678 ** If argument zWhere is not NULL, then the string returned is 
79679 ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
79680 ** In this case zWhere is passed to sqlite3DbFree() before returning.
79681 ** 
79682 */
79683 static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
79684   char *zNew;
79685   if( !zWhere ){
79686     zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
79687   }else{
79688     zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
79689     sqlite3DbFree(db, zWhere);
79690   }
79691   return zNew;
79692 }
79693
79694 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
79695 /*
79696 ** Generate the text of a WHERE expression which can be used to select all
79697 ** tables that have foreign key constraints that refer to table pTab (i.e.
79698 ** constraints for which pTab is the parent table) from the sqlite_master
79699 ** table.
79700 */
79701 static char *whereForeignKeys(Parse *pParse, Table *pTab){
79702   FKey *p;
79703   char *zWhere = 0;
79704   for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
79705     zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
79706   }
79707   return zWhere;
79708 }
79709 #endif
79710
79711 /*
79712 ** Generate the text of a WHERE expression which can be used to select all
79713 ** temporary triggers on table pTab from the sqlite_temp_master table. If
79714 ** table pTab has no temporary triggers, or is itself stored in the 
79715 ** temporary database, NULL is returned.
79716 */
79717 static char *whereTempTriggers(Parse *pParse, Table *pTab){
79718   Trigger *pTrig;
79719   char *zWhere = 0;
79720   const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
79721
79722   /* If the table is not located in the temp-db (in which case NULL is 
79723   ** returned, loop through the tables list of triggers. For each trigger
79724   ** that is not part of the temp-db schema, add a clause to the WHERE 
79725   ** expression being built up in zWhere.
79726   */
79727   if( pTab->pSchema!=pTempSchema ){
79728     sqlite3 *db = pParse->db;
79729     for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
79730       if( pTrig->pSchema==pTempSchema ){
79731         zWhere = whereOrName(db, zWhere, pTrig->zName);
79732       }
79733     }
79734   }
79735   if( zWhere ){
79736     char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
79737     sqlite3DbFree(pParse->db, zWhere);
79738     zWhere = zNew;
79739   }
79740   return zWhere;
79741 }
79742
79743 /*
79744 ** Generate code to drop and reload the internal representation of table
79745 ** pTab from the database, including triggers and temporary triggers.
79746 ** Argument zName is the name of the table in the database schema at
79747 ** the time the generated code is executed. This can be different from
79748 ** pTab->zName if this function is being called to code part of an 
79749 ** "ALTER TABLE RENAME TO" statement.
79750 */
79751 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
79752   Vdbe *v;
79753   char *zWhere;
79754   int iDb;                   /* Index of database containing pTab */
79755 #ifndef SQLITE_OMIT_TRIGGER
79756   Trigger *pTrig;
79757 #endif
79758
79759   v = sqlite3GetVdbe(pParse);
79760   if( NEVER(v==0) ) return;
79761   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
79762   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
79763   assert( iDb>=0 );
79764
79765 #ifndef SQLITE_OMIT_TRIGGER
79766   /* Drop any table triggers from the internal schema. */
79767   for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
79768     int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
79769     assert( iTrigDb==iDb || iTrigDb==1 );
79770     sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
79771   }
79772 #endif
79773
79774   /* Drop the table and index from the internal schema.  */
79775   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
79776
79777   /* Reload the table, index and permanent trigger schemas. */
79778   zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
79779   if( !zWhere ) return;
79780   sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
79781
79782 #ifndef SQLITE_OMIT_TRIGGER
79783   /* Now, if the table is not stored in the temp database, reload any temp 
79784   ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined. 
79785   */
79786   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
79787     sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
79788   }
79789 #endif
79790 }
79791
79792 /*
79793 ** Parameter zName is the name of a table that is about to be altered
79794 ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
79795 ** If the table is a system table, this function leaves an error message
79796 ** in pParse->zErr (system tables may not be altered) and returns non-zero.
79797 **
79798 ** Or, if zName is not a system table, zero is returned.
79799 */
79800 static int isSystemTable(Parse *pParse, const char *zName){
79801   if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
79802     sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
79803     return 1;
79804   }
79805   return 0;
79806 }
79807
79808 /*
79809 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy" 
79810 ** command. 
79811 */
79812 SQLITE_PRIVATE void sqlite3AlterRenameTable(
79813   Parse *pParse,            /* Parser context. */
79814   SrcList *pSrc,            /* The table to rename. */
79815   Token *pName              /* The new table name. */
79816 ){
79817   int iDb;                  /* Database that contains the table */
79818   char *zDb;                /* Name of database iDb */
79819   Table *pTab;              /* Table being renamed */
79820   char *zName = 0;          /* NULL-terminated version of pName */ 
79821   sqlite3 *db = pParse->db; /* Database connection */
79822   int nTabName;             /* Number of UTF-8 characters in zTabName */
79823   const char *zTabName;     /* Original name of the table */
79824   Vdbe *v;
79825 #ifndef SQLITE_OMIT_TRIGGER
79826   char *zWhere = 0;         /* Where clause to locate temp triggers */
79827 #endif
79828   VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
79829   int savedDbFlags;         /* Saved value of db->flags */
79830
79831   savedDbFlags = db->flags;  
79832   if( NEVER(db->mallocFailed) ) goto exit_rename_table;
79833   assert( pSrc->nSrc==1 );
79834   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
79835
79836   pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
79837   if( !pTab ) goto exit_rename_table;
79838   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
79839   zDb = db->aDb[iDb].zName;
79840   db->flags |= SQLITE_PreferBuiltin;
79841
79842   /* Get a NULL terminated version of the new table name. */
79843   zName = sqlite3NameFromToken(db, pName);
79844   if( !zName ) goto exit_rename_table;
79845
79846   /* Check that a table or index named 'zName' does not already exist
79847   ** in database iDb. If so, this is an error.
79848   */
79849   if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
79850     sqlite3ErrorMsg(pParse, 
79851         "there is already another table or index with this name: %s", zName);
79852     goto exit_rename_table;
79853   }
79854
79855   /* Make sure it is not a system table being altered, or a reserved name
79856   ** that the table is being renamed to.
79857   */
79858   if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
79859     goto exit_rename_table;
79860   }
79861   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
79862     exit_rename_table;
79863   }
79864
79865 #ifndef SQLITE_OMIT_VIEW
79866   if( pTab->pSelect ){
79867     sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
79868     goto exit_rename_table;
79869   }
79870 #endif
79871
79872 #ifndef SQLITE_OMIT_AUTHORIZATION
79873   /* Invoke the authorization callback. */
79874   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
79875     goto exit_rename_table;
79876   }
79877 #endif
79878
79879 #ifndef SQLITE_OMIT_VIRTUALTABLE
79880   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
79881     goto exit_rename_table;
79882   }
79883   if( IsVirtual(pTab) ){
79884     pVTab = sqlite3GetVTable(db, pTab);
79885     if( pVTab->pVtab->pModule->xRename==0 ){
79886       pVTab = 0;
79887     }
79888   }
79889 #endif
79890
79891   /* Begin a transaction and code the VerifyCookie for database iDb. 
79892   ** Then modify the schema cookie (since the ALTER TABLE modifies the
79893   ** schema). Open a statement transaction if the table is a virtual
79894   ** table.
79895   */
79896   v = sqlite3GetVdbe(pParse);
79897   if( v==0 ){
79898     goto exit_rename_table;
79899   }
79900   sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
79901   sqlite3ChangeCookie(pParse, iDb);
79902
79903   /* If this is a virtual table, invoke the xRename() function if
79904   ** one is defined. The xRename() callback will modify the names
79905   ** of any resources used by the v-table implementation (including other
79906   ** SQLite tables) that are identified by the name of the virtual table.
79907   */
79908 #ifndef SQLITE_OMIT_VIRTUALTABLE
79909   if( pVTab ){
79910     int i = ++pParse->nMem;
79911     sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
79912     sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
79913     sqlite3MayAbort(pParse);
79914   }
79915 #endif
79916
79917   /* figure out how many UTF-8 characters are in zName */
79918   zTabName = pTab->zName;
79919   nTabName = sqlite3Utf8CharLen(zTabName, -1);
79920
79921 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
79922   if( db->flags&SQLITE_ForeignKeys ){
79923     /* If foreign-key support is enabled, rewrite the CREATE TABLE 
79924     ** statements corresponding to all child tables of foreign key constraints
79925     ** for which the renamed table is the parent table.  */
79926     if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
79927       sqlite3NestedParse(pParse, 
79928           "UPDATE \"%w\".%s SET "
79929               "sql = sqlite_rename_parent(sql, %Q, %Q) "
79930               "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
79931       sqlite3DbFree(db, zWhere);
79932     }
79933   }
79934 #endif
79935
79936   /* Modify the sqlite_master table to use the new table name. */
79937   sqlite3NestedParse(pParse,
79938       "UPDATE %Q.%s SET "
79939 #ifdef SQLITE_OMIT_TRIGGER
79940           "sql = sqlite_rename_table(sql, %Q), "
79941 #else
79942           "sql = CASE "
79943             "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
79944             "ELSE sqlite_rename_table(sql, %Q) END, "
79945 #endif
79946           "tbl_name = %Q, "
79947           "name = CASE "
79948             "WHEN type='table' THEN %Q "
79949             "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
79950              "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
79951             "ELSE name END "
79952       "WHERE tbl_name=%Q COLLATE nocase AND "
79953           "(type='table' OR type='index' OR type='trigger');", 
79954       zDb, SCHEMA_TABLE(iDb), zName, zName, zName, 
79955 #ifndef SQLITE_OMIT_TRIGGER
79956       zName,
79957 #endif
79958       zName, nTabName, zTabName
79959   );
79960
79961 #ifndef SQLITE_OMIT_AUTOINCREMENT
79962   /* If the sqlite_sequence table exists in this database, then update 
79963   ** it with the new table name.
79964   */
79965   if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
79966     sqlite3NestedParse(pParse,
79967         "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
79968         zDb, zName, pTab->zName);
79969   }
79970 #endif
79971
79972 #ifndef SQLITE_OMIT_TRIGGER
79973   /* If there are TEMP triggers on this table, modify the sqlite_temp_master
79974   ** table. Don't do this if the table being ALTERed is itself located in
79975   ** the temp database.
79976   */
79977   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
79978     sqlite3NestedParse(pParse, 
79979         "UPDATE sqlite_temp_master SET "
79980             "sql = sqlite_rename_trigger(sql, %Q), "
79981             "tbl_name = %Q "
79982             "WHERE %s;", zName, zName, zWhere);
79983     sqlite3DbFree(db, zWhere);
79984   }
79985 #endif
79986
79987 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
79988   if( db->flags&SQLITE_ForeignKeys ){
79989     FKey *p;
79990     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
79991       Table *pFrom = p->pFrom;
79992       if( pFrom!=pTab ){
79993         reloadTableSchema(pParse, p->pFrom, pFrom->zName);
79994       }
79995     }
79996   }
79997 #endif
79998
79999   /* Drop and reload the internal table schema. */
80000   reloadTableSchema(pParse, pTab, zName);
80001
80002 exit_rename_table:
80003   sqlite3SrcListDelete(db, pSrc);
80004   sqlite3DbFree(db, zName);
80005   db->flags = savedDbFlags;
80006 }
80007
80008
80009 /*
80010 ** Generate code to make sure the file format number is at least minFormat.
80011 ** The generated code will increase the file format number if necessary.
80012 */
80013 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
80014   Vdbe *v;
80015   v = sqlite3GetVdbe(pParse);
80016   /* The VDBE should have been allocated before this routine is called.
80017   ** If that allocation failed, we would have quit before reaching this
80018   ** point */
80019   if( ALWAYS(v) ){
80020     int r1 = sqlite3GetTempReg(pParse);
80021     int r2 = sqlite3GetTempReg(pParse);
80022     int j1;
80023     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
80024     sqlite3VdbeUsesBtree(v, iDb);
80025     sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
80026     j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
80027     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
80028     sqlite3VdbeJumpHere(v, j1);
80029     sqlite3ReleaseTempReg(pParse, r1);
80030     sqlite3ReleaseTempReg(pParse, r2);
80031   }
80032 }
80033
80034 /*
80035 ** This function is called after an "ALTER TABLE ... ADD" statement
80036 ** has been parsed. Argument pColDef contains the text of the new
80037 ** column definition.
80038 **
80039 ** The Table structure pParse->pNewTable was extended to include
80040 ** the new column during parsing.
80041 */
80042 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
80043   Table *pNew;              /* Copy of pParse->pNewTable */
80044   Table *pTab;              /* Table being altered */
80045   int iDb;                  /* Database number */
80046   const char *zDb;          /* Database name */
80047   const char *zTab;         /* Table name */
80048   char *zCol;               /* Null-terminated column definition */
80049   Column *pCol;             /* The new column */
80050   Expr *pDflt;              /* Default value for the new column */
80051   sqlite3 *db;              /* The database connection; */
80052
80053   db = pParse->db;
80054   if( pParse->nErr || db->mallocFailed ) return;
80055   pNew = pParse->pNewTable;
80056   assert( pNew );
80057
80058   assert( sqlite3BtreeHoldsAllMutexes(db) );
80059   iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
80060   zDb = db->aDb[iDb].zName;
80061   zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
80062   pCol = &pNew->aCol[pNew->nCol-1];
80063   pDflt = pCol->pDflt;
80064   pTab = sqlite3FindTable(db, zTab, zDb);
80065   assert( pTab );
80066
80067 #ifndef SQLITE_OMIT_AUTHORIZATION
80068   /* Invoke the authorization callback. */
80069   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
80070     return;
80071   }
80072 #endif
80073
80074   /* If the default value for the new column was specified with a 
80075   ** literal NULL, then set pDflt to 0. This simplifies checking
80076   ** for an SQL NULL default below.
80077   */
80078   if( pDflt && pDflt->op==TK_NULL ){
80079     pDflt = 0;
80080   }
80081
80082   /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
80083   ** If there is a NOT NULL constraint, then the default value for the
80084   ** column must not be NULL.
80085   */
80086   if( pCol->colFlags & COLFLAG_PRIMKEY ){
80087     sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
80088     return;
80089   }
80090   if( pNew->pIndex ){
80091     sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
80092     return;
80093   }
80094   if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
80095     sqlite3ErrorMsg(pParse, 
80096         "Cannot add a REFERENCES column with non-NULL default value");
80097     return;
80098   }
80099   if( pCol->notNull && !pDflt ){
80100     sqlite3ErrorMsg(pParse, 
80101         "Cannot add a NOT NULL column with default value NULL");
80102     return;
80103   }
80104
80105   /* Ensure the default expression is something that sqlite3ValueFromExpr()
80106   ** can handle (i.e. not CURRENT_TIME etc.)
80107   */
80108   if( pDflt ){
80109     sqlite3_value *pVal;
80110     if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
80111       db->mallocFailed = 1;
80112       return;
80113     }
80114     if( !pVal ){
80115       sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
80116       return;
80117     }
80118     sqlite3ValueFree(pVal);
80119   }
80120
80121   /* Modify the CREATE TABLE statement. */
80122   zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
80123   if( zCol ){
80124     char *zEnd = &zCol[pColDef->n-1];
80125     int savedDbFlags = db->flags;
80126     while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
80127       *zEnd-- = '\0';
80128     }
80129     db->flags |= SQLITE_PreferBuiltin;
80130     sqlite3NestedParse(pParse, 
80131         "UPDATE \"%w\".%s SET "
80132           "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
80133         "WHERE type = 'table' AND name = %Q", 
80134       zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
80135       zTab
80136     );
80137     sqlite3DbFree(db, zCol);
80138     db->flags = savedDbFlags;
80139   }
80140
80141   /* If the default value of the new column is NULL, then set the file
80142   ** format to 2. If the default value of the new column is not NULL,
80143   ** the file format becomes 3.
80144   */
80145   sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
80146
80147   /* Reload the schema of the modified table. */
80148   reloadTableSchema(pParse, pTab, pTab->zName);
80149 }
80150
80151 /*
80152 ** This function is called by the parser after the table-name in
80153 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument 
80154 ** pSrc is the full-name of the table being altered.
80155 **
80156 ** This routine makes a (partial) copy of the Table structure
80157 ** for the table being altered and sets Parse.pNewTable to point
80158 ** to it. Routines called by the parser as the column definition
80159 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to 
80160 ** the copy. The copy of the Table structure is deleted by tokenize.c 
80161 ** after parsing is finished.
80162 **
80163 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
80164 ** coding the "ALTER TABLE ... ADD" statement.
80165 */
80166 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
80167   Table *pNew;
80168   Table *pTab;
80169   Vdbe *v;
80170   int iDb;
80171   int i;
80172   int nAlloc;
80173   sqlite3 *db = pParse->db;
80174
80175   /* Look up the table being altered. */
80176   assert( pParse->pNewTable==0 );
80177   assert( sqlite3BtreeHoldsAllMutexes(db) );
80178   if( db->mallocFailed ) goto exit_begin_add_column;
80179   pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
80180   if( !pTab ) goto exit_begin_add_column;
80181
80182 #ifndef SQLITE_OMIT_VIRTUALTABLE
80183   if( IsVirtual(pTab) ){
80184     sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
80185     goto exit_begin_add_column;
80186   }
80187 #endif
80188
80189   /* Make sure this is not an attempt to ALTER a view. */
80190   if( pTab->pSelect ){
80191     sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
80192     goto exit_begin_add_column;
80193   }
80194   if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
80195     goto exit_begin_add_column;
80196   }
80197
80198   assert( pTab->addColOffset>0 );
80199   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
80200
80201   /* Put a copy of the Table struct in Parse.pNewTable for the
80202   ** sqlite3AddColumn() function and friends to modify.  But modify
80203   ** the name by adding an "sqlite_altertab_" prefix.  By adding this
80204   ** prefix, we insure that the name will not collide with an existing
80205   ** table because user table are not allowed to have the "sqlite_"
80206   ** prefix on their name.
80207   */
80208   pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
80209   if( !pNew ) goto exit_begin_add_column;
80210   pParse->pNewTable = pNew;
80211   pNew->nRef = 1;
80212   pNew->nCol = pTab->nCol;
80213   assert( pNew->nCol>0 );
80214   nAlloc = (((pNew->nCol-1)/8)*8)+8;
80215   assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
80216   pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
80217   pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
80218   if( !pNew->aCol || !pNew->zName ){
80219     db->mallocFailed = 1;
80220     goto exit_begin_add_column;
80221   }
80222   memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
80223   for(i=0; i<pNew->nCol; i++){
80224     Column *pCol = &pNew->aCol[i];
80225     pCol->zName = sqlite3DbStrDup(db, pCol->zName);
80226     pCol->zColl = 0;
80227     pCol->zType = 0;
80228     pCol->pDflt = 0;
80229     pCol->zDflt = 0;
80230   }
80231   pNew->pSchema = db->aDb[iDb].pSchema;
80232   pNew->addColOffset = pTab->addColOffset;
80233   pNew->nRef = 1;
80234
80235   /* Begin a transaction and increment the schema cookie.  */
80236   sqlite3BeginWriteOperation(pParse, 0, iDb);
80237   v = sqlite3GetVdbe(pParse);
80238   if( !v ) goto exit_begin_add_column;
80239   sqlite3ChangeCookie(pParse, iDb);
80240
80241 exit_begin_add_column:
80242   sqlite3SrcListDelete(db, pSrc);
80243   return;
80244 }
80245 #endif  /* SQLITE_ALTER_TABLE */
80246
80247 /************** End of alter.c ***********************************************/
80248 /************** Begin file analyze.c *****************************************/
80249 /*
80250 ** 2005 July 8
80251 **
80252 ** The author disclaims copyright to this source code.  In place of
80253 ** a legal notice, here is a blessing:
80254 **
80255 **    May you do good and not evil.
80256 **    May you find forgiveness for yourself and forgive others.
80257 **    May you share freely, never taking more than you give.
80258 **
80259 *************************************************************************
80260 ** This file contains code associated with the ANALYZE command.
80261 **
80262 ** The ANALYZE command gather statistics about the content of tables
80263 ** and indices.  These statistics are made available to the query planner
80264 ** to help it make better decisions about how to perform queries.
80265 **
80266 ** The following system tables are or have been supported:
80267 **
80268 **    CREATE TABLE sqlite_stat1(tbl, idx, stat);
80269 **    CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
80270 **    CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
80271 **
80272 ** Additional tables might be added in future releases of SQLite.
80273 ** The sqlite_stat2 table is not created or used unless the SQLite version
80274 ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
80275 ** with SQLITE_ENABLE_STAT2.  The sqlite_stat2 table is deprecated.
80276 ** The sqlite_stat2 table is superceded by sqlite_stat3, which is only
80277 ** created and used by SQLite versions 3.7.9 and later and with
80278 ** SQLITE_ENABLE_STAT3 defined.  The fucntionality of sqlite_stat3
80279 ** is a superset of sqlite_stat2.  
80280 **
80281 ** Format of sqlite_stat1:
80282 **
80283 ** There is normally one row per index, with the index identified by the
80284 ** name in the idx column.  The tbl column is the name of the table to
80285 ** which the index belongs.  In each such row, the stat column will be
80286 ** a string consisting of a list of integers.  The first integer in this
80287 ** list is the number of rows in the index and in the table.  The second
80288 ** integer is the average number of rows in the index that have the same
80289 ** value in the first column of the index.  The third integer is the average
80290 ** number of rows in the index that have the same value for the first two
80291 ** columns.  The N-th integer (for N>1) is the average number of rows in 
80292 ** the index which have the same value for the first N-1 columns.  For
80293 ** a K-column index, there will be K+1 integers in the stat column.  If
80294 ** the index is unique, then the last integer will be 1.
80295 **
80296 ** The list of integers in the stat column can optionally be followed
80297 ** by the keyword "unordered".  The "unordered" keyword, if it is present,
80298 ** must be separated from the last integer by a single space.  If the
80299 ** "unordered" keyword is present, then the query planner assumes that
80300 ** the index is unordered and will not use the index for a range query.
80301 ** 
80302 ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
80303 ** column contains a single integer which is the (estimated) number of
80304 ** rows in the table identified by sqlite_stat1.tbl.
80305 **
80306 ** Format of sqlite_stat2:
80307 **
80308 ** The sqlite_stat2 is only created and is only used if SQLite is compiled
80309 ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
80310 ** 3.6.18 and 3.7.8.  The "stat2" table contains additional information
80311 ** about the distribution of keys within an index.  The index is identified by
80312 ** the "idx" column and the "tbl" column is the name of the table to which
80313 ** the index belongs.  There are usually 10 rows in the sqlite_stat2
80314 ** table for each index.
80315 **
80316 ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
80317 ** inclusive are samples of the left-most key value in the index taken at
80318 ** evenly spaced points along the index.  Let the number of samples be S
80319 ** (10 in the standard build) and let C be the number of rows in the index.
80320 ** Then the sampled rows are given by:
80321 **
80322 **     rownumber = (i*C*2 + C)/(S*2)
80323 **
80324 ** For i between 0 and S-1.  Conceptually, the index space is divided into
80325 ** S uniform buckets and the samples are the middle row from each bucket.
80326 **
80327 ** The format for sqlite_stat2 is recorded here for legacy reference.  This
80328 ** version of SQLite does not support sqlite_stat2.  It neither reads nor
80329 ** writes the sqlite_stat2 table.  This version of SQLite only supports
80330 ** sqlite_stat3.
80331 **
80332 ** Format for sqlite_stat3:
80333 **
80334 ** The sqlite_stat3 is an enhancement to sqlite_stat2.  A new name is
80335 ** used to avoid compatibility problems.  
80336 **
80337 ** The format of the sqlite_stat3 table is similar to the format of
80338 ** the sqlite_stat2 table.  There are multiple entries for each index.
80339 ** The idx column names the index and the tbl column is the table of the
80340 ** index.  If the idx and tbl columns are the same, then the sample is
80341 ** of the INTEGER PRIMARY KEY.  The sample column is a value taken from
80342 ** the left-most column of the index.  The nEq column is the approximate
80343 ** number of entires in the index whose left-most column exactly matches
80344 ** the sample.  nLt is the approximate number of entires whose left-most
80345 ** column is less than the sample.  The nDLt column is the approximate
80346 ** number of distinct left-most entries in the index that are less than
80347 ** the sample.
80348 **
80349 ** Future versions of SQLite might change to store a string containing
80350 ** multiple integers values in the nDLt column of sqlite_stat3.  The first
80351 ** integer will be the number of prior index entires that are distinct in
80352 ** the left-most column.  The second integer will be the number of prior index
80353 ** entries that are distinct in the first two columns.  The third integer
80354 ** will be the number of prior index entries that are distinct in the first
80355 ** three columns.  And so forth.  With that extension, the nDLt field is
80356 ** similar in function to the sqlite_stat1.stat field.
80357 **
80358 ** There can be an arbitrary number of sqlite_stat3 entries per index.
80359 ** The ANALYZE command will typically generate sqlite_stat3 tables
80360 ** that contain between 10 and 40 samples which are distributed across
80361 ** the key space, though not uniformly, and which include samples with
80362 ** largest possible nEq values.
80363 */
80364 #ifndef SQLITE_OMIT_ANALYZE
80365
80366 /*
80367 ** This routine generates code that opens the sqlite_stat1 table for
80368 ** writing with cursor iStatCur. If the library was built with the
80369 ** SQLITE_ENABLE_STAT3 macro defined, then the sqlite_stat3 table is
80370 ** opened for writing using cursor (iStatCur+1)
80371 **
80372 ** If the sqlite_stat1 tables does not previously exist, it is created.
80373 ** Similarly, if the sqlite_stat3 table does not exist and the library
80374 ** is compiled with SQLITE_ENABLE_STAT3 defined, it is created. 
80375 **
80376 ** Argument zWhere may be a pointer to a buffer containing a table name,
80377 ** or it may be a NULL pointer. If it is not NULL, then all entries in
80378 ** the sqlite_stat1 and (if applicable) sqlite_stat3 tables associated
80379 ** with the named table are deleted. If zWhere==0, then code is generated
80380 ** to delete all stat table entries.
80381 */
80382 static void openStatTable(
80383   Parse *pParse,          /* Parsing context */
80384   int iDb,                /* The database we are looking in */
80385   int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
80386   const char *zWhere,     /* Delete entries for this table or index */
80387   const char *zWhereType  /* Either "tbl" or "idx" */
80388 ){
80389   static const struct {
80390     const char *zName;
80391     const char *zCols;
80392   } aTable[] = {
80393     { "sqlite_stat1", "tbl,idx,stat" },
80394 #ifdef SQLITE_ENABLE_STAT3
80395     { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
80396 #endif
80397   };
80398
80399   int aRoot[] = {0, 0};
80400   u8 aCreateTbl[] = {0, 0};
80401
80402   int i;
80403   sqlite3 *db = pParse->db;
80404   Db *pDb;
80405   Vdbe *v = sqlite3GetVdbe(pParse);
80406   if( v==0 ) return;
80407   assert( sqlite3BtreeHoldsAllMutexes(db) );
80408   assert( sqlite3VdbeDb(v)==db );
80409   pDb = &db->aDb[iDb];
80410
80411   /* Create new statistic tables if they do not exist, or clear them
80412   ** if they do already exist.
80413   */
80414   for(i=0; i<ArraySize(aTable); i++){
80415     const char *zTab = aTable[i].zName;
80416     Table *pStat;
80417     if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
80418       /* The sqlite_stat[12] table does not exist. Create it. Note that a 
80419       ** side-effect of the CREATE TABLE statement is to leave the rootpage 
80420       ** of the new table in register pParse->regRoot. This is important 
80421       ** because the OpenWrite opcode below will be needing it. */
80422       sqlite3NestedParse(pParse,
80423           "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
80424       );
80425       aRoot[i] = pParse->regRoot;
80426       aCreateTbl[i] = OPFLAG_P2ISREG;
80427     }else{
80428       /* The table already exists. If zWhere is not NULL, delete all entries 
80429       ** associated with the table zWhere. If zWhere is NULL, delete the
80430       ** entire contents of the table. */
80431       aRoot[i] = pStat->tnum;
80432       sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
80433       if( zWhere ){
80434         sqlite3NestedParse(pParse,
80435            "DELETE FROM %Q.%s WHERE %s=%Q", pDb->zName, zTab, zWhereType, zWhere
80436         );
80437       }else{
80438         /* The sqlite_stat[12] table already exists.  Delete all rows. */
80439         sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
80440       }
80441     }
80442   }
80443
80444   /* Open the sqlite_stat[13] tables for writing. */
80445   for(i=0; i<ArraySize(aTable); i++){
80446     sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb);
80447     sqlite3VdbeChangeP4(v, -1, (char *)3, P4_INT32);
80448     sqlite3VdbeChangeP5(v, aCreateTbl[i]);
80449   }
80450 }
80451
80452 /*
80453 ** Recommended number of samples for sqlite_stat3
80454 */
80455 #ifndef SQLITE_STAT3_SAMPLES
80456 # define SQLITE_STAT3_SAMPLES 24
80457 #endif
80458
80459 /*
80460 ** Three SQL functions - stat3_init(), stat3_push(), and stat3_pop() -
80461 ** share an instance of the following structure to hold their state
80462 ** information.
80463 */
80464 typedef struct Stat3Accum Stat3Accum;
80465 struct Stat3Accum {
80466   tRowcnt nRow;             /* Number of rows in the entire table */
80467   tRowcnt nPSample;         /* How often to do a periodic sample */
80468   int iMin;                 /* Index of entry with minimum nEq and hash */
80469   int mxSample;             /* Maximum number of samples to accumulate */
80470   int nSample;              /* Current number of samples */
80471   u32 iPrn;                 /* Pseudo-random number used for sampling */
80472   struct Stat3Sample {
80473     i64 iRowid;                /* Rowid in main table of the key */
80474     tRowcnt nEq;               /* sqlite_stat3.nEq */
80475     tRowcnt nLt;               /* sqlite_stat3.nLt */
80476     tRowcnt nDLt;              /* sqlite_stat3.nDLt */
80477     u8 isPSample;              /* True if a periodic sample */
80478     u32 iHash;                 /* Tiebreaker hash */
80479   } *a;                     /* An array of samples */
80480 };
80481
80482 #ifdef SQLITE_ENABLE_STAT3
80483 /*
80484 ** Implementation of the stat3_init(C,S) SQL function.  The two parameters
80485 ** are the number of rows in the table or index (C) and the number of samples
80486 ** to accumulate (S).
80487 **
80488 ** This routine allocates the Stat3Accum object.
80489 **
80490 ** The return value is the Stat3Accum object (P).
80491 */
80492 static void stat3Init(
80493   sqlite3_context *context,
80494   int argc,
80495   sqlite3_value **argv
80496 ){
80497   Stat3Accum *p;
80498   tRowcnt nRow;
80499   int mxSample;
80500   int n;
80501
80502   UNUSED_PARAMETER(argc);
80503   nRow = (tRowcnt)sqlite3_value_int64(argv[0]);
80504   mxSample = sqlite3_value_int(argv[1]);
80505   n = sizeof(*p) + sizeof(p->a[0])*mxSample;
80506   p = sqlite3MallocZero( n );
80507   if( p==0 ){
80508     sqlite3_result_error_nomem(context);
80509     return;
80510   }
80511   p->a = (struct Stat3Sample*)&p[1];
80512   p->nRow = nRow;
80513   p->mxSample = mxSample;
80514   p->nPSample = p->nRow/(mxSample/3+1) + 1;
80515   sqlite3_randomness(sizeof(p->iPrn), &p->iPrn);
80516   sqlite3_result_blob(context, p, sizeof(p), sqlite3_free);
80517 }
80518 static const FuncDef stat3InitFuncdef = {
80519   2,                /* nArg */
80520   SQLITE_UTF8,      /* iPrefEnc */
80521   0,                /* flags */
80522   0,                /* pUserData */
80523   0,                /* pNext */
80524   stat3Init,        /* xFunc */
80525   0,                /* xStep */
80526   0,                /* xFinalize */
80527   "stat3_init",     /* zName */
80528   0,                /* pHash */
80529   0                 /* pDestructor */
80530 };
80531
80532
80533 /*
80534 ** Implementation of the stat3_push(nEq,nLt,nDLt,rowid,P) SQL function.  The
80535 ** arguments describe a single key instance.  This routine makes the 
80536 ** decision about whether or not to retain this key for the sqlite_stat3
80537 ** table.
80538 **
80539 ** The return value is NULL.
80540 */
80541 static void stat3Push(
80542   sqlite3_context *context,
80543   int argc,
80544   sqlite3_value **argv
80545 ){
80546   Stat3Accum *p = (Stat3Accum*)sqlite3_value_blob(argv[4]);
80547   tRowcnt nEq = sqlite3_value_int64(argv[0]);
80548   tRowcnt nLt = sqlite3_value_int64(argv[1]);
80549   tRowcnt nDLt = sqlite3_value_int64(argv[2]);
80550   i64 rowid = sqlite3_value_int64(argv[3]);
80551   u8 isPSample = 0;
80552   u8 doInsert = 0;
80553   int iMin = p->iMin;
80554   struct Stat3Sample *pSample;
80555   int i;
80556   u32 h;
80557
80558   UNUSED_PARAMETER(context);
80559   UNUSED_PARAMETER(argc);
80560   if( nEq==0 ) return;
80561   h = p->iPrn = p->iPrn*1103515245 + 12345;
80562   if( (nLt/p->nPSample)!=((nEq+nLt)/p->nPSample) ){
80563     doInsert = isPSample = 1;
80564   }else if( p->nSample<p->mxSample ){
80565     doInsert = 1;
80566   }else{
80567     if( nEq>p->a[iMin].nEq || (nEq==p->a[iMin].nEq && h>p->a[iMin].iHash) ){
80568       doInsert = 1;
80569     }
80570   }
80571   if( !doInsert ) return;
80572   if( p->nSample==p->mxSample ){
80573     assert( p->nSample - iMin - 1 >= 0 );
80574     memmove(&p->a[iMin], &p->a[iMin+1], sizeof(p->a[0])*(p->nSample-iMin-1));
80575     pSample = &p->a[p->nSample-1];
80576   }else{
80577     pSample = &p->a[p->nSample++];
80578   }
80579   pSample->iRowid = rowid;
80580   pSample->nEq = nEq;
80581   pSample->nLt = nLt;
80582   pSample->nDLt = nDLt;
80583   pSample->iHash = h;
80584   pSample->isPSample = isPSample;
80585
80586   /* Find the new minimum */
80587   if( p->nSample==p->mxSample ){
80588     pSample = p->a;
80589     i = 0;
80590     while( pSample->isPSample ){
80591       i++;
80592       pSample++;
80593       assert( i<p->nSample );
80594     }
80595     nEq = pSample->nEq;
80596     h = pSample->iHash;
80597     iMin = i;
80598     for(i++, pSample++; i<p->nSample; i++, pSample++){
80599       if( pSample->isPSample ) continue;
80600       if( pSample->nEq<nEq
80601        || (pSample->nEq==nEq && pSample->iHash<h)
80602       ){
80603         iMin = i;
80604         nEq = pSample->nEq;
80605         h = pSample->iHash;
80606       }
80607     }
80608     p->iMin = iMin;
80609   }
80610 }
80611 static const FuncDef stat3PushFuncdef = {
80612   5,                /* nArg */
80613   SQLITE_UTF8,      /* iPrefEnc */
80614   0,                /* flags */
80615   0,                /* pUserData */
80616   0,                /* pNext */
80617   stat3Push,        /* xFunc */
80618   0,                /* xStep */
80619   0,                /* xFinalize */
80620   "stat3_push",     /* zName */
80621   0,                /* pHash */
80622   0                 /* pDestructor */
80623 };
80624
80625 /*
80626 ** Implementation of the stat3_get(P,N,...) SQL function.  This routine is
80627 ** used to query the results.  Content is returned for the Nth sqlite_stat3
80628 ** row where N is between 0 and S-1 and S is the number of samples.  The
80629 ** value returned depends on the number of arguments.
80630 **
80631 **   argc==2    result:  rowid
80632 **   argc==3    result:  nEq
80633 **   argc==4    result:  nLt
80634 **   argc==5    result:  nDLt
80635 */
80636 static void stat3Get(
80637   sqlite3_context *context,
80638   int argc,
80639   sqlite3_value **argv
80640 ){
80641   int n = sqlite3_value_int(argv[1]);
80642   Stat3Accum *p = (Stat3Accum*)sqlite3_value_blob(argv[0]);
80643
80644   assert( p!=0 );
80645   if( p->nSample<=n ) return;
80646   switch( argc ){
80647     case 2:  sqlite3_result_int64(context, p->a[n].iRowid); break;
80648     case 3:  sqlite3_result_int64(context, p->a[n].nEq);    break;
80649     case 4:  sqlite3_result_int64(context, p->a[n].nLt);    break;
80650     default: sqlite3_result_int64(context, p->a[n].nDLt);   break;
80651   }
80652 }
80653 static const FuncDef stat3GetFuncdef = {
80654   -1,               /* nArg */
80655   SQLITE_UTF8,      /* iPrefEnc */
80656   0,                /* flags */
80657   0,                /* pUserData */
80658   0,                /* pNext */
80659   stat3Get,         /* xFunc */
80660   0,                /* xStep */
80661   0,                /* xFinalize */
80662   "stat3_get",     /* zName */
80663   0,                /* pHash */
80664   0                 /* pDestructor */
80665 };
80666 #endif /* SQLITE_ENABLE_STAT3 */
80667
80668
80669
80670
80671 /*
80672 ** Generate code to do an analysis of all indices associated with
80673 ** a single table.
80674 */
80675 static void analyzeOneTable(
80676   Parse *pParse,   /* Parser context */
80677   Table *pTab,     /* Table whose indices are to be analyzed */
80678   Index *pOnlyIdx, /* If not NULL, only analyze this one index */
80679   int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
80680   int iMem         /* Available memory locations begin here */
80681 ){
80682   sqlite3 *db = pParse->db;    /* Database handle */
80683   Index *pIdx;                 /* An index to being analyzed */
80684   int iIdxCur;                 /* Cursor open on index being analyzed */
80685   Vdbe *v;                     /* The virtual machine being built up */
80686   int i;                       /* Loop counter */
80687   int topOfLoop;               /* The top of the loop */
80688   int endOfLoop;               /* The end of the loop */
80689   int jZeroRows = -1;          /* Jump from here if number of rows is zero */
80690   int iDb;                     /* Index of database containing pTab */
80691   int regTabname = iMem++;     /* Register containing table name */
80692   int regIdxname = iMem++;     /* Register containing index name */
80693   int regStat1 = iMem++;       /* The stat column of sqlite_stat1 */
80694 #ifdef SQLITE_ENABLE_STAT3
80695   int regNumEq = regStat1;     /* Number of instances.  Same as regStat1 */
80696   int regNumLt = iMem++;       /* Number of keys less than regSample */
80697   int regNumDLt = iMem++;      /* Number of distinct keys less than regSample */
80698   int regSample = iMem++;      /* The next sample value */
80699   int regRowid = regSample;    /* Rowid of a sample */
80700   int regAccum = iMem++;       /* Register to hold Stat3Accum object */
80701   int regLoop = iMem++;        /* Loop counter */
80702   int regCount = iMem++;       /* Number of rows in the table or index */
80703   int regTemp1 = iMem++;       /* Intermediate register */
80704   int regTemp2 = iMem++;       /* Intermediate register */
80705   int once = 1;                /* One-time initialization */
80706   int shortJump = 0;           /* Instruction address */
80707   int iTabCur = pParse->nTab++; /* Table cursor */
80708 #endif
80709   int regCol = iMem++;         /* Content of a column in analyzed table */
80710   int regRec = iMem++;         /* Register holding completed record */
80711   int regTemp = iMem++;        /* Temporary use register */
80712   int regNewRowid = iMem++;    /* Rowid for the inserted record */
80713
80714
80715   v = sqlite3GetVdbe(pParse);
80716   if( v==0 || NEVER(pTab==0) ){
80717     return;
80718   }
80719   if( pTab->tnum==0 ){
80720     /* Do not gather statistics on views or virtual tables */
80721     return;
80722   }
80723   if( sqlite3_strnicmp(pTab->zName, "sqlite_", 7)==0 ){
80724     /* Do not gather statistics on system tables */
80725     return;
80726   }
80727   assert( sqlite3BtreeHoldsAllMutexes(db) );
80728   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
80729   assert( iDb>=0 );
80730   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
80731 #ifndef SQLITE_OMIT_AUTHORIZATION
80732   if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
80733       db->aDb[iDb].zName ) ){
80734     return;
80735   }
80736 #endif
80737
80738   /* Establish a read-lock on the table at the shared-cache level. */
80739   sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
80740
80741   iIdxCur = pParse->nTab++;
80742   sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
80743   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
80744     int nCol;
80745     KeyInfo *pKey;
80746     int addrIfNot = 0;           /* address of OP_IfNot */
80747     int *aChngAddr;              /* Array of jump instruction addresses */
80748
80749     if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
80750     VdbeNoopComment((v, "Begin analysis of %s", pIdx->zName));
80751     nCol = pIdx->nColumn;
80752     aChngAddr = sqlite3DbMallocRaw(db, sizeof(int)*nCol);
80753     if( aChngAddr==0 ) continue;
80754     pKey = sqlite3IndexKeyinfo(pParse, pIdx);
80755     if( iMem+1+(nCol*2)>pParse->nMem ){
80756       pParse->nMem = iMem+1+(nCol*2);
80757     }
80758
80759     /* Open a cursor to the index to be analyzed. */
80760     assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
80761     sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
80762         (char *)pKey, P4_KEYINFO_HANDOFF);
80763     VdbeComment((v, "%s", pIdx->zName));
80764
80765     /* Populate the register containing the index name. */
80766     sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);
80767
80768 #ifdef SQLITE_ENABLE_STAT3
80769     if( once ){
80770       once = 0;
80771       sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
80772     }
80773     sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regCount);
80774     sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_STAT3_SAMPLES, regTemp1);
80775     sqlite3VdbeAddOp2(v, OP_Integer, 0, regNumEq);
80776     sqlite3VdbeAddOp2(v, OP_Integer, 0, regNumLt);
80777     sqlite3VdbeAddOp2(v, OP_Integer, -1, regNumDLt);
80778     sqlite3VdbeAddOp3(v, OP_Null, 0, regSample, regAccum);
80779     sqlite3VdbeAddOp4(v, OP_Function, 1, regCount, regAccum,
80780                       (char*)&stat3InitFuncdef, P4_FUNCDEF);
80781     sqlite3VdbeChangeP5(v, 2);
80782 #endif /* SQLITE_ENABLE_STAT3 */
80783
80784     /* The block of memory cells initialized here is used as follows.
80785     **
80786     **    iMem:                
80787     **        The total number of rows in the table.
80788     **
80789     **    iMem+1 .. iMem+nCol: 
80790     **        Number of distinct entries in index considering the 
80791     **        left-most N columns only, where N is between 1 and nCol, 
80792     **        inclusive.
80793     **
80794     **    iMem+nCol+1 .. Mem+2*nCol:  
80795     **        Previous value of indexed columns, from left to right.
80796     **
80797     ** Cells iMem through iMem+nCol are initialized to 0. The others are 
80798     ** initialized to contain an SQL NULL.
80799     */
80800     for(i=0; i<=nCol; i++){
80801       sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i);
80802     }
80803     for(i=0; i<nCol; i++){
80804       sqlite3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);
80805     }
80806
80807     /* Start the analysis loop. This loop runs through all the entries in
80808     ** the index b-tree.  */
80809     endOfLoop = sqlite3VdbeMakeLabel(v);
80810     sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
80811     topOfLoop = sqlite3VdbeCurrentAddr(v);
80812     sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1);  /* Increment row counter */
80813
80814     for(i=0; i<nCol; i++){
80815       CollSeq *pColl;
80816       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
80817       if( i==0 ){
80818         /* Always record the very first row */
80819         addrIfNot = sqlite3VdbeAddOp1(v, OP_IfNot, iMem+1);
80820       }
80821       assert( pIdx->azColl!=0 );
80822       assert( pIdx->azColl[i]!=0 );
80823       pColl = sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
80824       aChngAddr[i] = sqlite3VdbeAddOp4(v, OP_Ne, regCol, 0, iMem+nCol+i+1,
80825                                       (char*)pColl, P4_COLLSEQ);
80826       sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
80827       VdbeComment((v, "jump if column %d changed", i));
80828 #ifdef SQLITE_ENABLE_STAT3
80829       if( i==0 ){
80830         sqlite3VdbeAddOp2(v, OP_AddImm, regNumEq, 1);
80831         VdbeComment((v, "incr repeat count"));
80832       }
80833 #endif
80834     }
80835     sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
80836     for(i=0; i<nCol; i++){
80837       sqlite3VdbeJumpHere(v, aChngAddr[i]);  /* Set jump dest for the OP_Ne */
80838       if( i==0 ){
80839         sqlite3VdbeJumpHere(v, addrIfNot);   /* Jump dest for OP_IfNot */
80840 #ifdef SQLITE_ENABLE_STAT3
80841         sqlite3VdbeAddOp4(v, OP_Function, 1, regNumEq, regTemp2,
80842                           (char*)&stat3PushFuncdef, P4_FUNCDEF);
80843         sqlite3VdbeChangeP5(v, 5);
80844         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, pIdx->nColumn, regRowid);
80845         sqlite3VdbeAddOp3(v, OP_Add, regNumEq, regNumLt, regNumLt);
80846         sqlite3VdbeAddOp2(v, OP_AddImm, regNumDLt, 1);
80847         sqlite3VdbeAddOp2(v, OP_Integer, 1, regNumEq);
80848 #endif        
80849       }
80850       sqlite3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);
80851       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);
80852     }
80853     sqlite3DbFree(db, aChngAddr);
80854
80855     /* Always jump here after updating the iMem+1...iMem+1+nCol counters */
80856     sqlite3VdbeResolveLabel(v, endOfLoop);
80857
80858     sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
80859     sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
80860 #ifdef SQLITE_ENABLE_STAT3
80861     sqlite3VdbeAddOp4(v, OP_Function, 1, regNumEq, regTemp2,
80862                       (char*)&stat3PushFuncdef, P4_FUNCDEF);
80863     sqlite3VdbeChangeP5(v, 5);
80864     sqlite3VdbeAddOp2(v, OP_Integer, -1, regLoop);
80865     shortJump = 
80866     sqlite3VdbeAddOp2(v, OP_AddImm, regLoop, 1);
80867     sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regTemp1,
80868                       (char*)&stat3GetFuncdef, P4_FUNCDEF);
80869     sqlite3VdbeChangeP5(v, 2);
80870     sqlite3VdbeAddOp1(v, OP_IsNull, regTemp1);
80871     sqlite3VdbeAddOp3(v, OP_NotExists, iTabCur, shortJump, regTemp1);
80872     sqlite3VdbeAddOp3(v, OP_Column, iTabCur, pIdx->aiColumn[0], regSample);
80873     sqlite3ColumnDefault(v, pTab, pIdx->aiColumn[0], regSample);
80874     sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumEq,
80875                       (char*)&stat3GetFuncdef, P4_FUNCDEF);
80876     sqlite3VdbeChangeP5(v, 3);
80877     sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumLt,
80878                       (char*)&stat3GetFuncdef, P4_FUNCDEF);
80879     sqlite3VdbeChangeP5(v, 4);
80880     sqlite3VdbeAddOp4(v, OP_Function, 1, regAccum, regNumDLt,
80881                       (char*)&stat3GetFuncdef, P4_FUNCDEF);
80882     sqlite3VdbeChangeP5(v, 5);
80883     sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 6, regRec, "bbbbbb", 0);
80884     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
80885     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regRec, regNewRowid);
80886     sqlite3VdbeAddOp2(v, OP_Goto, 0, shortJump);
80887     sqlite3VdbeJumpHere(v, shortJump+2);
80888 #endif        
80889
80890     /* Store the results in sqlite_stat1.
80891     **
80892     ** The result is a single row of the sqlite_stat1 table.  The first
80893     ** two columns are the names of the table and index.  The third column
80894     ** is a string composed of a list of integer statistics about the
80895     ** index.  The first integer in the list is the total number of entries
80896     ** in the index.  There is one additional integer in the list for each
80897     ** column of the table.  This additional integer is a guess of how many
80898     ** rows of the table the index will select.  If D is the count of distinct
80899     ** values and K is the total number of rows, then the integer is computed
80900     ** as:
80901     **
80902     **        I = (K+D-1)/D
80903     **
80904     ** If K==0 then no entry is made into the sqlite_stat1 table.  
80905     ** If K>0 then it is always the case the D>0 so division by zero
80906     ** is never possible.
80907     */
80908     sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regStat1);
80909     if( jZeroRows<0 ){
80910       jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
80911     }
80912     for(i=0; i<nCol; i++){
80913       sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
80914       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regStat1, regStat1);
80915       sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
80916       sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
80917       sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
80918       sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
80919       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regStat1, regStat1);
80920     }
80921     sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
80922     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
80923     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regNewRowid);
80924     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
80925   }
80926
80927   /* If the table has no indices, create a single sqlite_stat1 entry
80928   ** containing NULL as the index name and the row count as the content.
80929   */
80930   if( pTab->pIndex==0 ){
80931     sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pTab->tnum, iDb);
80932     VdbeComment((v, "%s", pTab->zName));
80933     sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat1);
80934     sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
80935     jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1);
80936   }else{
80937     sqlite3VdbeJumpHere(v, jZeroRows);
80938     jZeroRows = sqlite3VdbeAddOp0(v, OP_Goto);
80939   }
80940   sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
80941   sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
80942   sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
80943   sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regNewRowid);
80944   sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
80945   if( pParse->nMem<regRec ) pParse->nMem = regRec;
80946   sqlite3VdbeJumpHere(v, jZeroRows);
80947 }
80948
80949
80950 /*
80951 ** Generate code that will cause the most recent index analysis to
80952 ** be loaded into internal hash tables where is can be used.
80953 */
80954 static void loadAnalysis(Parse *pParse, int iDb){
80955   Vdbe *v = sqlite3GetVdbe(pParse);
80956   if( v ){
80957     sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
80958   }
80959 }
80960
80961 /*
80962 ** Generate code that will do an analysis of an entire database
80963 */
80964 static void analyzeDatabase(Parse *pParse, int iDb){
80965   sqlite3 *db = pParse->db;
80966   Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
80967   HashElem *k;
80968   int iStatCur;
80969   int iMem;
80970
80971   sqlite3BeginWriteOperation(pParse, 0, iDb);
80972   iStatCur = pParse->nTab;
80973   pParse->nTab += 3;
80974   openStatTable(pParse, iDb, iStatCur, 0, 0);
80975   iMem = pParse->nMem+1;
80976   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
80977   for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
80978     Table *pTab = (Table*)sqliteHashData(k);
80979     analyzeOneTable(pParse, pTab, 0, iStatCur, iMem);
80980   }
80981   loadAnalysis(pParse, iDb);
80982 }
80983
80984 /*
80985 ** Generate code that will do an analysis of a single table in
80986 ** a database.  If pOnlyIdx is not NULL then it is a single index
80987 ** in pTab that should be analyzed.
80988 */
80989 static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
80990   int iDb;
80991   int iStatCur;
80992
80993   assert( pTab!=0 );
80994   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
80995   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
80996   sqlite3BeginWriteOperation(pParse, 0, iDb);
80997   iStatCur = pParse->nTab;
80998   pParse->nTab += 3;
80999   if( pOnlyIdx ){
81000     openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
81001   }else{
81002     openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
81003   }
81004   analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur, pParse->nMem+1);
81005   loadAnalysis(pParse, iDb);
81006 }
81007
81008 /*
81009 ** Generate code for the ANALYZE command.  The parser calls this routine
81010 ** when it recognizes an ANALYZE command.
81011 **
81012 **        ANALYZE                            -- 1
81013 **        ANALYZE  <database>                -- 2
81014 **        ANALYZE  ?<database>.?<tablename>  -- 3
81015 **
81016 ** Form 1 causes all indices in all attached databases to be analyzed.
81017 ** Form 2 analyzes all indices the single database named.
81018 ** Form 3 analyzes all indices associated with the named table.
81019 */
81020 SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
81021   sqlite3 *db = pParse->db;
81022   int iDb;
81023   int i;
81024   char *z, *zDb;
81025   Table *pTab;
81026   Index *pIdx;
81027   Token *pTableName;
81028
81029   /* Read the database schema. If an error occurs, leave an error message
81030   ** and code in pParse and return NULL. */
81031   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
81032   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
81033     return;
81034   }
81035
81036   assert( pName2!=0 || pName1==0 );
81037   if( pName1==0 ){
81038     /* Form 1:  Analyze everything */
81039     for(i=0; i<db->nDb; i++){
81040       if( i==1 ) continue;  /* Do not analyze the TEMP database */
81041       analyzeDatabase(pParse, i);
81042     }
81043   }else if( pName2->n==0 ){
81044     /* Form 2:  Analyze the database or table named */
81045     iDb = sqlite3FindDb(db, pName1);
81046     if( iDb>=0 ){
81047       analyzeDatabase(pParse, iDb);
81048     }else{
81049       z = sqlite3NameFromToken(db, pName1);
81050       if( z ){
81051         if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
81052           analyzeTable(pParse, pIdx->pTable, pIdx);
81053         }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
81054           analyzeTable(pParse, pTab, 0);
81055         }
81056         sqlite3DbFree(db, z);
81057       }
81058     }
81059   }else{
81060     /* Form 3: Analyze the fully qualified table name */
81061     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
81062     if( iDb>=0 ){
81063       zDb = db->aDb[iDb].zName;
81064       z = sqlite3NameFromToken(db, pTableName);
81065       if( z ){
81066         if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
81067           analyzeTable(pParse, pIdx->pTable, pIdx);
81068         }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
81069           analyzeTable(pParse, pTab, 0);
81070         }
81071         sqlite3DbFree(db, z);
81072       }
81073     }   
81074   }
81075 }
81076
81077 /*
81078 ** Used to pass information from the analyzer reader through to the
81079 ** callback routine.
81080 */
81081 typedef struct analysisInfo analysisInfo;
81082 struct analysisInfo {
81083   sqlite3 *db;
81084   const char *zDatabase;
81085 };
81086
81087 /*
81088 ** This callback is invoked once for each index when reading the
81089 ** sqlite_stat1 table.  
81090 **
81091 **     argv[0] = name of the table
81092 **     argv[1] = name of the index (might be NULL)
81093 **     argv[2] = results of analysis - on integer for each column
81094 **
81095 ** Entries for which argv[1]==NULL simply record the number of rows in
81096 ** the table.
81097 */
81098 static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
81099   analysisInfo *pInfo = (analysisInfo*)pData;
81100   Index *pIndex;
81101   Table *pTable;
81102   int i, c, n;
81103   tRowcnt v;
81104   const char *z;
81105
81106   assert( argc==3 );
81107   UNUSED_PARAMETER2(NotUsed, argc);
81108
81109   if( argv==0 || argv[0]==0 || argv[2]==0 ){
81110     return 0;
81111   }
81112   pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
81113   if( pTable==0 ){
81114     return 0;
81115   }
81116   if( argv[1] ){
81117     pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
81118   }else{
81119     pIndex = 0;
81120   }
81121   n = pIndex ? pIndex->nColumn : 0;
81122   z = argv[2];
81123   for(i=0; *z && i<=n; i++){
81124     v = 0;
81125     while( (c=z[0])>='0' && c<='9' ){
81126       v = v*10 + c - '0';
81127       z++;
81128     }
81129     if( i==0 ) pTable->nRowEst = v;
81130     if( pIndex==0 ) break;
81131     pIndex->aiRowEst[i] = v;
81132     if( *z==' ' ) z++;
81133     if( strcmp(z, "unordered")==0 ){
81134       pIndex->bUnordered = 1;
81135       break;
81136     }
81137   }
81138   return 0;
81139 }
81140
81141 /*
81142 ** If the Index.aSample variable is not NULL, delete the aSample[] array
81143 ** and its contents.
81144 */
81145 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
81146 #ifdef SQLITE_ENABLE_STAT3
81147   if( pIdx->aSample ){
81148     int j;
81149     for(j=0; j<pIdx->nSample; j++){
81150       IndexSample *p = &pIdx->aSample[j];
81151       if( p->eType==SQLITE_TEXT || p->eType==SQLITE_BLOB ){
81152         sqlite3DbFree(db, p->u.z);
81153       }
81154     }
81155     sqlite3DbFree(db, pIdx->aSample);
81156   }
81157   if( db && db->pnBytesFreed==0 ){
81158     pIdx->nSample = 0;
81159     pIdx->aSample = 0;
81160   }
81161 #else
81162   UNUSED_PARAMETER(db);
81163   UNUSED_PARAMETER(pIdx);
81164 #endif
81165 }
81166
81167 #ifdef SQLITE_ENABLE_STAT3
81168 /*
81169 ** Load content from the sqlite_stat3 table into the Index.aSample[]
81170 ** arrays of all indices.
81171 */
81172 static int loadStat3(sqlite3 *db, const char *zDb){
81173   int rc;                       /* Result codes from subroutines */
81174   sqlite3_stmt *pStmt = 0;      /* An SQL statement being run */
81175   char *zSql;                   /* Text of the SQL statement */
81176   Index *pPrevIdx = 0;          /* Previous index in the loop */
81177   int idx = 0;                  /* slot in pIdx->aSample[] for next sample */
81178   int eType;                    /* Datatype of a sample */
81179   IndexSample *pSample;         /* A slot in pIdx->aSample[] */
81180
81181   assert( db->lookaside.bEnabled==0 );
81182   if( !sqlite3FindTable(db, "sqlite_stat3", zDb) ){
81183     return SQLITE_OK;
81184   }
81185
81186   zSql = sqlite3MPrintf(db, 
81187       "SELECT idx,count(*) FROM %Q.sqlite_stat3"
81188       " GROUP BY idx", zDb);
81189   if( !zSql ){
81190     return SQLITE_NOMEM;
81191   }
81192   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
81193   sqlite3DbFree(db, zSql);
81194   if( rc ) return rc;
81195
81196   while( sqlite3_step(pStmt)==SQLITE_ROW ){
81197     char *zIndex;   /* Index name */
81198     Index *pIdx;    /* Pointer to the index object */
81199     int nSample;    /* Number of samples */
81200
81201     zIndex = (char *)sqlite3_column_text(pStmt, 0);
81202     if( zIndex==0 ) continue;
81203     nSample = sqlite3_column_int(pStmt, 1);
81204     pIdx = sqlite3FindIndex(db, zIndex, zDb);
81205     if( pIdx==0 ) continue;
81206     assert( pIdx->nSample==0 );
81207     pIdx->nSample = nSample;
81208     pIdx->aSample = sqlite3DbMallocZero(db, nSample*sizeof(IndexSample));
81209     pIdx->avgEq = pIdx->aiRowEst[1];
81210     if( pIdx->aSample==0 ){
81211       db->mallocFailed = 1;
81212       sqlite3_finalize(pStmt);
81213       return SQLITE_NOMEM;
81214     }
81215   }
81216   rc = sqlite3_finalize(pStmt);
81217   if( rc ) return rc;
81218
81219   zSql = sqlite3MPrintf(db, 
81220       "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat3", zDb);
81221   if( !zSql ){
81222     return SQLITE_NOMEM;
81223   }
81224   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
81225   sqlite3DbFree(db, zSql);
81226   if( rc ) return rc;
81227
81228   while( sqlite3_step(pStmt)==SQLITE_ROW ){
81229     char *zIndex;   /* Index name */
81230     Index *pIdx;    /* Pointer to the index object */
81231     int i;          /* Loop counter */
81232     tRowcnt sumEq;  /* Sum of the nEq values */
81233
81234     zIndex = (char *)sqlite3_column_text(pStmt, 0);
81235     if( zIndex==0 ) continue;
81236     pIdx = sqlite3FindIndex(db, zIndex, zDb);
81237     if( pIdx==0 ) continue;
81238     if( pIdx==pPrevIdx ){
81239       idx++;
81240     }else{
81241       pPrevIdx = pIdx;
81242       idx = 0;
81243     }
81244     assert( idx<pIdx->nSample );
81245     pSample = &pIdx->aSample[idx];
81246     pSample->nEq = (tRowcnt)sqlite3_column_int64(pStmt, 1);
81247     pSample->nLt = (tRowcnt)sqlite3_column_int64(pStmt, 2);
81248     pSample->nDLt = (tRowcnt)sqlite3_column_int64(pStmt, 3);
81249     if( idx==pIdx->nSample-1 ){
81250       if( pSample->nDLt>0 ){
81251         for(i=0, sumEq=0; i<=idx-1; i++) sumEq += pIdx->aSample[i].nEq;
81252         pIdx->avgEq = (pSample->nLt - sumEq)/pSample->nDLt;
81253       }
81254       if( pIdx->avgEq<=0 ) pIdx->avgEq = 1;
81255     }
81256     eType = sqlite3_column_type(pStmt, 4);
81257     pSample->eType = (u8)eType;
81258     switch( eType ){
81259       case SQLITE_INTEGER: {
81260         pSample->u.i = sqlite3_column_int64(pStmt, 4);
81261         break;
81262       }
81263       case SQLITE_FLOAT: {
81264         pSample->u.r = sqlite3_column_double(pStmt, 4);
81265         break;
81266       }
81267       case SQLITE_NULL: {
81268         break;
81269       }
81270       default: assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB ); {
81271         const char *z = (const char *)(
81272               (eType==SQLITE_BLOB) ?
81273               sqlite3_column_blob(pStmt, 4):
81274               sqlite3_column_text(pStmt, 4)
81275            );
81276         int n = z ? sqlite3_column_bytes(pStmt, 4) : 0;
81277         pSample->nByte = n;
81278         if( n < 1){
81279           pSample->u.z = 0;
81280         }else{
81281           pSample->u.z = sqlite3DbMallocRaw(db, n);
81282           if( pSample->u.z==0 ){
81283             db->mallocFailed = 1;
81284             sqlite3_finalize(pStmt);
81285             return SQLITE_NOMEM;
81286           }
81287           memcpy(pSample->u.z, z, n);
81288         }
81289       }
81290     }
81291   }
81292   return sqlite3_finalize(pStmt);
81293 }
81294 #endif /* SQLITE_ENABLE_STAT3 */
81295
81296 /*
81297 ** Load the content of the sqlite_stat1 and sqlite_stat3 tables. The
81298 ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
81299 ** arrays. The contents of sqlite_stat3 are used to populate the
81300 ** Index.aSample[] arrays.
81301 **
81302 ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
81303 ** is returned. In this case, even if SQLITE_ENABLE_STAT3 was defined 
81304 ** during compilation and the sqlite_stat3 table is present, no data is 
81305 ** read from it.
81306 **
81307 ** If SQLITE_ENABLE_STAT3 was defined during compilation and the 
81308 ** sqlite_stat3 table is not present in the database, SQLITE_ERROR is
81309 ** returned. However, in this case, data is read from the sqlite_stat1
81310 ** table (if it is present) before returning.
81311 **
81312 ** If an OOM error occurs, this function always sets db->mallocFailed.
81313 ** This means if the caller does not care about other errors, the return
81314 ** code may be ignored.
81315 */
81316 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
81317   analysisInfo sInfo;
81318   HashElem *i;
81319   char *zSql;
81320   int rc;
81321
81322   assert( iDb>=0 && iDb<db->nDb );
81323   assert( db->aDb[iDb].pBt!=0 );
81324
81325   /* Clear any prior statistics */
81326   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
81327   for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
81328     Index *pIdx = sqliteHashData(i);
81329     sqlite3DefaultRowEst(pIdx);
81330 #ifdef SQLITE_ENABLE_STAT3
81331     sqlite3DeleteIndexSamples(db, pIdx);
81332     pIdx->aSample = 0;
81333 #endif
81334   }
81335
81336   /* Check to make sure the sqlite_stat1 table exists */
81337   sInfo.db = db;
81338   sInfo.zDatabase = db->aDb[iDb].zName;
81339   if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
81340     return SQLITE_ERROR;
81341   }
81342
81343   /* Load new statistics out of the sqlite_stat1 table */
81344   zSql = sqlite3MPrintf(db, 
81345       "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
81346   if( zSql==0 ){
81347     rc = SQLITE_NOMEM;
81348   }else{
81349     rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
81350     sqlite3DbFree(db, zSql);
81351   }
81352
81353
81354   /* Load the statistics from the sqlite_stat3 table. */
81355 #ifdef SQLITE_ENABLE_STAT3
81356   if( rc==SQLITE_OK ){
81357     int lookasideEnabled = db->lookaside.bEnabled;
81358     db->lookaside.bEnabled = 0;
81359     rc = loadStat3(db, sInfo.zDatabase);
81360     db->lookaside.bEnabled = lookasideEnabled;
81361   }
81362 #endif
81363
81364   if( rc==SQLITE_NOMEM ){
81365     db->mallocFailed = 1;
81366   }
81367   return rc;
81368 }
81369
81370
81371 #endif /* SQLITE_OMIT_ANALYZE */
81372
81373 /************** End of analyze.c *********************************************/
81374 /************** Begin file attach.c ******************************************/
81375 /*
81376 ** 2003 April 6
81377 **
81378 ** The author disclaims copyright to this source code.  In place of
81379 ** a legal notice, here is a blessing:
81380 **
81381 **    May you do good and not evil.
81382 **    May you find forgiveness for yourself and forgive others.
81383 **    May you share freely, never taking more than you give.
81384 **
81385 *************************************************************************
81386 ** This file contains code used to implement the ATTACH and DETACH commands.
81387 */
81388
81389 #ifndef SQLITE_OMIT_ATTACH
81390 /*
81391 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
81392 ** is slightly different from resolving a normal SQL expression, because simple
81393 ** identifiers are treated as strings, not possible column names or aliases.
81394 **
81395 ** i.e. if the parser sees:
81396 **
81397 **     ATTACH DATABASE abc AS def
81398 **
81399 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
81400 ** looking for columns of the same name.
81401 **
81402 ** This only applies to the root node of pExpr, so the statement:
81403 **
81404 **     ATTACH DATABASE abc||def AS 'db2'
81405 **
81406 ** will fail because neither abc or def can be resolved.
81407 */
81408 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
81409 {
81410   int rc = SQLITE_OK;
81411   if( pExpr ){
81412     if( pExpr->op!=TK_ID ){
81413       rc = sqlite3ResolveExprNames(pName, pExpr);
81414       if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
81415         sqlite3ErrorMsg(pName->pParse, "invalid name: \"%s\"", pExpr->u.zToken);
81416         return SQLITE_ERROR;
81417       }
81418     }else{
81419       pExpr->op = TK_STRING;
81420     }
81421   }
81422   return rc;
81423 }
81424
81425 /*
81426 ** An SQL user-function registered to do the work of an ATTACH statement. The
81427 ** three arguments to the function come directly from an attach statement:
81428 **
81429 **     ATTACH DATABASE x AS y KEY z
81430 **
81431 **     SELECT sqlite_attach(x, y, z)
81432 **
81433 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
81434 ** third argument.
81435 */
81436 static void attachFunc(
81437   sqlite3_context *context,
81438   int NotUsed,
81439   sqlite3_value **argv
81440 ){
81441   int i;
81442   int rc = 0;
81443   sqlite3 *db = sqlite3_context_db_handle(context);
81444   const char *zName;
81445   const char *zFile;
81446   char *zPath = 0;
81447   char *zErr = 0;
81448   unsigned int flags;
81449   Db *aNew;
81450   char *zErrDyn = 0;
81451   sqlite3_vfs *pVfs;
81452
81453   UNUSED_PARAMETER(NotUsed);
81454
81455   zFile = (const char *)sqlite3_value_text(argv[0]);
81456   zName = (const char *)sqlite3_value_text(argv[1]);
81457   if( zFile==0 ) zFile = "";
81458   if( zName==0 ) zName = "";
81459
81460   /* Check for the following errors:
81461   **
81462   **     * Too many attached databases,
81463   **     * Transaction currently open
81464   **     * Specified database name already being used.
81465   */
81466   if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
81467     zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d", 
81468       db->aLimit[SQLITE_LIMIT_ATTACHED]
81469     );
81470     goto attach_error;
81471   }
81472   if( !db->autoCommit ){
81473     zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
81474     goto attach_error;
81475   }
81476   for(i=0; i<db->nDb; i++){
81477     char *z = db->aDb[i].zName;
81478     assert( z && zName );
81479     if( sqlite3StrICmp(z, zName)==0 ){
81480       zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
81481       goto attach_error;
81482     }
81483   }
81484
81485   /* Allocate the new entry in the db->aDb[] array and initialize the schema
81486   ** hash tables.
81487   */
81488   if( db->aDb==db->aDbStatic ){
81489     aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
81490     if( aNew==0 ) return;
81491     memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
81492   }else{
81493     aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
81494     if( aNew==0 ) return;
81495   }
81496   db->aDb = aNew;
81497   aNew = &db->aDb[db->nDb];
81498   memset(aNew, 0, sizeof(*aNew));
81499
81500   /* Open the database file. If the btree is successfully opened, use
81501   ** it to obtain the database schema. At this point the schema may
81502   ** or may not be initialized.
81503   */
81504   flags = db->openFlags;
81505   rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
81506   if( rc!=SQLITE_OK ){
81507     if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
81508     sqlite3_result_error(context, zErr, -1);
81509     sqlite3_free(zErr);
81510     return;
81511   }
81512   assert( pVfs );
81513   flags |= SQLITE_OPEN_MAIN_DB;
81514   rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
81515   sqlite3_free( zPath );
81516   db->nDb++;
81517   if( rc==SQLITE_CONSTRAINT ){
81518     rc = SQLITE_ERROR;
81519     zErrDyn = sqlite3MPrintf(db, "database is already attached");
81520   }else if( rc==SQLITE_OK ){
81521     Pager *pPager;
81522     aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
81523     if( !aNew->pSchema ){
81524       rc = SQLITE_NOMEM;
81525     }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
81526       zErrDyn = sqlite3MPrintf(db, 
81527         "attached databases must use the same text encoding as main database");
81528       rc = SQLITE_ERROR;
81529     }
81530     pPager = sqlite3BtreePager(aNew->pBt);
81531     sqlite3PagerLockingMode(pPager, db->dfltLockMode);
81532     sqlite3BtreeSecureDelete(aNew->pBt,
81533                              sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
81534   }
81535   aNew->safety_level = 3;
81536   aNew->zName = sqlite3DbStrDup(db, zName);
81537   if( rc==SQLITE_OK && aNew->zName==0 ){
81538     rc = SQLITE_NOMEM;
81539   }
81540
81541
81542 #ifdef SQLITE_HAS_CODEC
81543   if( rc==SQLITE_OK ){
81544     extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
81545     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
81546     int nKey;
81547     char *zKey;
81548     int t = sqlite3_value_type(argv[2]);
81549     switch( t ){
81550       case SQLITE_INTEGER:
81551       case SQLITE_FLOAT:
81552         zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
81553         rc = SQLITE_ERROR;
81554         break;
81555         
81556       case SQLITE_TEXT:
81557       case SQLITE_BLOB:
81558         nKey = sqlite3_value_bytes(argv[2]);
81559         zKey = (char *)sqlite3_value_blob(argv[2]);
81560         rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
81561         break;
81562
81563       case SQLITE_NULL:
81564         /* No key specified.  Use the key from the main database */
81565         sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
81566         if( nKey>0 || sqlite3BtreeGetReserve(db->aDb[0].pBt)>0 ){
81567           rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
81568         }
81569         break;
81570     }
81571   }
81572 #endif
81573
81574   /* If the file was opened successfully, read the schema for the new database.
81575   ** If this fails, or if opening the file failed, then close the file and 
81576   ** remove the entry from the db->aDb[] array. i.e. put everything back the way
81577   ** we found it.
81578   */
81579   if( rc==SQLITE_OK ){
81580     sqlite3BtreeEnterAll(db);
81581     rc = sqlite3Init(db, &zErrDyn);
81582     sqlite3BtreeLeaveAll(db);
81583   }
81584   if( rc ){
81585     int iDb = db->nDb - 1;
81586     assert( iDb>=2 );
81587     if( db->aDb[iDb].pBt ){
81588       sqlite3BtreeClose(db->aDb[iDb].pBt);
81589       db->aDb[iDb].pBt = 0;
81590       db->aDb[iDb].pSchema = 0;
81591     }
81592     sqlite3ResetAllSchemasOfConnection(db);
81593     db->nDb = iDb;
81594     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
81595       db->mallocFailed = 1;
81596       sqlite3DbFree(db, zErrDyn);
81597       zErrDyn = sqlite3MPrintf(db, "out of memory");
81598     }else if( zErrDyn==0 ){
81599       zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
81600     }
81601     goto attach_error;
81602   }
81603   
81604   return;
81605
81606 attach_error:
81607   /* Return an error if we get here */
81608   if( zErrDyn ){
81609     sqlite3_result_error(context, zErrDyn, -1);
81610     sqlite3DbFree(db, zErrDyn);
81611   }
81612   if( rc ) sqlite3_result_error_code(context, rc);
81613 }
81614
81615 /*
81616 ** An SQL user-function registered to do the work of an DETACH statement. The
81617 ** three arguments to the function come directly from a detach statement:
81618 **
81619 **     DETACH DATABASE x
81620 **
81621 **     SELECT sqlite_detach(x)
81622 */
81623 static void detachFunc(
81624   sqlite3_context *context,
81625   int NotUsed,
81626   sqlite3_value **argv
81627 ){
81628   const char *zName = (const char *)sqlite3_value_text(argv[0]);
81629   sqlite3 *db = sqlite3_context_db_handle(context);
81630   int i;
81631   Db *pDb = 0;
81632   char zErr[128];
81633
81634   UNUSED_PARAMETER(NotUsed);
81635
81636   if( zName==0 ) zName = "";
81637   for(i=0; i<db->nDb; i++){
81638     pDb = &db->aDb[i];
81639     if( pDb->pBt==0 ) continue;
81640     if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
81641   }
81642
81643   if( i>=db->nDb ){
81644     sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
81645     goto detach_error;
81646   }
81647   if( i<2 ){
81648     sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
81649     goto detach_error;
81650   }
81651   if( !db->autoCommit ){
81652     sqlite3_snprintf(sizeof(zErr), zErr,
81653                      "cannot DETACH database within transaction");
81654     goto detach_error;
81655   }
81656   if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
81657     sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
81658     goto detach_error;
81659   }
81660
81661   sqlite3BtreeClose(pDb->pBt);
81662   pDb->pBt = 0;
81663   pDb->pSchema = 0;
81664   sqlite3ResetAllSchemasOfConnection(db);
81665   return;
81666
81667 detach_error:
81668   sqlite3_result_error(context, zErr, -1);
81669 }
81670
81671 /*
81672 ** This procedure generates VDBE code for a single invocation of either the
81673 ** sqlite_detach() or sqlite_attach() SQL user functions.
81674 */
81675 static void codeAttach(
81676   Parse *pParse,       /* The parser context */
81677   int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
81678   FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
81679   Expr *pAuthArg,      /* Expression to pass to authorization callback */
81680   Expr *pFilename,     /* Name of database file */
81681   Expr *pDbname,       /* Name of the database to use internally */
81682   Expr *pKey           /* Database key for encryption extension */
81683 ){
81684   int rc;
81685   NameContext sName;
81686   Vdbe *v;
81687   sqlite3* db = pParse->db;
81688   int regArgs;
81689
81690   memset(&sName, 0, sizeof(NameContext));
81691   sName.pParse = pParse;
81692
81693   if( 
81694       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
81695       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
81696       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
81697   ){
81698     pParse->nErr++;
81699     goto attach_end;
81700   }
81701
81702 #ifndef SQLITE_OMIT_AUTHORIZATION
81703   if( pAuthArg ){
81704     char *zAuthArg;
81705     if( pAuthArg->op==TK_STRING ){
81706       zAuthArg = pAuthArg->u.zToken;
81707     }else{
81708       zAuthArg = 0;
81709     }
81710     rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
81711     if(rc!=SQLITE_OK ){
81712       goto attach_end;
81713     }
81714   }
81715 #endif /* SQLITE_OMIT_AUTHORIZATION */
81716
81717
81718   v = sqlite3GetVdbe(pParse);
81719   regArgs = sqlite3GetTempRange(pParse, 4);
81720   sqlite3ExprCode(pParse, pFilename, regArgs);
81721   sqlite3ExprCode(pParse, pDbname, regArgs+1);
81722   sqlite3ExprCode(pParse, pKey, regArgs+2);
81723
81724   assert( v || db->mallocFailed );
81725   if( v ){
81726     sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
81727     assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
81728     sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
81729     sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
81730
81731     /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
81732     ** statement only). For DETACH, set it to false (expire all existing
81733     ** statements).
81734     */
81735     sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
81736   }
81737   
81738 attach_end:
81739   sqlite3ExprDelete(db, pFilename);
81740   sqlite3ExprDelete(db, pDbname);
81741   sqlite3ExprDelete(db, pKey);
81742 }
81743
81744 /*
81745 ** Called by the parser to compile a DETACH statement.
81746 **
81747 **     DETACH pDbname
81748 */
81749 SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
81750   static const FuncDef detach_func = {
81751     1,                /* nArg */
81752     SQLITE_UTF8,      /* iPrefEnc */
81753     0,                /* flags */
81754     0,                /* pUserData */
81755     0,                /* pNext */
81756     detachFunc,       /* xFunc */
81757     0,                /* xStep */
81758     0,                /* xFinalize */
81759     "sqlite_detach",  /* zName */
81760     0,                /* pHash */
81761     0                 /* pDestructor */
81762   };
81763   codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
81764 }
81765
81766 /*
81767 ** Called by the parser to compile an ATTACH statement.
81768 **
81769 **     ATTACH p AS pDbname KEY pKey
81770 */
81771 SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
81772   static const FuncDef attach_func = {
81773     3,                /* nArg */
81774     SQLITE_UTF8,      /* iPrefEnc */
81775     0,                /* flags */
81776     0,                /* pUserData */
81777     0,                /* pNext */
81778     attachFunc,       /* xFunc */
81779     0,                /* xStep */
81780     0,                /* xFinalize */
81781     "sqlite_attach",  /* zName */
81782     0,                /* pHash */
81783     0                 /* pDestructor */
81784   };
81785   codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
81786 }
81787 #endif /* SQLITE_OMIT_ATTACH */
81788
81789 /*
81790 ** Initialize a DbFixer structure.  This routine must be called prior
81791 ** to passing the structure to one of the sqliteFixAAAA() routines below.
81792 **
81793 ** The return value indicates whether or not fixation is required.  TRUE
81794 ** means we do need to fix the database references, FALSE means we do not.
81795 */
81796 SQLITE_PRIVATE int sqlite3FixInit(
81797   DbFixer *pFix,      /* The fixer to be initialized */
81798   Parse *pParse,      /* Error messages will be written here */
81799   int iDb,            /* This is the database that must be used */
81800   const char *zType,  /* "view", "trigger", or "index" */
81801   const Token *pName  /* Name of the view, trigger, or index */
81802 ){
81803   sqlite3 *db;
81804
81805   if( NEVER(iDb<0) || iDb==1 ) return 0;
81806   db = pParse->db;
81807   assert( db->nDb>iDb );
81808   pFix->pParse = pParse;
81809   pFix->zDb = db->aDb[iDb].zName;
81810   pFix->pSchema = db->aDb[iDb].pSchema;
81811   pFix->zType = zType;
81812   pFix->pName = pName;
81813   return 1;
81814 }
81815
81816 /*
81817 ** The following set of routines walk through the parse tree and assign
81818 ** a specific database to all table references where the database name
81819 ** was left unspecified in the original SQL statement.  The pFix structure
81820 ** must have been initialized by a prior call to sqlite3FixInit().
81821 **
81822 ** These routines are used to make sure that an index, trigger, or
81823 ** view in one database does not refer to objects in a different database.
81824 ** (Exception: indices, triggers, and views in the TEMP database are
81825 ** allowed to refer to anything.)  If a reference is explicitly made
81826 ** to an object in a different database, an error message is added to
81827 ** pParse->zErrMsg and these routines return non-zero.  If everything
81828 ** checks out, these routines return 0.
81829 */
81830 SQLITE_PRIVATE int sqlite3FixSrcList(
81831   DbFixer *pFix,       /* Context of the fixation */
81832   SrcList *pList       /* The Source list to check and modify */
81833 ){
81834   int i;
81835   const char *zDb;
81836   struct SrcList_item *pItem;
81837
81838   if( NEVER(pList==0) ) return 0;
81839   zDb = pFix->zDb;
81840   for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
81841     if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
81842       sqlite3ErrorMsg(pFix->pParse,
81843          "%s %T cannot reference objects in database %s",
81844          pFix->zType, pFix->pName, pItem->zDatabase);
81845       return 1;
81846     }
81847     sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
81848     pItem->zDatabase = 0;
81849     pItem->pSchema = pFix->pSchema;
81850 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
81851     if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
81852     if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
81853 #endif
81854   }
81855   return 0;
81856 }
81857 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
81858 SQLITE_PRIVATE int sqlite3FixSelect(
81859   DbFixer *pFix,       /* Context of the fixation */
81860   Select *pSelect      /* The SELECT statement to be fixed to one database */
81861 ){
81862   while( pSelect ){
81863     if( sqlite3FixExprList(pFix, pSelect->pEList) ){
81864       return 1;
81865     }
81866     if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
81867       return 1;
81868     }
81869     if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
81870       return 1;
81871     }
81872     if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
81873       return 1;
81874     }
81875     pSelect = pSelect->pPrior;
81876   }
81877   return 0;
81878 }
81879 SQLITE_PRIVATE int sqlite3FixExpr(
81880   DbFixer *pFix,     /* Context of the fixation */
81881   Expr *pExpr        /* The expression to be fixed to one database */
81882 ){
81883   while( pExpr ){
81884     if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ) break;
81885     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
81886       if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
81887     }else{
81888       if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
81889     }
81890     if( sqlite3FixExpr(pFix, pExpr->pRight) ){
81891       return 1;
81892     }
81893     pExpr = pExpr->pLeft;
81894   }
81895   return 0;
81896 }
81897 SQLITE_PRIVATE int sqlite3FixExprList(
81898   DbFixer *pFix,     /* Context of the fixation */
81899   ExprList *pList    /* The expression to be fixed to one database */
81900 ){
81901   int i;
81902   struct ExprList_item *pItem;
81903   if( pList==0 ) return 0;
81904   for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
81905     if( sqlite3FixExpr(pFix, pItem->pExpr) ){
81906       return 1;
81907     }
81908   }
81909   return 0;
81910 }
81911 #endif
81912
81913 #ifndef SQLITE_OMIT_TRIGGER
81914 SQLITE_PRIVATE int sqlite3FixTriggerStep(
81915   DbFixer *pFix,     /* Context of the fixation */
81916   TriggerStep *pStep /* The trigger step be fixed to one database */
81917 ){
81918   while( pStep ){
81919     if( sqlite3FixSelect(pFix, pStep->pSelect) ){
81920       return 1;
81921     }
81922     if( sqlite3FixExpr(pFix, pStep->pWhere) ){
81923       return 1;
81924     }
81925     if( sqlite3FixExprList(pFix, pStep->pExprList) ){
81926       return 1;
81927     }
81928     pStep = pStep->pNext;
81929   }
81930   return 0;
81931 }
81932 #endif
81933
81934 /************** End of attach.c **********************************************/
81935 /************** Begin file auth.c ********************************************/
81936 /*
81937 ** 2003 January 11
81938 **
81939 ** The author disclaims copyright to this source code.  In place of
81940 ** a legal notice, here is a blessing:
81941 **
81942 **    May you do good and not evil.
81943 **    May you find forgiveness for yourself and forgive others.
81944 **    May you share freely, never taking more than you give.
81945 **
81946 *************************************************************************
81947 ** This file contains code used to implement the sqlite3_set_authorizer()
81948 ** API.  This facility is an optional feature of the library.  Embedded
81949 ** systems that do not need this facility may omit it by recompiling
81950 ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
81951 */
81952
81953 /*
81954 ** All of the code in this file may be omitted by defining a single
81955 ** macro.
81956 */
81957 #ifndef SQLITE_OMIT_AUTHORIZATION
81958
81959 /*
81960 ** Set or clear the access authorization function.
81961 **
81962 ** The access authorization function is be called during the compilation
81963 ** phase to verify that the user has read and/or write access permission on
81964 ** various fields of the database.  The first argument to the auth function
81965 ** is a copy of the 3rd argument to this routine.  The second argument
81966 ** to the auth function is one of these constants:
81967 **
81968 **       SQLITE_CREATE_INDEX
81969 **       SQLITE_CREATE_TABLE
81970 **       SQLITE_CREATE_TEMP_INDEX
81971 **       SQLITE_CREATE_TEMP_TABLE
81972 **       SQLITE_CREATE_TEMP_TRIGGER
81973 **       SQLITE_CREATE_TEMP_VIEW
81974 **       SQLITE_CREATE_TRIGGER
81975 **       SQLITE_CREATE_VIEW
81976 **       SQLITE_DELETE
81977 **       SQLITE_DROP_INDEX
81978 **       SQLITE_DROP_TABLE
81979 **       SQLITE_DROP_TEMP_INDEX
81980 **       SQLITE_DROP_TEMP_TABLE
81981 **       SQLITE_DROP_TEMP_TRIGGER
81982 **       SQLITE_DROP_TEMP_VIEW
81983 **       SQLITE_DROP_TRIGGER
81984 **       SQLITE_DROP_VIEW
81985 **       SQLITE_INSERT
81986 **       SQLITE_PRAGMA
81987 **       SQLITE_READ
81988 **       SQLITE_SELECT
81989 **       SQLITE_TRANSACTION
81990 **       SQLITE_UPDATE
81991 **
81992 ** The third and fourth arguments to the auth function are the name of
81993 ** the table and the column that are being accessed.  The auth function
81994 ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
81995 ** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
81996 ** means that the SQL statement will never-run - the sqlite3_exec() call
81997 ** will return with an error.  SQLITE_IGNORE means that the SQL statement
81998 ** should run but attempts to read the specified column will return NULL
81999 ** and attempts to write the column will be ignored.
82000 **
82001 ** Setting the auth function to NULL disables this hook.  The default
82002 ** setting of the auth function is NULL.
82003 */
82004 SQLITE_API int sqlite3_set_authorizer(
82005   sqlite3 *db,
82006   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
82007   void *pArg
82008 ){
82009   sqlite3_mutex_enter(db->mutex);
82010   db->xAuth = xAuth;
82011   db->pAuthArg = pArg;
82012   sqlite3ExpirePreparedStatements(db);
82013   sqlite3_mutex_leave(db->mutex);
82014   return SQLITE_OK;
82015 }
82016
82017 /*
82018 ** Write an error message into pParse->zErrMsg that explains that the
82019 ** user-supplied authorization function returned an illegal value.
82020 */
82021 static void sqliteAuthBadReturnCode(Parse *pParse){
82022   sqlite3ErrorMsg(pParse, "authorizer malfunction");
82023   pParse->rc = SQLITE_ERROR;
82024 }
82025
82026 /*
82027 ** Invoke the authorization callback for permission to read column zCol from
82028 ** table zTab in database zDb. This function assumes that an authorization
82029 ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
82030 **
82031 ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
82032 ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
82033 ** is treated as SQLITE_DENY. In this case an error is left in pParse.
82034 */
82035 SQLITE_PRIVATE int sqlite3AuthReadCol(
82036   Parse *pParse,                  /* The parser context */
82037   const char *zTab,               /* Table name */
82038   const char *zCol,               /* Column name */
82039   int iDb                         /* Index of containing database. */
82040 ){
82041   sqlite3 *db = pParse->db;       /* Database handle */
82042   char *zDb = db->aDb[iDb].zName; /* Name of attached database */
82043   int rc;                         /* Auth callback return code */
82044
82045   rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
82046   if( rc==SQLITE_DENY ){
82047     if( db->nDb>2 || iDb!=0 ){
82048       sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
82049     }else{
82050       sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
82051     }
82052     pParse->rc = SQLITE_AUTH;
82053   }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
82054     sqliteAuthBadReturnCode(pParse);
82055   }
82056   return rc;
82057 }
82058
82059 /*
82060 ** The pExpr should be a TK_COLUMN expression.  The table referred to
82061 ** is in pTabList or else it is the NEW or OLD table of a trigger.  
82062 ** Check to see if it is OK to read this particular column.
82063 **
82064 ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN 
82065 ** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
82066 ** then generate an error.
82067 */
82068 SQLITE_PRIVATE void sqlite3AuthRead(
82069   Parse *pParse,        /* The parser context */
82070   Expr *pExpr,          /* The expression to check authorization on */
82071   Schema *pSchema,      /* The schema of the expression */
82072   SrcList *pTabList     /* All table that pExpr might refer to */
82073 ){
82074   sqlite3 *db = pParse->db;
82075   Table *pTab = 0;      /* The table being read */
82076   const char *zCol;     /* Name of the column of the table */
82077   int iSrc;             /* Index in pTabList->a[] of table being read */
82078   int iDb;              /* The index of the database the expression refers to */
82079   int iCol;             /* Index of column in table */
82080
82081   if( db->xAuth==0 ) return;
82082   iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
82083   if( iDb<0 ){
82084     /* An attempt to read a column out of a subquery or other
82085     ** temporary table. */
82086     return;
82087   }
82088
82089   assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
82090   if( pExpr->op==TK_TRIGGER ){
82091     pTab = pParse->pTriggerTab;
82092   }else{
82093     assert( pTabList );
82094     for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
82095       if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
82096         pTab = pTabList->a[iSrc].pTab;
82097         break;
82098       }
82099     }
82100   }
82101   iCol = pExpr->iColumn;
82102   if( NEVER(pTab==0) ) return;
82103
82104   if( iCol>=0 ){
82105     assert( iCol<pTab->nCol );
82106     zCol = pTab->aCol[iCol].zName;
82107   }else if( pTab->iPKey>=0 ){
82108     assert( pTab->iPKey<pTab->nCol );
82109     zCol = pTab->aCol[pTab->iPKey].zName;
82110   }else{
82111     zCol = "ROWID";
82112   }
82113   assert( iDb>=0 && iDb<db->nDb );
82114   if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
82115     pExpr->op = TK_NULL;
82116   }
82117 }
82118
82119 /*
82120 ** Do an authorization check using the code and arguments given.  Return
82121 ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
82122 ** is returned, then the error count and error message in pParse are
82123 ** modified appropriately.
82124 */
82125 SQLITE_PRIVATE int sqlite3AuthCheck(
82126   Parse *pParse,
82127   int code,
82128   const char *zArg1,
82129   const char *zArg2,
82130   const char *zArg3
82131 ){
82132   sqlite3 *db = pParse->db;
82133   int rc;
82134
82135   /* Don't do any authorization checks if the database is initialising
82136   ** or if the parser is being invoked from within sqlite3_declare_vtab.
82137   */
82138   if( db->init.busy || IN_DECLARE_VTAB ){
82139     return SQLITE_OK;
82140   }
82141
82142   if( db->xAuth==0 ){
82143     return SQLITE_OK;
82144   }
82145   rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
82146   if( rc==SQLITE_DENY ){
82147     sqlite3ErrorMsg(pParse, "not authorized");
82148     pParse->rc = SQLITE_AUTH;
82149   }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
82150     rc = SQLITE_DENY;
82151     sqliteAuthBadReturnCode(pParse);
82152   }
82153   return rc;
82154 }
82155
82156 /*
82157 ** Push an authorization context.  After this routine is called, the
82158 ** zArg3 argument to authorization callbacks will be zContext until
82159 ** popped.  Or if pParse==0, this routine is a no-op.
82160 */
82161 SQLITE_PRIVATE void sqlite3AuthContextPush(
82162   Parse *pParse,
82163   AuthContext *pContext, 
82164   const char *zContext
82165 ){
82166   assert( pParse );
82167   pContext->pParse = pParse;
82168   pContext->zAuthContext = pParse->zAuthContext;
82169   pParse->zAuthContext = zContext;
82170 }
82171
82172 /*
82173 ** Pop an authorization context that was previously pushed
82174 ** by sqlite3AuthContextPush
82175 */
82176 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
82177   if( pContext->pParse ){
82178     pContext->pParse->zAuthContext = pContext->zAuthContext;
82179     pContext->pParse = 0;
82180   }
82181 }
82182
82183 #endif /* SQLITE_OMIT_AUTHORIZATION */
82184
82185 /************** End of auth.c ************************************************/
82186 /************** Begin file build.c *******************************************/
82187 /*
82188 ** 2001 September 15
82189 **
82190 ** The author disclaims copyright to this source code.  In place of
82191 ** a legal notice, here is a blessing:
82192 **
82193 **    May you do good and not evil.
82194 **    May you find forgiveness for yourself and forgive others.
82195 **    May you share freely, never taking more than you give.
82196 **
82197 *************************************************************************
82198 ** This file contains C code routines that are called by the SQLite parser
82199 ** when syntax rules are reduced.  The routines in this file handle the
82200 ** following kinds of SQL syntax:
82201 **
82202 **     CREATE TABLE
82203 **     DROP TABLE
82204 **     CREATE INDEX
82205 **     DROP INDEX
82206 **     creating ID lists
82207 **     BEGIN TRANSACTION
82208 **     COMMIT
82209 **     ROLLBACK
82210 */
82211
82212 /*
82213 ** This routine is called when a new SQL statement is beginning to
82214 ** be parsed.  Initialize the pParse structure as needed.
82215 */
82216 SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
82217   pParse->explain = (u8)explainFlag;
82218   pParse->nVar = 0;
82219 }
82220
82221 #ifndef SQLITE_OMIT_SHARED_CACHE
82222 /*
82223 ** The TableLock structure is only used by the sqlite3TableLock() and
82224 ** codeTableLocks() functions.
82225 */
82226 struct TableLock {
82227   int iDb;             /* The database containing the table to be locked */
82228   int iTab;            /* The root page of the table to be locked */
82229   u8 isWriteLock;      /* True for write lock.  False for a read lock */
82230   const char *zName;   /* Name of the table */
82231 };
82232
82233 /*
82234 ** Record the fact that we want to lock a table at run-time.  
82235 **
82236 ** The table to be locked has root page iTab and is found in database iDb.
82237 ** A read or a write lock can be taken depending on isWritelock.
82238 **
82239 ** This routine just records the fact that the lock is desired.  The
82240 ** code to make the lock occur is generated by a later call to
82241 ** codeTableLocks() which occurs during sqlite3FinishCoding().
82242 */
82243 SQLITE_PRIVATE void sqlite3TableLock(
82244   Parse *pParse,     /* Parsing context */
82245   int iDb,           /* Index of the database containing the table to lock */
82246   int iTab,          /* Root page number of the table to be locked */
82247   u8 isWriteLock,    /* True for a write lock */
82248   const char *zName  /* Name of the table to be locked */
82249 ){
82250   Parse *pToplevel = sqlite3ParseToplevel(pParse);
82251   int i;
82252   int nBytes;
82253   TableLock *p;
82254   assert( iDb>=0 );
82255
82256   for(i=0; i<pToplevel->nTableLock; i++){
82257     p = &pToplevel->aTableLock[i];
82258     if( p->iDb==iDb && p->iTab==iTab ){
82259       p->isWriteLock = (p->isWriteLock || isWriteLock);
82260       return;
82261     }
82262   }
82263
82264   nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
82265   pToplevel->aTableLock =
82266       sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
82267   if( pToplevel->aTableLock ){
82268     p = &pToplevel->aTableLock[pToplevel->nTableLock++];
82269     p->iDb = iDb;
82270     p->iTab = iTab;
82271     p->isWriteLock = isWriteLock;
82272     p->zName = zName;
82273   }else{
82274     pToplevel->nTableLock = 0;
82275     pToplevel->db->mallocFailed = 1;
82276   }
82277 }
82278
82279 /*
82280 ** Code an OP_TableLock instruction for each table locked by the
82281 ** statement (configured by calls to sqlite3TableLock()).
82282 */
82283 static void codeTableLocks(Parse *pParse){
82284   int i;
82285   Vdbe *pVdbe; 
82286
82287   pVdbe = sqlite3GetVdbe(pParse);
82288   assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
82289
82290   for(i=0; i<pParse->nTableLock; i++){
82291     TableLock *p = &pParse->aTableLock[i];
82292     int p1 = p->iDb;
82293     sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
82294                       p->zName, P4_STATIC);
82295   }
82296 }
82297 #else
82298   #define codeTableLocks(x)
82299 #endif
82300
82301 /*
82302 ** This routine is called after a single SQL statement has been
82303 ** parsed and a VDBE program to execute that statement has been
82304 ** prepared.  This routine puts the finishing touches on the
82305 ** VDBE program and resets the pParse structure for the next
82306 ** parse.
82307 **
82308 ** Note that if an error occurred, it might be the case that
82309 ** no VDBE code was generated.
82310 */
82311 SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
82312   sqlite3 *db;
82313   Vdbe *v;
82314
82315   assert( pParse->pToplevel==0 );
82316   db = pParse->db;
82317   if( db->mallocFailed ) return;
82318   if( pParse->nested ) return;
82319   if( pParse->nErr ) return;
82320
82321   /* Begin by generating some termination code at the end of the
82322   ** vdbe program
82323   */
82324   v = sqlite3GetVdbe(pParse);
82325   assert( !pParse->isMultiWrite 
82326        || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
82327   if( v ){
82328     sqlite3VdbeAddOp0(v, OP_Halt);
82329
82330     /* The cookie mask contains one bit for each database file open.
82331     ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
82332     ** set for each database that is used.  Generate code to start a
82333     ** transaction on each used database and to verify the schema cookie
82334     ** on each used database.
82335     */
82336     if( pParse->cookieGoto>0 ){
82337       yDbMask mask;
82338       int iDb;
82339       sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
82340       for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
82341         if( (mask & pParse->cookieMask)==0 ) continue;
82342         sqlite3VdbeUsesBtree(v, iDb);
82343         sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
82344         if( db->init.busy==0 ){
82345           assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
82346           sqlite3VdbeAddOp3(v, OP_VerifyCookie,
82347                             iDb, pParse->cookieValue[iDb],
82348                             db->aDb[iDb].pSchema->iGeneration);
82349         }
82350       }
82351 #ifndef SQLITE_OMIT_VIRTUALTABLE
82352       {
82353         int i;
82354         for(i=0; i<pParse->nVtabLock; i++){
82355           char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
82356           sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
82357         }
82358         pParse->nVtabLock = 0;
82359       }
82360 #endif
82361
82362       /* Once all the cookies have been verified and transactions opened, 
82363       ** obtain the required table-locks. This is a no-op unless the 
82364       ** shared-cache feature is enabled.
82365       */
82366       codeTableLocks(pParse);
82367
82368       /* Initialize any AUTOINCREMENT data structures required.
82369       */
82370       sqlite3AutoincrementBegin(pParse);
82371
82372       /* Finally, jump back to the beginning of the executable code. */
82373       sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
82374     }
82375   }
82376
82377
82378   /* Get the VDBE program ready for execution
82379   */
82380   if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
82381 #ifdef SQLITE_DEBUG
82382     FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
82383     sqlite3VdbeTrace(v, trace);
82384 #endif
82385     assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
82386     /* A minimum of one cursor is required if autoincrement is used
82387     *  See ticket [a696379c1f08866] */
82388     if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
82389     sqlite3VdbeMakeReady(v, pParse);
82390     pParse->rc = SQLITE_DONE;
82391     pParse->colNamesSet = 0;
82392   }else{
82393     pParse->rc = SQLITE_ERROR;
82394   }
82395   pParse->nTab = 0;
82396   pParse->nMem = 0;
82397   pParse->nSet = 0;
82398   pParse->nVar = 0;
82399   pParse->cookieMask = 0;
82400   pParse->cookieGoto = 0;
82401 }
82402
82403 /*
82404 ** Run the parser and code generator recursively in order to generate
82405 ** code for the SQL statement given onto the end of the pParse context
82406 ** currently under construction.  When the parser is run recursively
82407 ** this way, the final OP_Halt is not appended and other initialization
82408 ** and finalization steps are omitted because those are handling by the
82409 ** outermost parser.
82410 **
82411 ** Not everything is nestable.  This facility is designed to permit
82412 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
82413 ** care if you decide to try to use this routine for some other purposes.
82414 */
82415 SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
82416   va_list ap;
82417   char *zSql;
82418   char *zErrMsg = 0;
82419   sqlite3 *db = pParse->db;
82420 # define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
82421   char saveBuf[SAVE_SZ];
82422
82423   if( pParse->nErr ) return;
82424   assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
82425   va_start(ap, zFormat);
82426   zSql = sqlite3VMPrintf(db, zFormat, ap);
82427   va_end(ap);
82428   if( zSql==0 ){
82429     return;   /* A malloc must have failed */
82430   }
82431   pParse->nested++;
82432   memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
82433   memset(&pParse->nVar, 0, SAVE_SZ);
82434   sqlite3RunParser(pParse, zSql, &zErrMsg);
82435   sqlite3DbFree(db, zErrMsg);
82436   sqlite3DbFree(db, zSql);
82437   memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
82438   pParse->nested--;
82439 }
82440
82441 /*
82442 ** Locate the in-memory structure that describes a particular database
82443 ** table given the name of that table and (optionally) the name of the
82444 ** database containing the table.  Return NULL if not found.
82445 **
82446 ** If zDatabase is 0, all databases are searched for the table and the
82447 ** first matching table is returned.  (No checking for duplicate table
82448 ** names is done.)  The search order is TEMP first, then MAIN, then any
82449 ** auxiliary databases added using the ATTACH command.
82450 **
82451 ** See also sqlite3LocateTable().
82452 */
82453 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
82454   Table *p = 0;
82455   int i;
82456   int nName;
82457   assert( zName!=0 );
82458   nName = sqlite3Strlen30(zName);
82459   /* All mutexes are required for schema access.  Make sure we hold them. */
82460   assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
82461   for(i=OMIT_TEMPDB; i<db->nDb; i++){
82462     int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
82463     if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
82464     assert( sqlite3SchemaMutexHeld(db, j, 0) );
82465     p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
82466     if( p ) break;
82467   }
82468   return p;
82469 }
82470
82471 /*
82472 ** Locate the in-memory structure that describes a particular database
82473 ** table given the name of that table and (optionally) the name of the
82474 ** database containing the table.  Return NULL if not found.  Also leave an
82475 ** error message in pParse->zErrMsg.
82476 **
82477 ** The difference between this routine and sqlite3FindTable() is that this
82478 ** routine leaves an error message in pParse->zErrMsg where
82479 ** sqlite3FindTable() does not.
82480 */
82481 SQLITE_PRIVATE Table *sqlite3LocateTable(
82482   Parse *pParse,         /* context in which to report errors */
82483   int isView,            /* True if looking for a VIEW rather than a TABLE */
82484   const char *zName,     /* Name of the table we are looking for */
82485   const char *zDbase     /* Name of the database.  Might be NULL */
82486 ){
82487   Table *p;
82488
82489   /* Read the database schema. If an error occurs, leave an error message
82490   ** and code in pParse and return NULL. */
82491   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
82492     return 0;
82493   }
82494
82495   p = sqlite3FindTable(pParse->db, zName, zDbase);
82496   if( p==0 ){
82497     const char *zMsg = isView ? "no such view" : "no such table";
82498     if( zDbase ){
82499       sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
82500     }else{
82501       sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
82502     }
82503     pParse->checkSchema = 1;
82504   }
82505   return p;
82506 }
82507
82508 /*
82509 ** Locate the table identified by *p.
82510 **
82511 ** This is a wrapper around sqlite3LocateTable(). The difference between
82512 ** sqlite3LocateTable() and this function is that this function restricts
82513 ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
82514 ** non-NULL if it is part of a view or trigger program definition. See
82515 ** sqlite3FixSrcList() for details.
82516 */
82517 SQLITE_PRIVATE Table *sqlite3LocateTableItem(
82518   Parse *pParse, 
82519   int isView, 
82520   struct SrcList_item *p
82521 ){
82522   const char *zDb;
82523   assert( p->pSchema==0 || p->zDatabase==0 );
82524   if( p->pSchema ){
82525     int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
82526     zDb = pParse->db->aDb[iDb].zName;
82527   }else{
82528     zDb = p->zDatabase;
82529   }
82530   return sqlite3LocateTable(pParse, isView, p->zName, zDb);
82531 }
82532
82533 /*
82534 ** Locate the in-memory structure that describes 
82535 ** a particular index given the name of that index
82536 ** and the name of the database that contains the index.
82537 ** Return NULL if not found.
82538 **
82539 ** If zDatabase is 0, all databases are searched for the
82540 ** table and the first matching index is returned.  (No checking
82541 ** for duplicate index names is done.)  The search order is
82542 ** TEMP first, then MAIN, then any auxiliary databases added
82543 ** using the ATTACH command.
82544 */
82545 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
82546   Index *p = 0;
82547   int i;
82548   int nName = sqlite3Strlen30(zName);
82549   /* All mutexes are required for schema access.  Make sure we hold them. */
82550   assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
82551   for(i=OMIT_TEMPDB; i<db->nDb; i++){
82552     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
82553     Schema *pSchema = db->aDb[j].pSchema;
82554     assert( pSchema );
82555     if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
82556     assert( sqlite3SchemaMutexHeld(db, j, 0) );
82557     p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
82558     if( p ) break;
82559   }
82560   return p;
82561 }
82562
82563 /*
82564 ** Reclaim the memory used by an index
82565 */
82566 static void freeIndex(sqlite3 *db, Index *p){
82567 #ifndef SQLITE_OMIT_ANALYZE
82568   sqlite3DeleteIndexSamples(db, p);
82569 #endif
82570   sqlite3DbFree(db, p->zColAff);
82571   sqlite3DbFree(db, p);
82572 }
82573
82574 /*
82575 ** For the index called zIdxName which is found in the database iDb,
82576 ** unlike that index from its Table then remove the index from
82577 ** the index hash table and free all memory structures associated
82578 ** with the index.
82579 */
82580 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
82581   Index *pIndex;
82582   int len;
82583   Hash *pHash;
82584
82585   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
82586   pHash = &db->aDb[iDb].pSchema->idxHash;
82587   len = sqlite3Strlen30(zIdxName);
82588   pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
82589   if( ALWAYS(pIndex) ){
82590     if( pIndex->pTable->pIndex==pIndex ){
82591       pIndex->pTable->pIndex = pIndex->pNext;
82592     }else{
82593       Index *p;
82594       /* Justification of ALWAYS();  The index must be on the list of
82595       ** indices. */
82596       p = pIndex->pTable->pIndex;
82597       while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
82598       if( ALWAYS(p && p->pNext==pIndex) ){
82599         p->pNext = pIndex->pNext;
82600       }
82601     }
82602     freeIndex(db, pIndex);
82603   }
82604   db->flags |= SQLITE_InternChanges;
82605 }
82606
82607 /*
82608 ** Look through the list of open database files in db->aDb[] and if
82609 ** any have been closed, remove them from the list.  Reallocate the
82610 ** db->aDb[] structure to a smaller size, if possible.
82611 **
82612 ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
82613 ** are never candidates for being collapsed.
82614 */
82615 SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
82616   int i, j;
82617   for(i=j=2; i<db->nDb; i++){
82618     struct Db *pDb = &db->aDb[i];
82619     if( pDb->pBt==0 ){
82620       sqlite3DbFree(db, pDb->zName);
82621       pDb->zName = 0;
82622       continue;
82623     }
82624     if( j<i ){
82625       db->aDb[j] = db->aDb[i];
82626     }
82627     j++;
82628   }
82629   memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
82630   db->nDb = j;
82631   if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
82632     memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
82633     sqlite3DbFree(db, db->aDb);
82634     db->aDb = db->aDbStatic;
82635   }
82636 }
82637
82638 /*
82639 ** Reset the schema for the database at index iDb.  Also reset the
82640 ** TEMP schema.
82641 */
82642 SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
82643   Db *pDb;
82644   assert( iDb<db->nDb );
82645
82646   /* Case 1:  Reset the single schema identified by iDb */
82647   pDb = &db->aDb[iDb];
82648   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
82649   assert( pDb->pSchema!=0 );
82650   sqlite3SchemaClear(pDb->pSchema);
82651
82652   /* If any database other than TEMP is reset, then also reset TEMP
82653   ** since TEMP might be holding triggers that reference tables in the
82654   ** other database.
82655   */
82656   if( iDb!=1 ){
82657     pDb = &db->aDb[1];
82658     assert( pDb->pSchema!=0 );
82659     sqlite3SchemaClear(pDb->pSchema);
82660   }
82661   return;
82662 }
82663
82664 /*
82665 ** Erase all schema information from all attached databases (including
82666 ** "main" and "temp") for a single database connection.
82667 */
82668 SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
82669   int i;
82670   sqlite3BtreeEnterAll(db);
82671   for(i=0; i<db->nDb; i++){
82672     Db *pDb = &db->aDb[i];
82673     if( pDb->pSchema ){
82674       sqlite3SchemaClear(pDb->pSchema);
82675     }
82676   }
82677   db->flags &= ~SQLITE_InternChanges;
82678   sqlite3VtabUnlockList(db);
82679   sqlite3BtreeLeaveAll(db);
82680   sqlite3CollapseDatabaseArray(db);
82681 }
82682
82683 /*
82684 ** This routine is called when a commit occurs.
82685 */
82686 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
82687   db->flags &= ~SQLITE_InternChanges;
82688 }
82689
82690 /*
82691 ** Delete memory allocated for the column names of a table or view (the
82692 ** Table.aCol[] array).
82693 */
82694 static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
82695   int i;
82696   Column *pCol;
82697   assert( pTable!=0 );
82698   if( (pCol = pTable->aCol)!=0 ){
82699     for(i=0; i<pTable->nCol; i++, pCol++){
82700       sqlite3DbFree(db, pCol->zName);
82701       sqlite3ExprDelete(db, pCol->pDflt);
82702       sqlite3DbFree(db, pCol->zDflt);
82703       sqlite3DbFree(db, pCol->zType);
82704       sqlite3DbFree(db, pCol->zColl);
82705     }
82706     sqlite3DbFree(db, pTable->aCol);
82707   }
82708 }
82709
82710 /*
82711 ** Remove the memory data structures associated with the given
82712 ** Table.  No changes are made to disk by this routine.
82713 **
82714 ** This routine just deletes the data structure.  It does not unlink
82715 ** the table data structure from the hash table.  But it does destroy
82716 ** memory structures of the indices and foreign keys associated with 
82717 ** the table.
82718 **
82719 ** The db parameter is optional.  It is needed if the Table object 
82720 ** contains lookaside memory.  (Table objects in the schema do not use
82721 ** lookaside memory, but some ephemeral Table objects do.)  Or the
82722 ** db parameter can be used with db->pnBytesFreed to measure the memory
82723 ** used by the Table object.
82724 */
82725 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
82726   Index *pIndex, *pNext;
82727   TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
82728
82729   assert( !pTable || pTable->nRef>0 );
82730
82731   /* Do not delete the table until the reference count reaches zero. */
82732   if( !pTable ) return;
82733   if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
82734
82735   /* Record the number of outstanding lookaside allocations in schema Tables
82736   ** prior to doing any free() operations.  Since schema Tables do not use
82737   ** lookaside, this number should not change. */
82738   TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
82739                          db->lookaside.nOut : 0 );
82740
82741   /* Delete all indices associated with this table. */
82742   for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
82743     pNext = pIndex->pNext;
82744     assert( pIndex->pSchema==pTable->pSchema );
82745     if( !db || db->pnBytesFreed==0 ){
82746       char *zName = pIndex->zName; 
82747       TESTONLY ( Index *pOld = ) sqlite3HashInsert(
82748          &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0
82749       );
82750       assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
82751       assert( pOld==pIndex || pOld==0 );
82752     }
82753     freeIndex(db, pIndex);
82754   }
82755
82756   /* Delete any foreign keys attached to this table. */
82757   sqlite3FkDelete(db, pTable);
82758
82759   /* Delete the Table structure itself.
82760   */
82761   sqliteDeleteColumnNames(db, pTable);
82762   sqlite3DbFree(db, pTable->zName);
82763   sqlite3DbFree(db, pTable->zColAff);
82764   sqlite3SelectDelete(db, pTable->pSelect);
82765 #ifndef SQLITE_OMIT_CHECK
82766   sqlite3ExprListDelete(db, pTable->pCheck);
82767 #endif
82768 #ifndef SQLITE_OMIT_VIRTUALTABLE
82769   sqlite3VtabClear(db, pTable);
82770 #endif
82771   sqlite3DbFree(db, pTable);
82772
82773   /* Verify that no lookaside memory was used by schema tables */
82774   assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
82775 }
82776
82777 /*
82778 ** Unlink the given table from the hash tables and the delete the
82779 ** table structure with all its indices and foreign keys.
82780 */
82781 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
82782   Table *p;
82783   Db *pDb;
82784
82785   assert( db!=0 );
82786   assert( iDb>=0 && iDb<db->nDb );
82787   assert( zTabName );
82788   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
82789   testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
82790   pDb = &db->aDb[iDb];
82791   p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
82792                         sqlite3Strlen30(zTabName),0);
82793   sqlite3DeleteTable(db, p);
82794   db->flags |= SQLITE_InternChanges;
82795 }
82796
82797 /*
82798 ** Given a token, return a string that consists of the text of that
82799 ** token.  Space to hold the returned string
82800 ** is obtained from sqliteMalloc() and must be freed by the calling
82801 ** function.
82802 **
82803 ** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
82804 ** surround the body of the token are removed.
82805 **
82806 ** Tokens are often just pointers into the original SQL text and so
82807 ** are not \000 terminated and are not persistent.  The returned string
82808 ** is \000 terminated and is persistent.
82809 */
82810 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
82811   char *zName;
82812   if( pName ){
82813     zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
82814     sqlite3Dequote(zName);
82815   }else{
82816     zName = 0;
82817   }
82818   return zName;
82819 }
82820
82821 /*
82822 ** Open the sqlite_master table stored in database number iDb for
82823 ** writing. The table is opened using cursor 0.
82824 */
82825 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
82826   Vdbe *v = sqlite3GetVdbe(p);
82827   sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
82828   sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
82829   sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32);  /* 5 column table */
82830   if( p->nTab==0 ){
82831     p->nTab = 1;
82832   }
82833 }
82834
82835 /*
82836 ** Parameter zName points to a nul-terminated buffer containing the name
82837 ** of a database ("main", "temp" or the name of an attached db). This
82838 ** function returns the index of the named database in db->aDb[], or
82839 ** -1 if the named db cannot be found.
82840 */
82841 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
82842   int i = -1;         /* Database number */
82843   if( zName ){
82844     Db *pDb;
82845     int n = sqlite3Strlen30(zName);
82846     for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
82847       if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) && 
82848           0==sqlite3StrICmp(pDb->zName, zName) ){
82849         break;
82850       }
82851     }
82852   }
82853   return i;
82854 }
82855
82856 /*
82857 ** The token *pName contains the name of a database (either "main" or
82858 ** "temp" or the name of an attached db). This routine returns the
82859 ** index of the named database in db->aDb[], or -1 if the named db 
82860 ** does not exist.
82861 */
82862 SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
82863   int i;                               /* Database number */
82864   char *zName;                         /* Name we are searching for */
82865   zName = sqlite3NameFromToken(db, pName);
82866   i = sqlite3FindDbName(db, zName);
82867   sqlite3DbFree(db, zName);
82868   return i;
82869 }
82870
82871 /* The table or view or trigger name is passed to this routine via tokens
82872 ** pName1 and pName2. If the table name was fully qualified, for example:
82873 **
82874 ** CREATE TABLE xxx.yyy (...);
82875 ** 
82876 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
82877 ** the table name is not fully qualified, i.e.:
82878 **
82879 ** CREATE TABLE yyy(...);
82880 **
82881 ** Then pName1 is set to "yyy" and pName2 is "".
82882 **
82883 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
82884 ** pName2) that stores the unqualified table name.  The index of the
82885 ** database "xxx" is returned.
82886 */
82887 SQLITE_PRIVATE int sqlite3TwoPartName(
82888   Parse *pParse,      /* Parsing and code generating context */
82889   Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
82890   Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
82891   Token **pUnqual     /* Write the unqualified object name here */
82892 ){
82893   int iDb;                    /* Database holding the object */
82894   sqlite3 *db = pParse->db;
82895
82896   if( ALWAYS(pName2!=0) && pName2->n>0 ){
82897     if( db->init.busy ) {
82898       sqlite3ErrorMsg(pParse, "corrupt database");
82899       pParse->nErr++;
82900       return -1;
82901     }
82902     *pUnqual = pName2;
82903     iDb = sqlite3FindDb(db, pName1);
82904     if( iDb<0 ){
82905       sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
82906       pParse->nErr++;
82907       return -1;
82908     }
82909   }else{
82910     assert( db->init.iDb==0 || db->init.busy );
82911     iDb = db->init.iDb;
82912     *pUnqual = pName1;
82913   }
82914   return iDb;
82915 }
82916
82917 /*
82918 ** This routine is used to check if the UTF-8 string zName is a legal
82919 ** unqualified name for a new schema object (table, index, view or
82920 ** trigger). All names are legal except those that begin with the string
82921 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
82922 ** is reserved for internal use.
82923 */
82924 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
82925   if( !pParse->db->init.busy && pParse->nested==0 
82926           && (pParse->db->flags & SQLITE_WriteSchema)==0
82927           && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
82928     sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
82929     return SQLITE_ERROR;
82930   }
82931   return SQLITE_OK;
82932 }
82933
82934 /*
82935 ** Begin constructing a new table representation in memory.  This is
82936 ** the first of several action routines that get called in response
82937 ** to a CREATE TABLE statement.  In particular, this routine is called
82938 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
82939 ** flag is true if the table should be stored in the auxiliary database
82940 ** file instead of in the main database file.  This is normally the case
82941 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
82942 ** CREATE and TABLE.
82943 **
82944 ** The new table record is initialized and put in pParse->pNewTable.
82945 ** As more of the CREATE TABLE statement is parsed, additional action
82946 ** routines will be called to add more information to this record.
82947 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
82948 ** is called to complete the construction of the new table record.
82949 */
82950 SQLITE_PRIVATE void sqlite3StartTable(
82951   Parse *pParse,   /* Parser context */
82952   Token *pName1,   /* First part of the name of the table or view */
82953   Token *pName2,   /* Second part of the name of the table or view */
82954   int isTemp,      /* True if this is a TEMP table */
82955   int isView,      /* True if this is a VIEW */
82956   int isVirtual,   /* True if this is a VIRTUAL table */
82957   int noErr        /* Do nothing if table already exists */
82958 ){
82959   Table *pTable;
82960   char *zName = 0; /* The name of the new table */
82961   sqlite3 *db = pParse->db;
82962   Vdbe *v;
82963   int iDb;         /* Database number to create the table in */
82964   Token *pName;    /* Unqualified name of the table to create */
82965
82966   /* The table or view name to create is passed to this routine via tokens
82967   ** pName1 and pName2. If the table name was fully qualified, for example:
82968   **
82969   ** CREATE TABLE xxx.yyy (...);
82970   ** 
82971   ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
82972   ** the table name is not fully qualified, i.e.:
82973   **
82974   ** CREATE TABLE yyy(...);
82975   **
82976   ** Then pName1 is set to "yyy" and pName2 is "".
82977   **
82978   ** The call below sets the pName pointer to point at the token (pName1 or
82979   ** pName2) that stores the unqualified table name. The variable iDb is
82980   ** set to the index of the database that the table or view is to be
82981   ** created in.
82982   */
82983   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
82984   if( iDb<0 ) return;
82985   if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
82986     /* If creating a temp table, the name may not be qualified. Unless 
82987     ** the database name is "temp" anyway.  */
82988     sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
82989     return;
82990   }
82991   if( !OMIT_TEMPDB && isTemp ) iDb = 1;
82992
82993   pParse->sNameToken = *pName;
82994   zName = sqlite3NameFromToken(db, pName);
82995   if( zName==0 ) return;
82996   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
82997     goto begin_table_error;
82998   }
82999   if( db->init.iDb==1 ) isTemp = 1;
83000 #ifndef SQLITE_OMIT_AUTHORIZATION
83001   assert( (isTemp & 1)==isTemp );
83002   {
83003     int code;
83004     char *zDb = db->aDb[iDb].zName;
83005     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
83006       goto begin_table_error;
83007     }
83008     if( isView ){
83009       if( !OMIT_TEMPDB && isTemp ){
83010         code = SQLITE_CREATE_TEMP_VIEW;
83011       }else{
83012         code = SQLITE_CREATE_VIEW;
83013       }
83014     }else{
83015       if( !OMIT_TEMPDB && isTemp ){
83016         code = SQLITE_CREATE_TEMP_TABLE;
83017       }else{
83018         code = SQLITE_CREATE_TABLE;
83019       }
83020     }
83021     if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
83022       goto begin_table_error;
83023     }
83024   }
83025 #endif
83026
83027   /* Make sure the new table name does not collide with an existing
83028   ** index or table name in the same database.  Issue an error message if
83029   ** it does. The exception is if the statement being parsed was passed
83030   ** to an sqlite3_declare_vtab() call. In that case only the column names
83031   ** and types will be used, so there is no need to test for namespace
83032   ** collisions.
83033   */
83034   if( !IN_DECLARE_VTAB ){
83035     char *zDb = db->aDb[iDb].zName;
83036     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
83037       goto begin_table_error;
83038     }
83039     pTable = sqlite3FindTable(db, zName, zDb);
83040     if( pTable ){
83041       if( !noErr ){
83042         sqlite3ErrorMsg(pParse, "table %T already exists", pName);
83043       }else{
83044         assert( !db->init.busy );
83045         sqlite3CodeVerifySchema(pParse, iDb);
83046       }
83047       goto begin_table_error;
83048     }
83049     if( sqlite3FindIndex(db, zName, zDb)!=0 ){
83050       sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
83051       goto begin_table_error;
83052     }
83053   }
83054
83055   pTable = sqlite3DbMallocZero(db, sizeof(Table));
83056   if( pTable==0 ){
83057     db->mallocFailed = 1;
83058     pParse->rc = SQLITE_NOMEM;
83059     pParse->nErr++;
83060     goto begin_table_error;
83061   }
83062   pTable->zName = zName;
83063   pTable->iPKey = -1;
83064   pTable->pSchema = db->aDb[iDb].pSchema;
83065   pTable->nRef = 1;
83066   pTable->nRowEst = 1000000;
83067   assert( pParse->pNewTable==0 );
83068   pParse->pNewTable = pTable;
83069
83070   /* If this is the magic sqlite_sequence table used by autoincrement,
83071   ** then record a pointer to this table in the main database structure
83072   ** so that INSERT can find the table easily.
83073   */
83074 #ifndef SQLITE_OMIT_AUTOINCREMENT
83075   if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
83076     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
83077     pTable->pSchema->pSeqTab = pTable;
83078   }
83079 #endif
83080
83081   /* Begin generating the code that will insert the table record into
83082   ** the SQLITE_MASTER table.  Note in particular that we must go ahead
83083   ** and allocate the record number for the table entry now.  Before any
83084   ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
83085   ** indices to be created and the table record must come before the 
83086   ** indices.  Hence, the record number for the table must be allocated
83087   ** now.
83088   */
83089   if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
83090     int j1;
83091     int fileFormat;
83092     int reg1, reg2, reg3;
83093     sqlite3BeginWriteOperation(pParse, 0, iDb);
83094
83095 #ifndef SQLITE_OMIT_VIRTUALTABLE
83096     if( isVirtual ){
83097       sqlite3VdbeAddOp0(v, OP_VBegin);
83098     }
83099 #endif
83100
83101     /* If the file format and encoding in the database have not been set, 
83102     ** set them now.
83103     */
83104     reg1 = pParse->regRowid = ++pParse->nMem;
83105     reg2 = pParse->regRoot = ++pParse->nMem;
83106     reg3 = ++pParse->nMem;
83107     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
83108     sqlite3VdbeUsesBtree(v, iDb);
83109     j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
83110     fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
83111                   1 : SQLITE_MAX_FILE_FORMAT;
83112     sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
83113     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
83114     sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
83115     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
83116     sqlite3VdbeJumpHere(v, j1);
83117
83118     /* This just creates a place-holder record in the sqlite_master table.
83119     ** The record created does not contain anything yet.  It will be replaced
83120     ** by the real entry in code generated at sqlite3EndTable().
83121     **
83122     ** The rowid for the new entry is left in register pParse->regRowid.
83123     ** The root page number of the new table is left in reg pParse->regRoot.
83124     ** The rowid and root page number values are needed by the code that
83125     ** sqlite3EndTable will generate.
83126     */
83127 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
83128     if( isView || isVirtual ){
83129       sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
83130     }else
83131 #endif
83132     {
83133       sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
83134     }
83135     sqlite3OpenMasterTable(pParse, iDb);
83136     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
83137     sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
83138     sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
83139     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
83140     sqlite3VdbeAddOp0(v, OP_Close);
83141   }
83142
83143   /* Normal (non-error) return. */
83144   return;
83145
83146   /* If an error occurs, we jump here */
83147 begin_table_error:
83148   sqlite3DbFree(db, zName);
83149   return;
83150 }
83151
83152 /*
83153 ** This macro is used to compare two strings in a case-insensitive manner.
83154 ** It is slightly faster than calling sqlite3StrICmp() directly, but
83155 ** produces larger code.
83156 **
83157 ** WARNING: This macro is not compatible with the strcmp() family. It
83158 ** returns true if the two strings are equal, otherwise false.
83159 */
83160 #define STRICMP(x, y) (\
83161 sqlite3UpperToLower[*(unsigned char *)(x)]==   \
83162 sqlite3UpperToLower[*(unsigned char *)(y)]     \
83163 && sqlite3StrICmp((x)+1,(y)+1)==0 )
83164
83165 /*
83166 ** Add a new column to the table currently being constructed.
83167 **
83168 ** The parser calls this routine once for each column declaration
83169 ** in a CREATE TABLE statement.  sqlite3StartTable() gets called
83170 ** first to get things going.  Then this routine is called for each
83171 ** column.
83172 */
83173 SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
83174   Table *p;
83175   int i;
83176   char *z;
83177   Column *pCol;
83178   sqlite3 *db = pParse->db;
83179   if( (p = pParse->pNewTable)==0 ) return;
83180 #if SQLITE_MAX_COLUMN
83181   if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
83182     sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
83183     return;
83184   }
83185 #endif
83186   z = sqlite3NameFromToken(db, pName);
83187   if( z==0 ) return;
83188   for(i=0; i<p->nCol; i++){
83189     if( STRICMP(z, p->aCol[i].zName) ){
83190       sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
83191       sqlite3DbFree(db, z);
83192       return;
83193     }
83194   }
83195   if( (p->nCol & 0x7)==0 ){
83196     Column *aNew;
83197     aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
83198     if( aNew==0 ){
83199       sqlite3DbFree(db, z);
83200       return;
83201     }
83202     p->aCol = aNew;
83203   }
83204   pCol = &p->aCol[p->nCol];
83205   memset(pCol, 0, sizeof(p->aCol[0]));
83206   pCol->zName = z;
83207  
83208   /* If there is no type specified, columns have the default affinity
83209   ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
83210   ** be called next to set pCol->affinity correctly.
83211   */
83212   pCol->affinity = SQLITE_AFF_NONE;
83213   p->nCol++;
83214 }
83215
83216 /*
83217 ** This routine is called by the parser while in the middle of
83218 ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
83219 ** been seen on a column.  This routine sets the notNull flag on
83220 ** the column currently under construction.
83221 */
83222 SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
83223   Table *p;
83224   p = pParse->pNewTable;
83225   if( p==0 || NEVER(p->nCol<1) ) return;
83226   p->aCol[p->nCol-1].notNull = (u8)onError;
83227 }
83228
83229 /*
83230 ** Scan the column type name zType (length nType) and return the
83231 ** associated affinity type.
83232 **
83233 ** This routine does a case-independent search of zType for the 
83234 ** substrings in the following table. If one of the substrings is
83235 ** found, the corresponding affinity is returned. If zType contains
83236 ** more than one of the substrings, entries toward the top of 
83237 ** the table take priority. For example, if zType is 'BLOBINT', 
83238 ** SQLITE_AFF_INTEGER is returned.
83239 **
83240 ** Substring     | Affinity
83241 ** --------------------------------
83242 ** 'INT'         | SQLITE_AFF_INTEGER
83243 ** 'CHAR'        | SQLITE_AFF_TEXT
83244 ** 'CLOB'        | SQLITE_AFF_TEXT
83245 ** 'TEXT'        | SQLITE_AFF_TEXT
83246 ** 'BLOB'        | SQLITE_AFF_NONE
83247 ** 'REAL'        | SQLITE_AFF_REAL
83248 ** 'FLOA'        | SQLITE_AFF_REAL
83249 ** 'DOUB'        | SQLITE_AFF_REAL
83250 **
83251 ** If none of the substrings in the above table are found,
83252 ** SQLITE_AFF_NUMERIC is returned.
83253 */
83254 SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn){
83255   u32 h = 0;
83256   char aff = SQLITE_AFF_NUMERIC;
83257
83258   if( zIn ) while( zIn[0] ){
83259     h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
83260     zIn++;
83261     if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
83262       aff = SQLITE_AFF_TEXT; 
83263     }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
83264       aff = SQLITE_AFF_TEXT;
83265     }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
83266       aff = SQLITE_AFF_TEXT;
83267     }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
83268         && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
83269       aff = SQLITE_AFF_NONE;
83270 #ifndef SQLITE_OMIT_FLOATING_POINT
83271     }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
83272         && aff==SQLITE_AFF_NUMERIC ){
83273       aff = SQLITE_AFF_REAL;
83274     }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
83275         && aff==SQLITE_AFF_NUMERIC ){
83276       aff = SQLITE_AFF_REAL;
83277     }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
83278         && aff==SQLITE_AFF_NUMERIC ){
83279       aff = SQLITE_AFF_REAL;
83280 #endif
83281     }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
83282       aff = SQLITE_AFF_INTEGER;
83283       break;
83284     }
83285   }
83286
83287   return aff;
83288 }
83289
83290 /*
83291 ** This routine is called by the parser while in the middle of
83292 ** parsing a CREATE TABLE statement.  The pFirst token is the first
83293 ** token in the sequence of tokens that describe the type of the
83294 ** column currently under construction.   pLast is the last token
83295 ** in the sequence.  Use this information to construct a string
83296 ** that contains the typename of the column and store that string
83297 ** in zType.
83298 */ 
83299 SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
83300   Table *p;
83301   Column *pCol;
83302
83303   p = pParse->pNewTable;
83304   if( p==0 || NEVER(p->nCol<1) ) return;
83305   pCol = &p->aCol[p->nCol-1];
83306   assert( pCol->zType==0 );
83307   pCol->zType = sqlite3NameFromToken(pParse->db, pType);
83308   pCol->affinity = sqlite3AffinityType(pCol->zType);
83309 }
83310
83311 /*
83312 ** The expression is the default value for the most recently added column
83313 ** of the table currently under construction.
83314 **
83315 ** Default value expressions must be constant.  Raise an exception if this
83316 ** is not the case.
83317 **
83318 ** This routine is called by the parser while in the middle of
83319 ** parsing a CREATE TABLE statement.
83320 */
83321 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
83322   Table *p;
83323   Column *pCol;
83324   sqlite3 *db = pParse->db;
83325   p = pParse->pNewTable;
83326   if( p!=0 ){
83327     pCol = &(p->aCol[p->nCol-1]);
83328     if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
83329       sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
83330           pCol->zName);
83331     }else{
83332       /* A copy of pExpr is used instead of the original, as pExpr contains
83333       ** tokens that point to volatile memory. The 'span' of the expression
83334       ** is required by pragma table_info.
83335       */
83336       sqlite3ExprDelete(db, pCol->pDflt);
83337       pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
83338       sqlite3DbFree(db, pCol->zDflt);
83339       pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
83340                                      (int)(pSpan->zEnd - pSpan->zStart));
83341     }
83342   }
83343   sqlite3ExprDelete(db, pSpan->pExpr);
83344 }
83345
83346 /*
83347 ** Designate the PRIMARY KEY for the table.  pList is a list of names 
83348 ** of columns that form the primary key.  If pList is NULL, then the
83349 ** most recently added column of the table is the primary key.
83350 **
83351 ** A table can have at most one primary key.  If the table already has
83352 ** a primary key (and this is the second primary key) then create an
83353 ** error.
83354 **
83355 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
83356 ** then we will try to use that column as the rowid.  Set the Table.iPKey
83357 ** field of the table under construction to be the index of the
83358 ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
83359 ** no INTEGER PRIMARY KEY.
83360 **
83361 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
83362 ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
83363 */
83364 SQLITE_PRIVATE void sqlite3AddPrimaryKey(
83365   Parse *pParse,    /* Parsing context */
83366   ExprList *pList,  /* List of field names to be indexed */
83367   int onError,      /* What to do with a uniqueness conflict */
83368   int autoInc,      /* True if the AUTOINCREMENT keyword is present */
83369   int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
83370 ){
83371   Table *pTab = pParse->pNewTable;
83372   char *zType = 0;
83373   int iCol = -1, i;
83374   if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
83375   if( pTab->tabFlags & TF_HasPrimaryKey ){
83376     sqlite3ErrorMsg(pParse, 
83377       "table \"%s\" has more than one primary key", pTab->zName);
83378     goto primary_key_exit;
83379   }
83380   pTab->tabFlags |= TF_HasPrimaryKey;
83381   if( pList==0 ){
83382     iCol = pTab->nCol - 1;
83383     pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
83384   }else{
83385     for(i=0; i<pList->nExpr; i++){
83386       for(iCol=0; iCol<pTab->nCol; iCol++){
83387         if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
83388           break;
83389         }
83390       }
83391       if( iCol<pTab->nCol ){
83392         pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
83393       }
83394     }
83395     if( pList->nExpr>1 ) iCol = -1;
83396   }
83397   if( iCol>=0 && iCol<pTab->nCol ){
83398     zType = pTab->aCol[iCol].zType;
83399   }
83400   if( zType && sqlite3StrICmp(zType, "INTEGER")==0
83401         && sortOrder==SQLITE_SO_ASC ){
83402     pTab->iPKey = iCol;
83403     pTab->keyConf = (u8)onError;
83404     assert( autoInc==0 || autoInc==1 );
83405     pTab->tabFlags |= autoInc*TF_Autoincrement;
83406   }else if( autoInc ){
83407 #ifndef SQLITE_OMIT_AUTOINCREMENT
83408     sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
83409        "INTEGER PRIMARY KEY");
83410 #endif
83411   }else{
83412     Index *p;
83413     p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
83414     if( p ){
83415       p->autoIndex = 2;
83416     }
83417     pList = 0;
83418   }
83419
83420 primary_key_exit:
83421   sqlite3ExprListDelete(pParse->db, pList);
83422   return;
83423 }
83424
83425 /*
83426 ** Add a new CHECK constraint to the table currently under construction.
83427 */
83428 SQLITE_PRIVATE void sqlite3AddCheckConstraint(
83429   Parse *pParse,    /* Parsing context */
83430   Expr *pCheckExpr  /* The check expression */
83431 ){
83432 #ifndef SQLITE_OMIT_CHECK
83433   Table *pTab = pParse->pNewTable;
83434   if( pTab && !IN_DECLARE_VTAB ){
83435     pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
83436     if( pParse->constraintName.n ){
83437       sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
83438     }
83439   }else
83440 #endif
83441   {
83442     sqlite3ExprDelete(pParse->db, pCheckExpr);
83443   }
83444 }
83445
83446 /*
83447 ** Set the collation function of the most recently parsed table column
83448 ** to the CollSeq given.
83449 */
83450 SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
83451   Table *p;
83452   int i;
83453   char *zColl;              /* Dequoted name of collation sequence */
83454   sqlite3 *db;
83455
83456   if( (p = pParse->pNewTable)==0 ) return;
83457   i = p->nCol-1;
83458   db = pParse->db;
83459   zColl = sqlite3NameFromToken(db, pToken);
83460   if( !zColl ) return;
83461
83462   if( sqlite3LocateCollSeq(pParse, zColl) ){
83463     Index *pIdx;
83464     p->aCol[i].zColl = zColl;
83465   
83466     /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
83467     ** then an index may have been created on this column before the
83468     ** collation type was added. Correct this if it is the case.
83469     */
83470     for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
83471       assert( pIdx->nColumn==1 );
83472       if( pIdx->aiColumn[0]==i ){
83473         pIdx->azColl[0] = p->aCol[i].zColl;
83474       }
83475     }
83476   }else{
83477     sqlite3DbFree(db, zColl);
83478   }
83479 }
83480
83481 /*
83482 ** This function returns the collation sequence for database native text
83483 ** encoding identified by the string zName, length nName.
83484 **
83485 ** If the requested collation sequence is not available, or not available
83486 ** in the database native encoding, the collation factory is invoked to
83487 ** request it. If the collation factory does not supply such a sequence,
83488 ** and the sequence is available in another text encoding, then that is
83489 ** returned instead.
83490 **
83491 ** If no versions of the requested collations sequence are available, or
83492 ** another error occurs, NULL is returned and an error message written into
83493 ** pParse.
83494 **
83495 ** This routine is a wrapper around sqlite3FindCollSeq().  This routine
83496 ** invokes the collation factory if the named collation cannot be found
83497 ** and generates an error message.
83498 **
83499 ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
83500 */
83501 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
83502   sqlite3 *db = pParse->db;
83503   u8 enc = ENC(db);
83504   u8 initbusy = db->init.busy;
83505   CollSeq *pColl;
83506
83507   pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
83508   if( !initbusy && (!pColl || !pColl->xCmp) ){
83509     pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
83510   }
83511
83512   return pColl;
83513 }
83514
83515
83516 /*
83517 ** Generate code that will increment the schema cookie.
83518 **
83519 ** The schema cookie is used to determine when the schema for the
83520 ** database changes.  After each schema change, the cookie value
83521 ** changes.  When a process first reads the schema it records the
83522 ** cookie.  Thereafter, whenever it goes to access the database,
83523 ** it checks the cookie to make sure the schema has not changed
83524 ** since it was last read.
83525 **
83526 ** This plan is not completely bullet-proof.  It is possible for
83527 ** the schema to change multiple times and for the cookie to be
83528 ** set back to prior value.  But schema changes are infrequent
83529 ** and the probability of hitting the same cookie value is only
83530 ** 1 chance in 2^32.  So we're safe enough.
83531 */
83532 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
83533   int r1 = sqlite3GetTempReg(pParse);
83534   sqlite3 *db = pParse->db;
83535   Vdbe *v = pParse->pVdbe;
83536   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
83537   sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
83538   sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
83539   sqlite3ReleaseTempReg(pParse, r1);
83540 }
83541
83542 /*
83543 ** Measure the number of characters needed to output the given
83544 ** identifier.  The number returned includes any quotes used
83545 ** but does not include the null terminator.
83546 **
83547 ** The estimate is conservative.  It might be larger that what is
83548 ** really needed.
83549 */
83550 static int identLength(const char *z){
83551   int n;
83552   for(n=0; *z; n++, z++){
83553     if( *z=='"' ){ n++; }
83554   }
83555   return n + 2;
83556 }
83557
83558 /*
83559 ** The first parameter is a pointer to an output buffer. The second 
83560 ** parameter is a pointer to an integer that contains the offset at
83561 ** which to write into the output buffer. This function copies the
83562 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
83563 ** to the specified offset in the buffer and updates *pIdx to refer
83564 ** to the first byte after the last byte written before returning.
83565 ** 
83566 ** If the string zSignedIdent consists entirely of alpha-numeric
83567 ** characters, does not begin with a digit and is not an SQL keyword,
83568 ** then it is copied to the output buffer exactly as it is. Otherwise,
83569 ** it is quoted using double-quotes.
83570 */
83571 static void identPut(char *z, int *pIdx, char *zSignedIdent){
83572   unsigned char *zIdent = (unsigned char*)zSignedIdent;
83573   int i, j, needQuote;
83574   i = *pIdx;
83575
83576   for(j=0; zIdent[j]; j++){
83577     if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
83578   }
83579   needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
83580   if( !needQuote ){
83581     needQuote = zIdent[j];
83582   }
83583
83584   if( needQuote ) z[i++] = '"';
83585   for(j=0; zIdent[j]; j++){
83586     z[i++] = zIdent[j];
83587     if( zIdent[j]=='"' ) z[i++] = '"';
83588   }
83589   if( needQuote ) z[i++] = '"';
83590   z[i] = 0;
83591   *pIdx = i;
83592 }
83593
83594 /*
83595 ** Generate a CREATE TABLE statement appropriate for the given
83596 ** table.  Memory to hold the text of the statement is obtained
83597 ** from sqliteMalloc() and must be freed by the calling function.
83598 */
83599 static char *createTableStmt(sqlite3 *db, Table *p){
83600   int i, k, n;
83601   char *zStmt;
83602   char *zSep, *zSep2, *zEnd;
83603   Column *pCol;
83604   n = 0;
83605   for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
83606     n += identLength(pCol->zName) + 5;
83607   }
83608   n += identLength(p->zName);
83609   if( n<50 ){ 
83610     zSep = "";
83611     zSep2 = ",";
83612     zEnd = ")";
83613   }else{
83614     zSep = "\n  ";
83615     zSep2 = ",\n  ";
83616     zEnd = "\n)";
83617   }
83618   n += 35 + 6*p->nCol;
83619   zStmt = sqlite3DbMallocRaw(0, n);
83620   if( zStmt==0 ){
83621     db->mallocFailed = 1;
83622     return 0;
83623   }
83624   sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
83625   k = sqlite3Strlen30(zStmt);
83626   identPut(zStmt, &k, p->zName);
83627   zStmt[k++] = '(';
83628   for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
83629     static const char * const azType[] = {
83630         /* SQLITE_AFF_TEXT    */ " TEXT",
83631         /* SQLITE_AFF_NONE    */ "",
83632         /* SQLITE_AFF_NUMERIC */ " NUM",
83633         /* SQLITE_AFF_INTEGER */ " INT",
83634         /* SQLITE_AFF_REAL    */ " REAL"
83635     };
83636     int len;
83637     const char *zType;
83638
83639     sqlite3_snprintf(n-k, &zStmt[k], zSep);
83640     k += sqlite3Strlen30(&zStmt[k]);
83641     zSep = zSep2;
83642     identPut(zStmt, &k, pCol->zName);
83643     assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
83644     assert( pCol->affinity-SQLITE_AFF_TEXT < ArraySize(azType) );
83645     testcase( pCol->affinity==SQLITE_AFF_TEXT );
83646     testcase( pCol->affinity==SQLITE_AFF_NONE );
83647     testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
83648     testcase( pCol->affinity==SQLITE_AFF_INTEGER );
83649     testcase( pCol->affinity==SQLITE_AFF_REAL );
83650     
83651     zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
83652     len = sqlite3Strlen30(zType);
83653     assert( pCol->affinity==SQLITE_AFF_NONE 
83654             || pCol->affinity==sqlite3AffinityType(zType) );
83655     memcpy(&zStmt[k], zType, len);
83656     k += len;
83657     assert( k<=n );
83658   }
83659   sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
83660   return zStmt;
83661 }
83662
83663 /*
83664 ** This routine is called to report the final ")" that terminates
83665 ** a CREATE TABLE statement.
83666 **
83667 ** The table structure that other action routines have been building
83668 ** is added to the internal hash tables, assuming no errors have
83669 ** occurred.
83670 **
83671 ** An entry for the table is made in the master table on disk, unless
83672 ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
83673 ** it means we are reading the sqlite_master table because we just
83674 ** connected to the database or because the sqlite_master table has
83675 ** recently changed, so the entry for this table already exists in
83676 ** the sqlite_master table.  We do not want to create it again.
83677 **
83678 ** If the pSelect argument is not NULL, it means that this routine
83679 ** was called to create a table generated from a 
83680 ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
83681 ** the new table will match the result set of the SELECT.
83682 */
83683 SQLITE_PRIVATE void sqlite3EndTable(
83684   Parse *pParse,          /* Parse context */
83685   Token *pCons,           /* The ',' token after the last column defn. */
83686   Token *pEnd,            /* The final ')' token in the CREATE TABLE */
83687   Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
83688 ){
83689   Table *p;
83690   sqlite3 *db = pParse->db;
83691   int iDb;
83692
83693   if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
83694     return;
83695   }
83696   p = pParse->pNewTable;
83697   if( p==0 ) return;
83698
83699   assert( !db->init.busy || !pSelect );
83700
83701   iDb = sqlite3SchemaToIndex(db, p->pSchema);
83702
83703 #ifndef SQLITE_OMIT_CHECK
83704   /* Resolve names in all CHECK constraint expressions.
83705   */
83706   if( p->pCheck ){
83707     SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
83708     NameContext sNC;                /* Name context for pParse->pNewTable */
83709     ExprList *pList;                /* List of all CHECK constraints */
83710     int i;                          /* Loop counter */
83711
83712     memset(&sNC, 0, sizeof(sNC));
83713     memset(&sSrc, 0, sizeof(sSrc));
83714     sSrc.nSrc = 1;
83715     sSrc.a[0].zName = p->zName;
83716     sSrc.a[0].pTab = p;
83717     sSrc.a[0].iCursor = -1;
83718     sNC.pParse = pParse;
83719     sNC.pSrcList = &sSrc;
83720     sNC.ncFlags = NC_IsCheck;
83721     pList = p->pCheck;
83722     for(i=0; i<pList->nExpr; i++){
83723       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
83724         return;
83725       }
83726     }
83727   }
83728 #endif /* !defined(SQLITE_OMIT_CHECK) */
83729
83730   /* If the db->init.busy is 1 it means we are reading the SQL off the
83731   ** "sqlite_master" or "sqlite_temp_master" table on the disk.
83732   ** So do not write to the disk again.  Extract the root page number
83733   ** for the table from the db->init.newTnum field.  (The page number
83734   ** should have been put there by the sqliteOpenCb routine.)
83735   */
83736   if( db->init.busy ){
83737     p->tnum = db->init.newTnum;
83738   }
83739
83740   /* If not initializing, then create a record for the new table
83741   ** in the SQLITE_MASTER table of the database.
83742   **
83743   ** If this is a TEMPORARY table, write the entry into the auxiliary
83744   ** file instead of into the main database file.
83745   */
83746   if( !db->init.busy ){
83747     int n;
83748     Vdbe *v;
83749     char *zType;    /* "view" or "table" */
83750     char *zType2;   /* "VIEW" or "TABLE" */
83751     char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
83752
83753     v = sqlite3GetVdbe(pParse);
83754     if( NEVER(v==0) ) return;
83755
83756     sqlite3VdbeAddOp1(v, OP_Close, 0);
83757
83758     /* 
83759     ** Initialize zType for the new view or table.
83760     */
83761     if( p->pSelect==0 ){
83762       /* A regular table */
83763       zType = "table";
83764       zType2 = "TABLE";
83765 #ifndef SQLITE_OMIT_VIEW
83766     }else{
83767       /* A view */
83768       zType = "view";
83769       zType2 = "VIEW";
83770 #endif
83771     }
83772
83773     /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
83774     ** statement to populate the new table. The root-page number for the
83775     ** new table is in register pParse->regRoot.
83776     **
83777     ** Once the SELECT has been coded by sqlite3Select(), it is in a
83778     ** suitable state to query for the column names and types to be used
83779     ** by the new table.
83780     **
83781     ** A shared-cache write-lock is not required to write to the new table,
83782     ** as a schema-lock must have already been obtained to create it. Since
83783     ** a schema-lock excludes all other database users, the write-lock would
83784     ** be redundant.
83785     */
83786     if( pSelect ){
83787       SelectDest dest;
83788       Table *pSelTab;
83789
83790       assert(pParse->nTab==1);
83791       sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
83792       sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
83793       pParse->nTab = 2;
83794       sqlite3SelectDestInit(&dest, SRT_Table, 1);
83795       sqlite3Select(pParse, pSelect, &dest);
83796       sqlite3VdbeAddOp1(v, OP_Close, 1);
83797       if( pParse->nErr==0 ){
83798         pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
83799         if( pSelTab==0 ) return;
83800         assert( p->aCol==0 );
83801         p->nCol = pSelTab->nCol;
83802         p->aCol = pSelTab->aCol;
83803         pSelTab->nCol = 0;
83804         pSelTab->aCol = 0;
83805         sqlite3DeleteTable(db, pSelTab);
83806       }
83807     }
83808
83809     /* Compute the complete text of the CREATE statement */
83810     if( pSelect ){
83811       zStmt = createTableStmt(db, p);
83812     }else{
83813       n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
83814       zStmt = sqlite3MPrintf(db, 
83815           "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
83816       );
83817     }
83818
83819     /* A slot for the record has already been allocated in the 
83820     ** SQLITE_MASTER table.  We just need to update that slot with all
83821     ** the information we've collected.
83822     */
83823     sqlite3NestedParse(pParse,
83824       "UPDATE %Q.%s "
83825          "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
83826        "WHERE rowid=#%d",
83827       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
83828       zType,
83829       p->zName,
83830       p->zName,
83831       pParse->regRoot,
83832       zStmt,
83833       pParse->regRowid
83834     );
83835     sqlite3DbFree(db, zStmt);
83836     sqlite3ChangeCookie(pParse, iDb);
83837
83838 #ifndef SQLITE_OMIT_AUTOINCREMENT
83839     /* Check to see if we need to create an sqlite_sequence table for
83840     ** keeping track of autoincrement keys.
83841     */
83842     if( p->tabFlags & TF_Autoincrement ){
83843       Db *pDb = &db->aDb[iDb];
83844       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
83845       if( pDb->pSchema->pSeqTab==0 ){
83846         sqlite3NestedParse(pParse,
83847           "CREATE TABLE %Q.sqlite_sequence(name,seq)",
83848           pDb->zName
83849         );
83850       }
83851     }
83852 #endif
83853
83854     /* Reparse everything to update our internal data structures */
83855     sqlite3VdbeAddParseSchemaOp(v, iDb,
83856                sqlite3MPrintf(db, "tbl_name='%q'", p->zName));
83857   }
83858
83859
83860   /* Add the table to the in-memory representation of the database.
83861   */
83862   if( db->init.busy ){
83863     Table *pOld;
83864     Schema *pSchema = p->pSchema;
83865     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
83866     pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
83867                              sqlite3Strlen30(p->zName),p);
83868     if( pOld ){
83869       assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
83870       db->mallocFailed = 1;
83871       return;
83872     }
83873     pParse->pNewTable = 0;
83874     db->flags |= SQLITE_InternChanges;
83875
83876 #ifndef SQLITE_OMIT_ALTERTABLE
83877     if( !p->pSelect ){
83878       const char *zName = (const char *)pParse->sNameToken.z;
83879       int nName;
83880       assert( !pSelect && pCons && pEnd );
83881       if( pCons->z==0 ){
83882         pCons = pEnd;
83883       }
83884       nName = (int)((const char *)pCons->z - zName);
83885       p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
83886     }
83887 #endif
83888   }
83889 }
83890
83891 #ifndef SQLITE_OMIT_VIEW
83892 /*
83893 ** The parser calls this routine in order to create a new VIEW
83894 */
83895 SQLITE_PRIVATE void sqlite3CreateView(
83896   Parse *pParse,     /* The parsing context */
83897   Token *pBegin,     /* The CREATE token that begins the statement */
83898   Token *pName1,     /* The token that holds the name of the view */
83899   Token *pName2,     /* The token that holds the name of the view */
83900   Select *pSelect,   /* A SELECT statement that will become the new view */
83901   int isTemp,        /* TRUE for a TEMPORARY view */
83902   int noErr          /* Suppress error messages if VIEW already exists */
83903 ){
83904   Table *p;
83905   int n;
83906   const char *z;
83907   Token sEnd;
83908   DbFixer sFix;
83909   Token *pName = 0;
83910   int iDb;
83911   sqlite3 *db = pParse->db;
83912
83913   if( pParse->nVar>0 ){
83914     sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
83915     sqlite3SelectDelete(db, pSelect);
83916     return;
83917   }
83918   sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
83919   p = pParse->pNewTable;
83920   if( p==0 || pParse->nErr ){
83921     sqlite3SelectDelete(db, pSelect);
83922     return;
83923   }
83924   sqlite3TwoPartName(pParse, pName1, pName2, &pName);
83925   iDb = sqlite3SchemaToIndex(db, p->pSchema);
83926   if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
83927     && sqlite3FixSelect(&sFix, pSelect)
83928   ){
83929     sqlite3SelectDelete(db, pSelect);
83930     return;
83931   }
83932
83933   /* Make a copy of the entire SELECT statement that defines the view.
83934   ** This will force all the Expr.token.z values to be dynamically
83935   ** allocated rather than point to the input string - which means that
83936   ** they will persist after the current sqlite3_exec() call returns.
83937   */
83938   p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
83939   sqlite3SelectDelete(db, pSelect);
83940   if( db->mallocFailed ){
83941     return;
83942   }
83943   if( !db->init.busy ){
83944     sqlite3ViewGetColumnNames(pParse, p);
83945   }
83946
83947   /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
83948   ** the end.
83949   */
83950   sEnd = pParse->sLastToken;
83951   if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
83952     sEnd.z += sEnd.n;
83953   }
83954   sEnd.n = 0;
83955   n = (int)(sEnd.z - pBegin->z);
83956   z = pBegin->z;
83957   while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
83958   sEnd.z = &z[n-1];
83959   sEnd.n = 1;
83960
83961   /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
83962   sqlite3EndTable(pParse, 0, &sEnd, 0);
83963   return;
83964 }
83965 #endif /* SQLITE_OMIT_VIEW */
83966
83967 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
83968 /*
83969 ** The Table structure pTable is really a VIEW.  Fill in the names of
83970 ** the columns of the view in the pTable structure.  Return the number
83971 ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
83972 */
83973 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
83974   Table *pSelTab;   /* A fake table from which we get the result set */
83975   Select *pSel;     /* Copy of the SELECT that implements the view */
83976   int nErr = 0;     /* Number of errors encountered */
83977   int n;            /* Temporarily holds the number of cursors assigned */
83978   sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
83979   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
83980
83981   assert( pTable );
83982
83983 #ifndef SQLITE_OMIT_VIRTUALTABLE
83984   if( sqlite3VtabCallConnect(pParse, pTable) ){
83985     return SQLITE_ERROR;
83986   }
83987   if( IsVirtual(pTable) ) return 0;
83988 #endif
83989
83990 #ifndef SQLITE_OMIT_VIEW
83991   /* A positive nCol means the columns names for this view are
83992   ** already known.
83993   */
83994   if( pTable->nCol>0 ) return 0;
83995
83996   /* A negative nCol is a special marker meaning that we are currently
83997   ** trying to compute the column names.  If we enter this routine with
83998   ** a negative nCol, it means two or more views form a loop, like this:
83999   **
84000   **     CREATE VIEW one AS SELECT * FROM two;
84001   **     CREATE VIEW two AS SELECT * FROM one;
84002   **
84003   ** Actually, the error above is now caught prior to reaching this point.
84004   ** But the following test is still important as it does come up
84005   ** in the following:
84006   ** 
84007   **     CREATE TABLE main.ex1(a);
84008   **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
84009   **     SELECT * FROM temp.ex1;
84010   */
84011   if( pTable->nCol<0 ){
84012     sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
84013     return 1;
84014   }
84015   assert( pTable->nCol>=0 );
84016
84017   /* If we get this far, it means we need to compute the table names.
84018   ** Note that the call to sqlite3ResultSetOfSelect() will expand any
84019   ** "*" elements in the results set of the view and will assign cursors
84020   ** to the elements of the FROM clause.  But we do not want these changes
84021   ** to be permanent.  So the computation is done on a copy of the SELECT
84022   ** statement that defines the view.
84023   */
84024   assert( pTable->pSelect );
84025   pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
84026   if( pSel ){
84027     u8 enableLookaside = db->lookaside.bEnabled;
84028     n = pParse->nTab;
84029     sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
84030     pTable->nCol = -1;
84031     db->lookaside.bEnabled = 0;
84032 #ifndef SQLITE_OMIT_AUTHORIZATION
84033     xAuth = db->xAuth;
84034     db->xAuth = 0;
84035     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
84036     db->xAuth = xAuth;
84037 #else
84038     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
84039 #endif
84040     db->lookaside.bEnabled = enableLookaside;
84041     pParse->nTab = n;
84042     if( pSelTab ){
84043       assert( pTable->aCol==0 );
84044       pTable->nCol = pSelTab->nCol;
84045       pTable->aCol = pSelTab->aCol;
84046       pSelTab->nCol = 0;
84047       pSelTab->aCol = 0;
84048       sqlite3DeleteTable(db, pSelTab);
84049       assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
84050       pTable->pSchema->flags |= DB_UnresetViews;
84051     }else{
84052       pTable->nCol = 0;
84053       nErr++;
84054     }
84055     sqlite3SelectDelete(db, pSel);
84056   } else {
84057     nErr++;
84058   }
84059 #endif /* SQLITE_OMIT_VIEW */
84060   return nErr;  
84061 }
84062 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
84063
84064 #ifndef SQLITE_OMIT_VIEW
84065 /*
84066 ** Clear the column names from every VIEW in database idx.
84067 */
84068 static void sqliteViewResetAll(sqlite3 *db, int idx){
84069   HashElem *i;
84070   assert( sqlite3SchemaMutexHeld(db, idx, 0) );
84071   if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
84072   for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
84073     Table *pTab = sqliteHashData(i);
84074     if( pTab->pSelect ){
84075       sqliteDeleteColumnNames(db, pTab);
84076       pTab->aCol = 0;
84077       pTab->nCol = 0;
84078     }
84079   }
84080   DbClearProperty(db, idx, DB_UnresetViews);
84081 }
84082 #else
84083 # define sqliteViewResetAll(A,B)
84084 #endif /* SQLITE_OMIT_VIEW */
84085
84086 /*
84087 ** This function is called by the VDBE to adjust the internal schema
84088 ** used by SQLite when the btree layer moves a table root page. The
84089 ** root-page of a table or index in database iDb has changed from iFrom
84090 ** to iTo.
84091 **
84092 ** Ticket #1728:  The symbol table might still contain information
84093 ** on tables and/or indices that are the process of being deleted.
84094 ** If you are unlucky, one of those deleted indices or tables might
84095 ** have the same rootpage number as the real table or index that is
84096 ** being moved.  So we cannot stop searching after the first match 
84097 ** because the first match might be for one of the deleted indices
84098 ** or tables and not the table/index that is actually being moved.
84099 ** We must continue looping until all tables and indices with
84100 ** rootpage==iFrom have been converted to have a rootpage of iTo
84101 ** in order to be certain that we got the right one.
84102 */
84103 #ifndef SQLITE_OMIT_AUTOVACUUM
84104 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
84105   HashElem *pElem;
84106   Hash *pHash;
84107   Db *pDb;
84108
84109   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
84110   pDb = &db->aDb[iDb];
84111   pHash = &pDb->pSchema->tblHash;
84112   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
84113     Table *pTab = sqliteHashData(pElem);
84114     if( pTab->tnum==iFrom ){
84115       pTab->tnum = iTo;
84116     }
84117   }
84118   pHash = &pDb->pSchema->idxHash;
84119   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
84120     Index *pIdx = sqliteHashData(pElem);
84121     if( pIdx->tnum==iFrom ){
84122       pIdx->tnum = iTo;
84123     }
84124   }
84125 }
84126 #endif
84127
84128 /*
84129 ** Write code to erase the table with root-page iTable from database iDb.
84130 ** Also write code to modify the sqlite_master table and internal schema
84131 ** if a root-page of another table is moved by the btree-layer whilst
84132 ** erasing iTable (this can happen with an auto-vacuum database).
84133 */ 
84134 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
84135   Vdbe *v = sqlite3GetVdbe(pParse);
84136   int r1 = sqlite3GetTempReg(pParse);
84137   sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
84138   sqlite3MayAbort(pParse);
84139 #ifndef SQLITE_OMIT_AUTOVACUUM
84140   /* OP_Destroy stores an in integer r1. If this integer
84141   ** is non-zero, then it is the root page number of a table moved to
84142   ** location iTable. The following code modifies the sqlite_master table to
84143   ** reflect this.
84144   **
84145   ** The "#NNN" in the SQL is a special constant that means whatever value
84146   ** is in register NNN.  See grammar rules associated with the TK_REGISTER
84147   ** token for additional information.
84148   */
84149   sqlite3NestedParse(pParse, 
84150      "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
84151      pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
84152 #endif
84153   sqlite3ReleaseTempReg(pParse, r1);
84154 }
84155
84156 /*
84157 ** Write VDBE code to erase table pTab and all associated indices on disk.
84158 ** Code to update the sqlite_master tables and internal schema definitions
84159 ** in case a root-page belonging to another table is moved by the btree layer
84160 ** is also added (this can happen with an auto-vacuum database).
84161 */
84162 static void destroyTable(Parse *pParse, Table *pTab){
84163 #ifdef SQLITE_OMIT_AUTOVACUUM
84164   Index *pIdx;
84165   int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
84166   destroyRootPage(pParse, pTab->tnum, iDb);
84167   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
84168     destroyRootPage(pParse, pIdx->tnum, iDb);
84169   }
84170 #else
84171   /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
84172   ** is not defined), then it is important to call OP_Destroy on the
84173   ** table and index root-pages in order, starting with the numerically 
84174   ** largest root-page number. This guarantees that none of the root-pages
84175   ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
84176   ** following were coded:
84177   **
84178   ** OP_Destroy 4 0
84179   ** ...
84180   ** OP_Destroy 5 0
84181   **
84182   ** and root page 5 happened to be the largest root-page number in the
84183   ** database, then root page 5 would be moved to page 4 by the 
84184   ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
84185   ** a free-list page.
84186   */
84187   int iTab = pTab->tnum;
84188   int iDestroyed = 0;
84189
84190   while( 1 ){
84191     Index *pIdx;
84192     int iLargest = 0;
84193
84194     if( iDestroyed==0 || iTab<iDestroyed ){
84195       iLargest = iTab;
84196     }
84197     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
84198       int iIdx = pIdx->tnum;
84199       assert( pIdx->pSchema==pTab->pSchema );
84200       if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
84201         iLargest = iIdx;
84202       }
84203     }
84204     if( iLargest==0 ){
84205       return;
84206     }else{
84207       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
84208       assert( iDb>=0 && iDb<pParse->db->nDb );
84209       destroyRootPage(pParse, iLargest, iDb);
84210       iDestroyed = iLargest;
84211     }
84212   }
84213 #endif
84214 }
84215
84216 /*
84217 ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
84218 ** after a DROP INDEX or DROP TABLE command.
84219 */
84220 static void sqlite3ClearStatTables(
84221   Parse *pParse,         /* The parsing context */
84222   int iDb,               /* The database number */
84223   const char *zType,     /* "idx" or "tbl" */
84224   const char *zName      /* Name of index or table */
84225 ){
84226   int i;
84227   const char *zDbName = pParse->db->aDb[iDb].zName;
84228   for(i=1; i<=3; i++){
84229     char zTab[24];
84230     sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
84231     if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
84232       sqlite3NestedParse(pParse,
84233         "DELETE FROM %Q.%s WHERE %s=%Q",
84234         zDbName, zTab, zType, zName
84235       );
84236     }
84237   }
84238 }
84239
84240 /*
84241 ** Generate code to drop a table.
84242 */
84243 SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
84244   Vdbe *v;
84245   sqlite3 *db = pParse->db;
84246   Trigger *pTrigger;
84247   Db *pDb = &db->aDb[iDb];
84248
84249   v = sqlite3GetVdbe(pParse);
84250   assert( v!=0 );
84251   sqlite3BeginWriteOperation(pParse, 1, iDb);
84252
84253 #ifndef SQLITE_OMIT_VIRTUALTABLE
84254   if( IsVirtual(pTab) ){
84255     sqlite3VdbeAddOp0(v, OP_VBegin);
84256   }
84257 #endif
84258
84259   /* Drop all triggers associated with the table being dropped. Code
84260   ** is generated to remove entries from sqlite_master and/or
84261   ** sqlite_temp_master if required.
84262   */
84263   pTrigger = sqlite3TriggerList(pParse, pTab);
84264   while( pTrigger ){
84265     assert( pTrigger->pSchema==pTab->pSchema || 
84266         pTrigger->pSchema==db->aDb[1].pSchema );
84267     sqlite3DropTriggerPtr(pParse, pTrigger);
84268     pTrigger = pTrigger->pNext;
84269   }
84270
84271 #ifndef SQLITE_OMIT_AUTOINCREMENT
84272   /* Remove any entries of the sqlite_sequence table associated with
84273   ** the table being dropped. This is done before the table is dropped
84274   ** at the btree level, in case the sqlite_sequence table needs to
84275   ** move as a result of the drop (can happen in auto-vacuum mode).
84276   */
84277   if( pTab->tabFlags & TF_Autoincrement ){
84278     sqlite3NestedParse(pParse,
84279       "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
84280       pDb->zName, pTab->zName
84281     );
84282   }
84283 #endif
84284
84285   /* Drop all SQLITE_MASTER table and index entries that refer to the
84286   ** table. The program name loops through the master table and deletes
84287   ** every row that refers to a table of the same name as the one being
84288   ** dropped. Triggers are handled separately because a trigger can be
84289   ** created in the temp database that refers to a table in another
84290   ** database.
84291   */
84292   sqlite3NestedParse(pParse, 
84293       "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
84294       pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
84295   if( !isView && !IsVirtual(pTab) ){
84296     destroyTable(pParse, pTab);
84297   }
84298
84299   /* Remove the table entry from SQLite's internal schema and modify
84300   ** the schema cookie.
84301   */
84302   if( IsVirtual(pTab) ){
84303     sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
84304   }
84305   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
84306   sqlite3ChangeCookie(pParse, iDb);
84307   sqliteViewResetAll(db, iDb);
84308 }
84309
84310 /*
84311 ** This routine is called to do the work of a DROP TABLE statement.
84312 ** pName is the name of the table to be dropped.
84313 */
84314 SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
84315   Table *pTab;
84316   Vdbe *v;
84317   sqlite3 *db = pParse->db;
84318   int iDb;
84319
84320   if( db->mallocFailed ){
84321     goto exit_drop_table;
84322   }
84323   assert( pParse->nErr==0 );
84324   assert( pName->nSrc==1 );
84325   if( noErr ) db->suppressErr++;
84326   pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
84327   if( noErr ) db->suppressErr--;
84328
84329   if( pTab==0 ){
84330     if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
84331     goto exit_drop_table;
84332   }
84333   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
84334   assert( iDb>=0 && iDb<db->nDb );
84335
84336   /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
84337   ** it is initialized.
84338   */
84339   if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
84340     goto exit_drop_table;
84341   }
84342 #ifndef SQLITE_OMIT_AUTHORIZATION
84343   {
84344     int code;
84345     const char *zTab = SCHEMA_TABLE(iDb);
84346     const char *zDb = db->aDb[iDb].zName;
84347     const char *zArg2 = 0;
84348     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
84349       goto exit_drop_table;
84350     }
84351     if( isView ){
84352       if( !OMIT_TEMPDB && iDb==1 ){
84353         code = SQLITE_DROP_TEMP_VIEW;
84354       }else{
84355         code = SQLITE_DROP_VIEW;
84356       }
84357 #ifndef SQLITE_OMIT_VIRTUALTABLE
84358     }else if( IsVirtual(pTab) ){
84359       code = SQLITE_DROP_VTABLE;
84360       zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
84361 #endif
84362     }else{
84363       if( !OMIT_TEMPDB && iDb==1 ){
84364         code = SQLITE_DROP_TEMP_TABLE;
84365       }else{
84366         code = SQLITE_DROP_TABLE;
84367       }
84368     }
84369     if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
84370       goto exit_drop_table;
84371     }
84372     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
84373       goto exit_drop_table;
84374     }
84375   }
84376 #endif
84377   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 
84378     && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
84379     sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
84380     goto exit_drop_table;
84381   }
84382
84383 #ifndef SQLITE_OMIT_VIEW
84384   /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
84385   ** on a table.
84386   */
84387   if( isView && pTab->pSelect==0 ){
84388     sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
84389     goto exit_drop_table;
84390   }
84391   if( !isView && pTab->pSelect ){
84392     sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
84393     goto exit_drop_table;
84394   }
84395 #endif
84396
84397   /* Generate code to remove the table from the master table
84398   ** on disk.
84399   */
84400   v = sqlite3GetVdbe(pParse);
84401   if( v ){
84402     sqlite3BeginWriteOperation(pParse, 1, iDb);
84403     sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
84404     sqlite3FkDropTable(pParse, pName, pTab);
84405     sqlite3CodeDropTable(pParse, pTab, iDb, isView);
84406   }
84407
84408 exit_drop_table:
84409   sqlite3SrcListDelete(db, pName);
84410 }
84411
84412 /*
84413 ** This routine is called to create a new foreign key on the table
84414 ** currently under construction.  pFromCol determines which columns
84415 ** in the current table point to the foreign key.  If pFromCol==0 then
84416 ** connect the key to the last column inserted.  pTo is the name of
84417 ** the table referred to.  pToCol is a list of tables in the other
84418 ** pTo table that the foreign key points to.  flags contains all
84419 ** information about the conflict resolution algorithms specified
84420 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
84421 **
84422 ** An FKey structure is created and added to the table currently
84423 ** under construction in the pParse->pNewTable field.
84424 **
84425 ** The foreign key is set for IMMEDIATE processing.  A subsequent call
84426 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
84427 */
84428 SQLITE_PRIVATE void sqlite3CreateForeignKey(
84429   Parse *pParse,       /* Parsing context */
84430   ExprList *pFromCol,  /* Columns in this table that point to other table */
84431   Token *pTo,          /* Name of the other table */
84432   ExprList *pToCol,    /* Columns in the other table */
84433   int flags            /* Conflict resolution algorithms. */
84434 ){
84435   sqlite3 *db = pParse->db;
84436 #ifndef SQLITE_OMIT_FOREIGN_KEY
84437   FKey *pFKey = 0;
84438   FKey *pNextTo;
84439   Table *p = pParse->pNewTable;
84440   int nByte;
84441   int i;
84442   int nCol;
84443   char *z;
84444
84445   assert( pTo!=0 );
84446   if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
84447   if( pFromCol==0 ){
84448     int iCol = p->nCol-1;
84449     if( NEVER(iCol<0) ) goto fk_end;
84450     if( pToCol && pToCol->nExpr!=1 ){
84451       sqlite3ErrorMsg(pParse, "foreign key on %s"
84452          " should reference only one column of table %T",
84453          p->aCol[iCol].zName, pTo);
84454       goto fk_end;
84455     }
84456     nCol = 1;
84457   }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
84458     sqlite3ErrorMsg(pParse,
84459         "number of columns in foreign key does not match the number of "
84460         "columns in the referenced table");
84461     goto fk_end;
84462   }else{
84463     nCol = pFromCol->nExpr;
84464   }
84465   nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
84466   if( pToCol ){
84467     for(i=0; i<pToCol->nExpr; i++){
84468       nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
84469     }
84470   }
84471   pFKey = sqlite3DbMallocZero(db, nByte );
84472   if( pFKey==0 ){
84473     goto fk_end;
84474   }
84475   pFKey->pFrom = p;
84476   pFKey->pNextFrom = p->pFKey;
84477   z = (char*)&pFKey->aCol[nCol];
84478   pFKey->zTo = z;
84479   memcpy(z, pTo->z, pTo->n);
84480   z[pTo->n] = 0;
84481   sqlite3Dequote(z);
84482   z += pTo->n+1;
84483   pFKey->nCol = nCol;
84484   if( pFromCol==0 ){
84485     pFKey->aCol[0].iFrom = p->nCol-1;
84486   }else{
84487     for(i=0; i<nCol; i++){
84488       int j;
84489       for(j=0; j<p->nCol; j++){
84490         if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
84491           pFKey->aCol[i].iFrom = j;
84492           break;
84493         }
84494       }
84495       if( j>=p->nCol ){
84496         sqlite3ErrorMsg(pParse, 
84497           "unknown column \"%s\" in foreign key definition", 
84498           pFromCol->a[i].zName);
84499         goto fk_end;
84500       }
84501     }
84502   }
84503   if( pToCol ){
84504     for(i=0; i<nCol; i++){
84505       int n = sqlite3Strlen30(pToCol->a[i].zName);
84506       pFKey->aCol[i].zCol = z;
84507       memcpy(z, pToCol->a[i].zName, n);
84508       z[n] = 0;
84509       z += n+1;
84510     }
84511   }
84512   pFKey->isDeferred = 0;
84513   pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
84514   pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
84515
84516   assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
84517   pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash, 
84518       pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
84519   );
84520   if( pNextTo==pFKey ){
84521     db->mallocFailed = 1;
84522     goto fk_end;
84523   }
84524   if( pNextTo ){
84525     assert( pNextTo->pPrevTo==0 );
84526     pFKey->pNextTo = pNextTo;
84527     pNextTo->pPrevTo = pFKey;
84528   }
84529
84530   /* Link the foreign key to the table as the last step.
84531   */
84532   p->pFKey = pFKey;
84533   pFKey = 0;
84534
84535 fk_end:
84536   sqlite3DbFree(db, pFKey);
84537 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
84538   sqlite3ExprListDelete(db, pFromCol);
84539   sqlite3ExprListDelete(db, pToCol);
84540 }
84541
84542 /*
84543 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
84544 ** clause is seen as part of a foreign key definition.  The isDeferred
84545 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
84546 ** The behavior of the most recently created foreign key is adjusted
84547 ** accordingly.
84548 */
84549 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
84550 #ifndef SQLITE_OMIT_FOREIGN_KEY
84551   Table *pTab;
84552   FKey *pFKey;
84553   if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
84554   assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
84555   pFKey->isDeferred = (u8)isDeferred;
84556 #endif
84557 }
84558
84559 /*
84560 ** Generate code that will erase and refill index *pIdx.  This is
84561 ** used to initialize a newly created index or to recompute the
84562 ** content of an index in response to a REINDEX command.
84563 **
84564 ** if memRootPage is not negative, it means that the index is newly
84565 ** created.  The register specified by memRootPage contains the
84566 ** root page number of the index.  If memRootPage is negative, then
84567 ** the index already exists and must be cleared before being refilled and
84568 ** the root page number of the index is taken from pIndex->tnum.
84569 */
84570 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
84571   Table *pTab = pIndex->pTable;  /* The table that is indexed */
84572   int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
84573   int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
84574   int iSorter;                   /* Cursor opened by OpenSorter (if in use) */
84575   int addr1;                     /* Address of top of loop */
84576   int addr2;                     /* Address to jump to for next iteration */
84577   int tnum;                      /* Root page of index */
84578   Vdbe *v;                       /* Generate code into this virtual machine */
84579   KeyInfo *pKey;                 /* KeyInfo for index */
84580   int regRecord;                 /* Register holding assemblied index record */
84581   sqlite3 *db = pParse->db;      /* The database connection */
84582   int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
84583
84584 #ifndef SQLITE_OMIT_AUTHORIZATION
84585   if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
84586       db->aDb[iDb].zName ) ){
84587     return;
84588   }
84589 #endif
84590
84591   /* Require a write-lock on the table to perform this operation */
84592   sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
84593
84594   v = sqlite3GetVdbe(pParse);
84595   if( v==0 ) return;
84596   if( memRootPage>=0 ){
84597     tnum = memRootPage;
84598   }else{
84599     tnum = pIndex->tnum;
84600     sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
84601   }
84602   pKey = sqlite3IndexKeyinfo(pParse, pIndex);
84603   sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, 
84604                     (char *)pKey, P4_KEYINFO_HANDOFF);
84605   sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
84606
84607   /* Open the sorter cursor if we are to use one. */
84608   iSorter = pParse->nTab++;
84609   sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, 0, (char*)pKey, P4_KEYINFO);
84610
84611   /* Open the table. Loop through all rows of the table, inserting index
84612   ** records into the sorter. */
84613   sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
84614   addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
84615   regRecord = sqlite3GetTempReg(pParse);
84616
84617   sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
84618   sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
84619   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
84620   sqlite3VdbeJumpHere(v, addr1);
84621   addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0);
84622   if( pIndex->onError!=OE_None ){
84623     int j2 = sqlite3VdbeCurrentAddr(v) + 3;
84624     sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
84625     addr2 = sqlite3VdbeCurrentAddr(v);
84626     sqlite3VdbeAddOp3(v, OP_SorterCompare, iSorter, j2, regRecord);
84627     sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_UNIQUE,
84628         OE_Abort, "indexed columns are not unique", P4_STATIC
84629     );
84630   }else{
84631     addr2 = sqlite3VdbeCurrentAddr(v);
84632   }
84633   sqlite3VdbeAddOp2(v, OP_SorterData, iSorter, regRecord);
84634   sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);
84635   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
84636   sqlite3ReleaseTempReg(pParse, regRecord);
84637   sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2);
84638   sqlite3VdbeJumpHere(v, addr1);
84639
84640   sqlite3VdbeAddOp1(v, OP_Close, iTab);
84641   sqlite3VdbeAddOp1(v, OP_Close, iIdx);
84642   sqlite3VdbeAddOp1(v, OP_Close, iSorter);
84643 }
84644
84645 /*
84646 ** Create a new index for an SQL table.  pName1.pName2 is the name of the index 
84647 ** and pTblList is the name of the table that is to be indexed.  Both will 
84648 ** be NULL for a primary key or an index that is created to satisfy a
84649 ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
84650 ** as the table to be indexed.  pParse->pNewTable is a table that is
84651 ** currently being constructed by a CREATE TABLE statement.
84652 **
84653 ** pList is a list of columns to be indexed.  pList will be NULL if this
84654 ** is a primary key or unique-constraint on the most recent column added
84655 ** to the table currently under construction.  
84656 **
84657 ** If the index is created successfully, return a pointer to the new Index
84658 ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
84659 ** as the tables primary key (Index.autoIndex==2).
84660 */
84661 SQLITE_PRIVATE Index *sqlite3CreateIndex(
84662   Parse *pParse,     /* All information about this parse */
84663   Token *pName1,     /* First part of index name. May be NULL */
84664   Token *pName2,     /* Second part of index name. May be NULL */
84665   SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
84666   ExprList *pList,   /* A list of columns to be indexed */
84667   int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
84668   Token *pStart,     /* The CREATE token that begins this statement */
84669   Token *pEnd,       /* The ")" that closes the CREATE INDEX statement */
84670   int sortOrder,     /* Sort order of primary key when pList==NULL */
84671   int ifNotExist     /* Omit error if index already exists */
84672 ){
84673   Index *pRet = 0;     /* Pointer to return */
84674   Table *pTab = 0;     /* Table to be indexed */
84675   Index *pIndex = 0;   /* The index to be created */
84676   char *zName = 0;     /* Name of the index */
84677   int nName;           /* Number of characters in zName */
84678   int i, j;
84679   Token nullId;        /* Fake token for an empty ID list */
84680   DbFixer sFix;        /* For assigning database names to pTable */
84681   int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
84682   sqlite3 *db = pParse->db;
84683   Db *pDb;             /* The specific table containing the indexed database */
84684   int iDb;             /* Index of the database that is being written */
84685   Token *pName = 0;    /* Unqualified name of the index to create */
84686   struct ExprList_item *pListItem; /* For looping over pList */
84687   int nCol;
84688   int nExtra = 0;
84689   char *zExtra;
84690
84691   assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
84692   assert( pParse->nErr==0 );      /* Never called with prior errors */
84693   if( db->mallocFailed || IN_DECLARE_VTAB ){
84694     goto exit_create_index;
84695   }
84696   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
84697     goto exit_create_index;
84698   }
84699
84700   /*
84701   ** Find the table that is to be indexed.  Return early if not found.
84702   */
84703   if( pTblName!=0 ){
84704
84705     /* Use the two-part index name to determine the database 
84706     ** to search for the table. 'Fix' the table name to this db
84707     ** before looking up the table.
84708     */
84709     assert( pName1 && pName2 );
84710     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
84711     if( iDb<0 ) goto exit_create_index;
84712     assert( pName && pName->z );
84713
84714 #ifndef SQLITE_OMIT_TEMPDB
84715     /* If the index name was unqualified, check if the table
84716     ** is a temp table. If so, set the database to 1. Do not do this
84717     ** if initialising a database schema.
84718     */
84719     if( !db->init.busy ){
84720       pTab = sqlite3SrcListLookup(pParse, pTblName);
84721       if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
84722         iDb = 1;
84723       }
84724     }
84725 #endif
84726
84727     if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
84728         sqlite3FixSrcList(&sFix, pTblName)
84729     ){
84730       /* Because the parser constructs pTblName from a single identifier,
84731       ** sqlite3FixSrcList can never fail. */
84732       assert(0);
84733     }
84734     pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
84735     assert( db->mallocFailed==0 || pTab==0 );
84736     if( pTab==0 ) goto exit_create_index;
84737     assert( db->aDb[iDb].pSchema==pTab->pSchema );
84738   }else{
84739     assert( pName==0 );
84740     assert( pStart==0 );
84741     pTab = pParse->pNewTable;
84742     if( !pTab ) goto exit_create_index;
84743     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
84744   }
84745   pDb = &db->aDb[iDb];
84746
84747   assert( pTab!=0 );
84748   assert( pParse->nErr==0 );
84749   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 
84750        && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
84751     sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
84752     goto exit_create_index;
84753   }
84754 #ifndef SQLITE_OMIT_VIEW
84755   if( pTab->pSelect ){
84756     sqlite3ErrorMsg(pParse, "views may not be indexed");
84757     goto exit_create_index;
84758   }
84759 #endif
84760 #ifndef SQLITE_OMIT_VIRTUALTABLE
84761   if( IsVirtual(pTab) ){
84762     sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
84763     goto exit_create_index;
84764   }
84765 #endif
84766
84767   /*
84768   ** Find the name of the index.  Make sure there is not already another
84769   ** index or table with the same name.  
84770   **
84771   ** Exception:  If we are reading the names of permanent indices from the
84772   ** sqlite_master table (because some other process changed the schema) and
84773   ** one of the index names collides with the name of a temporary table or
84774   ** index, then we will continue to process this index.
84775   **
84776   ** If pName==0 it means that we are
84777   ** dealing with a primary key or UNIQUE constraint.  We have to invent our
84778   ** own name.
84779   */
84780   if( pName ){
84781     zName = sqlite3NameFromToken(db, pName);
84782     if( zName==0 ) goto exit_create_index;
84783     assert( pName->z!=0 );
84784     if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
84785       goto exit_create_index;
84786     }
84787     if( !db->init.busy ){
84788       if( sqlite3FindTable(db, zName, 0)!=0 ){
84789         sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
84790         goto exit_create_index;
84791       }
84792     }
84793     if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
84794       if( !ifNotExist ){
84795         sqlite3ErrorMsg(pParse, "index %s already exists", zName);
84796       }else{
84797         assert( !db->init.busy );
84798         sqlite3CodeVerifySchema(pParse, iDb);
84799       }
84800       goto exit_create_index;
84801     }
84802   }else{
84803     int n;
84804     Index *pLoop;
84805     for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
84806     zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
84807     if( zName==0 ){
84808       goto exit_create_index;
84809     }
84810   }
84811
84812   /* Check for authorization to create an index.
84813   */
84814 #ifndef SQLITE_OMIT_AUTHORIZATION
84815   {
84816     const char *zDb = pDb->zName;
84817     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
84818       goto exit_create_index;
84819     }
84820     i = SQLITE_CREATE_INDEX;
84821     if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
84822     if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
84823       goto exit_create_index;
84824     }
84825   }
84826 #endif
84827
84828   /* If pList==0, it means this routine was called to make a primary
84829   ** key out of the last column added to the table under construction.
84830   ** So create a fake list to simulate this.
84831   */
84832   if( pList==0 ){
84833     nullId.z = pTab->aCol[pTab->nCol-1].zName;
84834     nullId.n = sqlite3Strlen30((char*)nullId.z);
84835     pList = sqlite3ExprListAppend(pParse, 0, 0);
84836     if( pList==0 ) goto exit_create_index;
84837     sqlite3ExprListSetName(pParse, pList, &nullId, 0);
84838     pList->a[0].sortOrder = (u8)sortOrder;
84839   }
84840
84841   /* Figure out how many bytes of space are required to store explicitly
84842   ** specified collation sequence names.
84843   */
84844   for(i=0; i<pList->nExpr; i++){
84845     Expr *pExpr = pList->a[i].pExpr;
84846     if( pExpr ){
84847       assert( pExpr->op==TK_COLLATE );
84848       nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
84849     }
84850   }
84851
84852   /* 
84853   ** Allocate the index structure. 
84854   */
84855   nName = sqlite3Strlen30(zName);
84856   nCol = pList->nExpr;
84857   pIndex = sqlite3DbMallocZero(db, 
84858       ROUND8(sizeof(Index)) +              /* Index structure  */
84859       ROUND8(sizeof(tRowcnt)*(nCol+1)) +   /* Index.aiRowEst   */
84860       sizeof(char *)*nCol +                /* Index.azColl     */
84861       sizeof(int)*nCol +                   /* Index.aiColumn   */
84862       sizeof(u8)*nCol +                    /* Index.aSortOrder */
84863       nName + 1 +                          /* Index.zName      */
84864       nExtra                               /* Collation sequence names */
84865   );
84866   if( db->mallocFailed ){
84867     goto exit_create_index;
84868   }
84869   zExtra = (char*)pIndex;
84870   pIndex->aiRowEst = (tRowcnt*)&zExtra[ROUND8(sizeof(Index))];
84871   pIndex->azColl = (char**)
84872      ((char*)pIndex->aiRowEst + ROUND8(sizeof(tRowcnt)*nCol+1));
84873   assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowEst) );
84874   assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
84875   pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
84876   pIndex->aSortOrder = (u8 *)(&pIndex->aiColumn[nCol]);
84877   pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
84878   zExtra = (char *)(&pIndex->zName[nName+1]);
84879   memcpy(pIndex->zName, zName, nName+1);
84880   pIndex->pTable = pTab;
84881   pIndex->nColumn = pList->nExpr;
84882   pIndex->onError = (u8)onError;
84883   pIndex->autoIndex = (u8)(pName==0);
84884   pIndex->pSchema = db->aDb[iDb].pSchema;
84885   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
84886
84887   /* Check to see if we should honor DESC requests on index columns
84888   */
84889   if( pDb->pSchema->file_format>=4 ){
84890     sortOrderMask = -1;   /* Honor DESC */
84891   }else{
84892     sortOrderMask = 0;    /* Ignore DESC */
84893   }
84894
84895   /* Scan the names of the columns of the table to be indexed and
84896   ** load the column indices into the Index structure.  Report an error
84897   ** if any column is not found.
84898   **
84899   ** TODO:  Add a test to make sure that the same column is not named
84900   ** more than once within the same index.  Only the first instance of
84901   ** the column will ever be used by the optimizer.  Note that using the
84902   ** same column more than once cannot be an error because that would 
84903   ** break backwards compatibility - it needs to be a warning.
84904   */
84905   for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
84906     const char *zColName = pListItem->zName;
84907     Column *pTabCol;
84908     int requestedSortOrder;
84909     char *zColl;                   /* Collation sequence name */
84910
84911     for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
84912       if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
84913     }
84914     if( j>=pTab->nCol ){
84915       sqlite3ErrorMsg(pParse, "table %s has no column named %s",
84916         pTab->zName, zColName);
84917       pParse->checkSchema = 1;
84918       goto exit_create_index;
84919     }
84920     pIndex->aiColumn[i] = j;
84921     if( pListItem->pExpr ){
84922       int nColl;
84923       assert( pListItem->pExpr->op==TK_COLLATE );
84924       zColl = pListItem->pExpr->u.zToken;
84925       nColl = sqlite3Strlen30(zColl) + 1;
84926       assert( nExtra>=nColl );
84927       memcpy(zExtra, zColl, nColl);
84928       zColl = zExtra;
84929       zExtra += nColl;
84930       nExtra -= nColl;
84931     }else{
84932       zColl = pTab->aCol[j].zColl;
84933       if( !zColl ) zColl = "BINARY";
84934     }
84935     if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
84936       goto exit_create_index;
84937     }
84938     pIndex->azColl[i] = zColl;
84939     requestedSortOrder = pListItem->sortOrder & sortOrderMask;
84940     pIndex->aSortOrder[i] = (u8)requestedSortOrder;
84941   }
84942   sqlite3DefaultRowEst(pIndex);
84943
84944   if( pTab==pParse->pNewTable ){
84945     /* This routine has been called to create an automatic index as a
84946     ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
84947     ** a PRIMARY KEY or UNIQUE clause following the column definitions.
84948     ** i.e. one of:
84949     **
84950     ** CREATE TABLE t(x PRIMARY KEY, y);
84951     ** CREATE TABLE t(x, y, UNIQUE(x, y));
84952     **
84953     ** Either way, check to see if the table already has such an index. If
84954     ** so, don't bother creating this one. This only applies to
84955     ** automatically created indices. Users can do as they wish with
84956     ** explicit indices.
84957     **
84958     ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
84959     ** (and thus suppressing the second one) even if they have different
84960     ** sort orders.
84961     **
84962     ** If there are different collating sequences or if the columns of
84963     ** the constraint occur in different orders, then the constraints are
84964     ** considered distinct and both result in separate indices.
84965     */
84966     Index *pIdx;
84967     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
84968       int k;
84969       assert( pIdx->onError!=OE_None );
84970       assert( pIdx->autoIndex );
84971       assert( pIndex->onError!=OE_None );
84972
84973       if( pIdx->nColumn!=pIndex->nColumn ) continue;
84974       for(k=0; k<pIdx->nColumn; k++){
84975         const char *z1;
84976         const char *z2;
84977         if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
84978         z1 = pIdx->azColl[k];
84979         z2 = pIndex->azColl[k];
84980         if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
84981       }
84982       if( k==pIdx->nColumn ){
84983         if( pIdx->onError!=pIndex->onError ){
84984           /* This constraint creates the same index as a previous
84985           ** constraint specified somewhere in the CREATE TABLE statement.
84986           ** However the ON CONFLICT clauses are different. If both this 
84987           ** constraint and the previous equivalent constraint have explicit
84988           ** ON CONFLICT clauses this is an error. Otherwise, use the
84989           ** explicitly specified behavior for the index.
84990           */
84991           if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
84992             sqlite3ErrorMsg(pParse, 
84993                 "conflicting ON CONFLICT clauses specified", 0);
84994           }
84995           if( pIdx->onError==OE_Default ){
84996             pIdx->onError = pIndex->onError;
84997           }
84998         }
84999         goto exit_create_index;
85000       }
85001     }
85002   }
85003
85004   /* Link the new Index structure to its table and to the other
85005   ** in-memory database structures. 
85006   */
85007   if( db->init.busy ){
85008     Index *p;
85009     assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
85010     p = sqlite3HashInsert(&pIndex->pSchema->idxHash, 
85011                           pIndex->zName, sqlite3Strlen30(pIndex->zName),
85012                           pIndex);
85013     if( p ){
85014       assert( p==pIndex );  /* Malloc must have failed */
85015       db->mallocFailed = 1;
85016       goto exit_create_index;
85017     }
85018     db->flags |= SQLITE_InternChanges;
85019     if( pTblName!=0 ){
85020       pIndex->tnum = db->init.newTnum;
85021     }
85022   }
85023
85024   /* If the db->init.busy is 0 then create the index on disk.  This
85025   ** involves writing the index into the master table and filling in the
85026   ** index with the current table contents.
85027   **
85028   ** The db->init.busy is 0 when the user first enters a CREATE INDEX 
85029   ** command.  db->init.busy is 1 when a database is opened and 
85030   ** CREATE INDEX statements are read out of the master table.  In
85031   ** the latter case the index already exists on disk, which is why
85032   ** we don't want to recreate it.
85033   **
85034   ** If pTblName==0 it means this index is generated as a primary key
85035   ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
85036   ** has just been created, it contains no data and the index initialization
85037   ** step can be skipped.
85038   */
85039   else{ /* if( db->init.busy==0 ) */
85040     Vdbe *v;
85041     char *zStmt;
85042     int iMem = ++pParse->nMem;
85043
85044     v = sqlite3GetVdbe(pParse);
85045     if( v==0 ) goto exit_create_index;
85046
85047
85048     /* Create the rootpage for the index
85049     */
85050     sqlite3BeginWriteOperation(pParse, 1, iDb);
85051     sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
85052
85053     /* Gather the complete text of the CREATE INDEX statement into
85054     ** the zStmt variable
85055     */
85056     if( pStart ){
85057       assert( pEnd!=0 );
85058       /* A named index with an explicit CREATE INDEX statement */
85059       zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
85060         onError==OE_None ? "" : " UNIQUE",
85061         (int)(pEnd->z - pName->z) + 1,
85062         pName->z);
85063     }else{
85064       /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
85065       /* zStmt = sqlite3MPrintf(""); */
85066       zStmt = 0;
85067     }
85068
85069     /* Add an entry in sqlite_master for this index
85070     */
85071     sqlite3NestedParse(pParse, 
85072         "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
85073         db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
85074         pIndex->zName,
85075         pTab->zName,
85076         iMem,
85077         zStmt
85078     );
85079     sqlite3DbFree(db, zStmt);
85080
85081     /* Fill the index with data and reparse the schema. Code an OP_Expire
85082     ** to invalidate all pre-compiled statements.
85083     */
85084     if( pTblName ){
85085       sqlite3RefillIndex(pParse, pIndex, iMem);
85086       sqlite3ChangeCookie(pParse, iDb);
85087       sqlite3VdbeAddParseSchemaOp(v, iDb,
85088          sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
85089       sqlite3VdbeAddOp1(v, OP_Expire, 0);
85090     }
85091   }
85092
85093   /* When adding an index to the list of indices for a table, make
85094   ** sure all indices labeled OE_Replace come after all those labeled
85095   ** OE_Ignore.  This is necessary for the correct constraint check
85096   ** processing (in sqlite3GenerateConstraintChecks()) as part of
85097   ** UPDATE and INSERT statements.  
85098   */
85099   if( db->init.busy || pTblName==0 ){
85100     if( onError!=OE_Replace || pTab->pIndex==0
85101          || pTab->pIndex->onError==OE_Replace){
85102       pIndex->pNext = pTab->pIndex;
85103       pTab->pIndex = pIndex;
85104     }else{
85105       Index *pOther = pTab->pIndex;
85106       while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
85107         pOther = pOther->pNext;
85108       }
85109       pIndex->pNext = pOther->pNext;
85110       pOther->pNext = pIndex;
85111     }
85112     pRet = pIndex;
85113     pIndex = 0;
85114   }
85115
85116   /* Clean up before exiting */
85117 exit_create_index:
85118   if( pIndex ){
85119     sqlite3DbFree(db, pIndex->zColAff);
85120     sqlite3DbFree(db, pIndex);
85121   }
85122   sqlite3ExprListDelete(db, pList);
85123   sqlite3SrcListDelete(db, pTblName);
85124   sqlite3DbFree(db, zName);
85125   return pRet;
85126 }
85127
85128 /*
85129 ** Fill the Index.aiRowEst[] array with default information - information
85130 ** to be used when we have not run the ANALYZE command.
85131 **
85132 ** aiRowEst[0] is suppose to contain the number of elements in the index.
85133 ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
85134 ** number of rows in the table that match any particular value of the
85135 ** first column of the index.  aiRowEst[2] is an estimate of the number
85136 ** of rows that match any particular combiniation of the first 2 columns
85137 ** of the index.  And so forth.  It must always be the case that
85138 *
85139 **           aiRowEst[N]<=aiRowEst[N-1]
85140 **           aiRowEst[N]>=1
85141 **
85142 ** Apart from that, we have little to go on besides intuition as to
85143 ** how aiRowEst[] should be initialized.  The numbers generated here
85144 ** are based on typical values found in actual indices.
85145 */
85146 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
85147   tRowcnt *a = pIdx->aiRowEst;
85148   int i;
85149   tRowcnt n;
85150   assert( a!=0 );
85151   a[0] = pIdx->pTable->nRowEst;
85152   if( a[0]<10 ) a[0] = 10;
85153   n = 10;
85154   for(i=1; i<=pIdx->nColumn; i++){
85155     a[i] = n;
85156     if( n>5 ) n--;
85157   }
85158   if( pIdx->onError!=OE_None ){
85159     a[pIdx->nColumn] = 1;
85160   }
85161 }
85162
85163 /*
85164 ** This routine will drop an existing named index.  This routine
85165 ** implements the DROP INDEX statement.
85166 */
85167 SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
85168   Index *pIndex;
85169   Vdbe *v;
85170   sqlite3 *db = pParse->db;
85171   int iDb;
85172
85173   assert( pParse->nErr==0 );   /* Never called with prior errors */
85174   if( db->mallocFailed ){
85175     goto exit_drop_index;
85176   }
85177   assert( pName->nSrc==1 );
85178   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
85179     goto exit_drop_index;
85180   }
85181   pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
85182   if( pIndex==0 ){
85183     if( !ifExists ){
85184       sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
85185     }else{
85186       sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
85187     }
85188     pParse->checkSchema = 1;
85189     goto exit_drop_index;
85190   }
85191   if( pIndex->autoIndex ){
85192     sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
85193       "or PRIMARY KEY constraint cannot be dropped", 0);
85194     goto exit_drop_index;
85195   }
85196   iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
85197 #ifndef SQLITE_OMIT_AUTHORIZATION
85198   {
85199     int code = SQLITE_DROP_INDEX;
85200     Table *pTab = pIndex->pTable;
85201     const char *zDb = db->aDb[iDb].zName;
85202     const char *zTab = SCHEMA_TABLE(iDb);
85203     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
85204       goto exit_drop_index;
85205     }
85206     if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
85207     if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
85208       goto exit_drop_index;
85209     }
85210   }
85211 #endif
85212
85213   /* Generate code to remove the index and from the master table */
85214   v = sqlite3GetVdbe(pParse);
85215   if( v ){
85216     sqlite3BeginWriteOperation(pParse, 1, iDb);
85217     sqlite3NestedParse(pParse,
85218        "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
85219        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
85220     );
85221     sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
85222     sqlite3ChangeCookie(pParse, iDb);
85223     destroyRootPage(pParse, pIndex->tnum, iDb);
85224     sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
85225   }
85226
85227 exit_drop_index:
85228   sqlite3SrcListDelete(db, pName);
85229 }
85230
85231 /*
85232 ** pArray is a pointer to an array of objects. Each object in the
85233 ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
85234 ** to extend the array so that there is space for a new object at the end.
85235 **
85236 ** When this function is called, *pnEntry contains the current size of
85237 ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
85238 ** in total).
85239 **
85240 ** If the realloc() is successful (i.e. if no OOM condition occurs), the
85241 ** space allocated for the new object is zeroed, *pnEntry updated to
85242 ** reflect the new size of the array and a pointer to the new allocation
85243 ** returned. *pIdx is set to the index of the new array entry in this case.
85244 **
85245 ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
85246 ** unchanged and a copy of pArray returned.
85247 */
85248 SQLITE_PRIVATE void *sqlite3ArrayAllocate(
85249   sqlite3 *db,      /* Connection to notify of malloc failures */
85250   void *pArray,     /* Array of objects.  Might be reallocated */
85251   int szEntry,      /* Size of each object in the array */
85252   int *pnEntry,     /* Number of objects currently in use */
85253   int *pIdx         /* Write the index of a new slot here */
85254 ){
85255   char *z;
85256   int n = *pnEntry;
85257   if( (n & (n-1))==0 ){
85258     int sz = (n==0) ? 1 : 2*n;
85259     void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
85260     if( pNew==0 ){
85261       *pIdx = -1;
85262       return pArray;
85263     }
85264     pArray = pNew;
85265   }
85266   z = (char*)pArray;
85267   memset(&z[n * szEntry], 0, szEntry);
85268   *pIdx = n;
85269   ++*pnEntry;
85270   return pArray;
85271 }
85272
85273 /*
85274 ** Append a new element to the given IdList.  Create a new IdList if
85275 ** need be.
85276 **
85277 ** A new IdList is returned, or NULL if malloc() fails.
85278 */
85279 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
85280   int i;
85281   if( pList==0 ){
85282     pList = sqlite3DbMallocZero(db, sizeof(IdList) );
85283     if( pList==0 ) return 0;
85284   }
85285   pList->a = sqlite3ArrayAllocate(
85286       db,
85287       pList->a,
85288       sizeof(pList->a[0]),
85289       &pList->nId,
85290       &i
85291   );
85292   if( i<0 ){
85293     sqlite3IdListDelete(db, pList);
85294     return 0;
85295   }
85296   pList->a[i].zName = sqlite3NameFromToken(db, pToken);
85297   return pList;
85298 }
85299
85300 /*
85301 ** Delete an IdList.
85302 */
85303 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
85304   int i;
85305   if( pList==0 ) return;
85306   for(i=0; i<pList->nId; i++){
85307     sqlite3DbFree(db, pList->a[i].zName);
85308   }
85309   sqlite3DbFree(db, pList->a);
85310   sqlite3DbFree(db, pList);
85311 }
85312
85313 /*
85314 ** Return the index in pList of the identifier named zId.  Return -1
85315 ** if not found.
85316 */
85317 SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
85318   int i;
85319   if( pList==0 ) return -1;
85320   for(i=0; i<pList->nId; i++){
85321     if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
85322   }
85323   return -1;
85324 }
85325
85326 /*
85327 ** Expand the space allocated for the given SrcList object by
85328 ** creating nExtra new slots beginning at iStart.  iStart is zero based.
85329 ** New slots are zeroed.
85330 **
85331 ** For example, suppose a SrcList initially contains two entries: A,B.
85332 ** To append 3 new entries onto the end, do this:
85333 **
85334 **    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
85335 **
85336 ** After the call above it would contain:  A, B, nil, nil, nil.
85337 ** If the iStart argument had been 1 instead of 2, then the result
85338 ** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
85339 ** the iStart value would be 0.  The result then would
85340 ** be: nil, nil, nil, A, B.
85341 **
85342 ** If a memory allocation fails the SrcList is unchanged.  The
85343 ** db->mallocFailed flag will be set to true.
85344 */
85345 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
85346   sqlite3 *db,       /* Database connection to notify of OOM errors */
85347   SrcList *pSrc,     /* The SrcList to be enlarged */
85348   int nExtra,        /* Number of new slots to add to pSrc->a[] */
85349   int iStart         /* Index in pSrc->a[] of first new slot */
85350 ){
85351   int i;
85352
85353   /* Sanity checking on calling parameters */
85354   assert( iStart>=0 );
85355   assert( nExtra>=1 );
85356   assert( pSrc!=0 );
85357   assert( iStart<=pSrc->nSrc );
85358
85359   /* Allocate additional space if needed */
85360   if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
85361     SrcList *pNew;
85362     int nAlloc = pSrc->nSrc+nExtra;
85363     int nGot;
85364     pNew = sqlite3DbRealloc(db, pSrc,
85365                sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
85366     if( pNew==0 ){
85367       assert( db->mallocFailed );
85368       return pSrc;
85369     }
85370     pSrc = pNew;
85371     nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
85372     pSrc->nAlloc = (u16)nGot;
85373   }
85374
85375   /* Move existing slots that come after the newly inserted slots
85376   ** out of the way */
85377   for(i=pSrc->nSrc-1; i>=iStart; i--){
85378     pSrc->a[i+nExtra] = pSrc->a[i];
85379   }
85380   pSrc->nSrc += (i16)nExtra;
85381
85382   /* Zero the newly allocated slots */
85383   memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
85384   for(i=iStart; i<iStart+nExtra; i++){
85385     pSrc->a[i].iCursor = -1;
85386   }
85387
85388   /* Return a pointer to the enlarged SrcList */
85389   return pSrc;
85390 }
85391
85392
85393 /*
85394 ** Append a new table name to the given SrcList.  Create a new SrcList if
85395 ** need be.  A new entry is created in the SrcList even if pTable is NULL.
85396 **
85397 ** A SrcList is returned, or NULL if there is an OOM error.  The returned
85398 ** SrcList might be the same as the SrcList that was input or it might be
85399 ** a new one.  If an OOM error does occurs, then the prior value of pList
85400 ** that is input to this routine is automatically freed.
85401 **
85402 ** If pDatabase is not null, it means that the table has an optional
85403 ** database name prefix.  Like this:  "database.table".  The pDatabase
85404 ** points to the table name and the pTable points to the database name.
85405 ** The SrcList.a[].zName field is filled with the table name which might
85406 ** come from pTable (if pDatabase is NULL) or from pDatabase.  
85407 ** SrcList.a[].zDatabase is filled with the database name from pTable,
85408 ** or with NULL if no database is specified.
85409 **
85410 ** In other words, if call like this:
85411 **
85412 **         sqlite3SrcListAppend(D,A,B,0);
85413 **
85414 ** Then B is a table name and the database name is unspecified.  If called
85415 ** like this:
85416 **
85417 **         sqlite3SrcListAppend(D,A,B,C);
85418 **
85419 ** Then C is the table name and B is the database name.  If C is defined
85420 ** then so is B.  In other words, we never have a case where:
85421 **
85422 **         sqlite3SrcListAppend(D,A,0,C);
85423 **
85424 ** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
85425 ** before being added to the SrcList.
85426 */
85427 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
85428   sqlite3 *db,        /* Connection to notify of malloc failures */
85429   SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
85430   Token *pTable,      /* Table to append */
85431   Token *pDatabase    /* Database of the table */
85432 ){
85433   struct SrcList_item *pItem;
85434   assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
85435   if( pList==0 ){
85436     pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
85437     if( pList==0 ) return 0;
85438     pList->nAlloc = 1;
85439   }
85440   pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
85441   if( db->mallocFailed ){
85442     sqlite3SrcListDelete(db, pList);
85443     return 0;
85444   }
85445   pItem = &pList->a[pList->nSrc-1];
85446   if( pDatabase && pDatabase->z==0 ){
85447     pDatabase = 0;
85448   }
85449   if( pDatabase ){
85450     Token *pTemp = pDatabase;
85451     pDatabase = pTable;
85452     pTable = pTemp;
85453   }
85454   pItem->zName = sqlite3NameFromToken(db, pTable);
85455   pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
85456   return pList;
85457 }
85458
85459 /*
85460 ** Assign VdbeCursor index numbers to all tables in a SrcList
85461 */
85462 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
85463   int i;
85464   struct SrcList_item *pItem;
85465   assert(pList || pParse->db->mallocFailed );
85466   if( pList ){
85467     for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
85468       if( pItem->iCursor>=0 ) break;
85469       pItem->iCursor = pParse->nTab++;
85470       if( pItem->pSelect ){
85471         sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
85472       }
85473     }
85474   }
85475 }
85476
85477 /*
85478 ** Delete an entire SrcList including all its substructure.
85479 */
85480 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
85481   int i;
85482   struct SrcList_item *pItem;
85483   if( pList==0 ) return;
85484   for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
85485     sqlite3DbFree(db, pItem->zDatabase);
85486     sqlite3DbFree(db, pItem->zName);
85487     sqlite3DbFree(db, pItem->zAlias);
85488     sqlite3DbFree(db, pItem->zIndex);
85489     sqlite3DeleteTable(db, pItem->pTab);
85490     sqlite3SelectDelete(db, pItem->pSelect);
85491     sqlite3ExprDelete(db, pItem->pOn);
85492     sqlite3IdListDelete(db, pItem->pUsing);
85493   }
85494   sqlite3DbFree(db, pList);
85495 }
85496
85497 /*
85498 ** This routine is called by the parser to add a new term to the
85499 ** end of a growing FROM clause.  The "p" parameter is the part of
85500 ** the FROM clause that has already been constructed.  "p" is NULL
85501 ** if this is the first term of the FROM clause.  pTable and pDatabase
85502 ** are the name of the table and database named in the FROM clause term.
85503 ** pDatabase is NULL if the database name qualifier is missing - the
85504 ** usual case.  If the term has a alias, then pAlias points to the
85505 ** alias token.  If the term is a subquery, then pSubquery is the
85506 ** SELECT statement that the subquery encodes.  The pTable and
85507 ** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
85508 ** parameters are the content of the ON and USING clauses.
85509 **
85510 ** Return a new SrcList which encodes is the FROM with the new
85511 ** term added.
85512 */
85513 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
85514   Parse *pParse,          /* Parsing context */
85515   SrcList *p,             /* The left part of the FROM clause already seen */
85516   Token *pTable,          /* Name of the table to add to the FROM clause */
85517   Token *pDatabase,       /* Name of the database containing pTable */
85518   Token *pAlias,          /* The right-hand side of the AS subexpression */
85519   Select *pSubquery,      /* A subquery used in place of a table name */
85520   Expr *pOn,              /* The ON clause of a join */
85521   IdList *pUsing          /* The USING clause of a join */
85522 ){
85523   struct SrcList_item *pItem;
85524   sqlite3 *db = pParse->db;
85525   if( !p && (pOn || pUsing) ){
85526     sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s", 
85527       (pOn ? "ON" : "USING")
85528     );
85529     goto append_from_error;
85530   }
85531   p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
85532   if( p==0 || NEVER(p->nSrc==0) ){
85533     goto append_from_error;
85534   }
85535   pItem = &p->a[p->nSrc-1];
85536   assert( pAlias!=0 );
85537   if( pAlias->n ){
85538     pItem->zAlias = sqlite3NameFromToken(db, pAlias);
85539   }
85540   pItem->pSelect = pSubquery;
85541   pItem->pOn = pOn;
85542   pItem->pUsing = pUsing;
85543   return p;
85544
85545  append_from_error:
85546   assert( p==0 );
85547   sqlite3ExprDelete(db, pOn);
85548   sqlite3IdListDelete(db, pUsing);
85549   sqlite3SelectDelete(db, pSubquery);
85550   return 0;
85551 }
85552
85553 /*
85554 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added 
85555 ** element of the source-list passed as the second argument.
85556 */
85557 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
85558   assert( pIndexedBy!=0 );
85559   if( p && ALWAYS(p->nSrc>0) ){
85560     struct SrcList_item *pItem = &p->a[p->nSrc-1];
85561     assert( pItem->notIndexed==0 && pItem->zIndex==0 );
85562     if( pIndexedBy->n==1 && !pIndexedBy->z ){
85563       /* A "NOT INDEXED" clause was supplied. See parse.y 
85564       ** construct "indexed_opt" for details. */
85565       pItem->notIndexed = 1;
85566     }else{
85567       pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
85568     }
85569   }
85570 }
85571
85572 /*
85573 ** When building up a FROM clause in the parser, the join operator
85574 ** is initially attached to the left operand.  But the code generator
85575 ** expects the join operator to be on the right operand.  This routine
85576 ** Shifts all join operators from left to right for an entire FROM
85577 ** clause.
85578 **
85579 ** Example: Suppose the join is like this:
85580 **
85581 **           A natural cross join B
85582 **
85583 ** The operator is "natural cross join".  The A and B operands are stored
85584 ** in p->a[0] and p->a[1], respectively.  The parser initially stores the
85585 ** operator with A.  This routine shifts that operator over to B.
85586 */
85587 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
85588   if( p ){
85589     int i;
85590     assert( p->a || p->nSrc==0 );
85591     for(i=p->nSrc-1; i>0; i--){
85592       p->a[i].jointype = p->a[i-1].jointype;
85593     }
85594     p->a[0].jointype = 0;
85595   }
85596 }
85597
85598 /*
85599 ** Begin a transaction
85600 */
85601 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
85602   sqlite3 *db;
85603   Vdbe *v;
85604   int i;
85605
85606   assert( pParse!=0 );
85607   db = pParse->db;
85608   assert( db!=0 );
85609 /*  if( db->aDb[0].pBt==0 ) return; */
85610   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
85611     return;
85612   }
85613   v = sqlite3GetVdbe(pParse);
85614   if( !v ) return;
85615   if( type!=TK_DEFERRED ){
85616     for(i=0; i<db->nDb; i++){
85617       sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
85618       sqlite3VdbeUsesBtree(v, i);
85619     }
85620   }
85621   sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
85622 }
85623
85624 /*
85625 ** Commit a transaction
85626 */
85627 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
85628   Vdbe *v;
85629
85630   assert( pParse!=0 );
85631   assert( pParse->db!=0 );
85632   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
85633     return;
85634   }
85635   v = sqlite3GetVdbe(pParse);
85636   if( v ){
85637     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
85638   }
85639 }
85640
85641 /*
85642 ** Rollback a transaction
85643 */
85644 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
85645   Vdbe *v;
85646
85647   assert( pParse!=0 );
85648   assert( pParse->db!=0 );
85649   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
85650     return;
85651   }
85652   v = sqlite3GetVdbe(pParse);
85653   if( v ){
85654     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
85655   }
85656 }
85657
85658 /*
85659 ** This function is called by the parser when it parses a command to create,
85660 ** release or rollback an SQL savepoint. 
85661 */
85662 SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
85663   char *zName = sqlite3NameFromToken(pParse->db, pName);
85664   if( zName ){
85665     Vdbe *v = sqlite3GetVdbe(pParse);
85666 #ifndef SQLITE_OMIT_AUTHORIZATION
85667     static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
85668     assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
85669 #endif
85670     if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
85671       sqlite3DbFree(pParse->db, zName);
85672       return;
85673     }
85674     sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
85675   }
85676 }
85677
85678 /*
85679 ** Make sure the TEMP database is open and available for use.  Return
85680 ** the number of errors.  Leave any error messages in the pParse structure.
85681 */
85682 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
85683   sqlite3 *db = pParse->db;
85684   if( db->aDb[1].pBt==0 && !pParse->explain ){
85685     int rc;
85686     Btree *pBt;
85687     static const int flags = 
85688           SQLITE_OPEN_READWRITE |
85689           SQLITE_OPEN_CREATE |
85690           SQLITE_OPEN_EXCLUSIVE |
85691           SQLITE_OPEN_DELETEONCLOSE |
85692           SQLITE_OPEN_TEMP_DB;
85693
85694     rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
85695     if( rc!=SQLITE_OK ){
85696       sqlite3ErrorMsg(pParse, "unable to open a temporary database "
85697         "file for storing temporary tables");
85698       pParse->rc = rc;
85699       return 1;
85700     }
85701     db->aDb[1].pBt = pBt;
85702     assert( db->aDb[1].pSchema );
85703     if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
85704       db->mallocFailed = 1;
85705       return 1;
85706     }
85707   }
85708   return 0;
85709 }
85710
85711 /*
85712 ** Generate VDBE code that will verify the schema cookie and start
85713 ** a read-transaction for all named database files.
85714 **
85715 ** It is important that all schema cookies be verified and all
85716 ** read transactions be started before anything else happens in
85717 ** the VDBE program.  But this routine can be called after much other
85718 ** code has been generated.  So here is what we do:
85719 **
85720 ** The first time this routine is called, we code an OP_Goto that
85721 ** will jump to a subroutine at the end of the program.  Then we
85722 ** record every database that needs its schema verified in the
85723 ** pParse->cookieMask field.  Later, after all other code has been
85724 ** generated, the subroutine that does the cookie verifications and
85725 ** starts the transactions will be coded and the OP_Goto P2 value
85726 ** will be made to point to that subroutine.  The generation of the
85727 ** cookie verification subroutine code happens in sqlite3FinishCoding().
85728 **
85729 ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
85730 ** schema on any databases.  This can be used to position the OP_Goto
85731 ** early in the code, before we know if any database tables will be used.
85732 */
85733 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
85734   Parse *pToplevel = sqlite3ParseToplevel(pParse);
85735
85736 #ifndef SQLITE_OMIT_TRIGGER
85737   if( pToplevel!=pParse ){
85738     /* This branch is taken if a trigger is currently being coded. In this
85739     ** case, set cookieGoto to a non-zero value to show that this function
85740     ** has been called. This is used by the sqlite3ExprCodeConstants()
85741     ** function. */
85742     pParse->cookieGoto = -1;
85743   }
85744 #endif
85745   if( pToplevel->cookieGoto==0 ){
85746     Vdbe *v = sqlite3GetVdbe(pToplevel);
85747     if( v==0 ) return;  /* This only happens if there was a prior error */
85748     pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
85749   }
85750   if( iDb>=0 ){
85751     sqlite3 *db = pToplevel->db;
85752     yDbMask mask;
85753
85754     assert( iDb<db->nDb );
85755     assert( db->aDb[iDb].pBt!=0 || iDb==1 );
85756     assert( iDb<SQLITE_MAX_ATTACHED+2 );
85757     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
85758     mask = ((yDbMask)1)<<iDb;
85759     if( (pToplevel->cookieMask & mask)==0 ){
85760       pToplevel->cookieMask |= mask;
85761       pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
85762       if( !OMIT_TEMPDB && iDb==1 ){
85763         sqlite3OpenTempDatabase(pToplevel);
85764       }
85765     }
85766   }
85767 }
85768
85769 /*
85770 ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each 
85771 ** attached database. Otherwise, invoke it for the database named zDb only.
85772 */
85773 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
85774   sqlite3 *db = pParse->db;
85775   int i;
85776   for(i=0; i<db->nDb; i++){
85777     Db *pDb = &db->aDb[i];
85778     if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
85779       sqlite3CodeVerifySchema(pParse, i);
85780     }
85781   }
85782 }
85783
85784 /*
85785 ** Generate VDBE code that prepares for doing an operation that
85786 ** might change the database.
85787 **
85788 ** This routine starts a new transaction if we are not already within
85789 ** a transaction.  If we are already within a transaction, then a checkpoint
85790 ** is set if the setStatement parameter is true.  A checkpoint should
85791 ** be set for operations that might fail (due to a constraint) part of
85792 ** the way through and which will need to undo some writes without having to
85793 ** rollback the whole transaction.  For operations where all constraints
85794 ** can be checked before any changes are made to the database, it is never
85795 ** necessary to undo a write and the checkpoint should not be set.
85796 */
85797 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
85798   Parse *pToplevel = sqlite3ParseToplevel(pParse);
85799   sqlite3CodeVerifySchema(pParse, iDb);
85800   pToplevel->writeMask |= ((yDbMask)1)<<iDb;
85801   pToplevel->isMultiWrite |= setStatement;
85802 }
85803
85804 /*
85805 ** Indicate that the statement currently under construction might write
85806 ** more than one entry (example: deleting one row then inserting another,
85807 ** inserting multiple rows in a table, or inserting a row and index entries.)
85808 ** If an abort occurs after some of these writes have completed, then it will
85809 ** be necessary to undo the completed writes.
85810 */
85811 SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
85812   Parse *pToplevel = sqlite3ParseToplevel(pParse);
85813   pToplevel->isMultiWrite = 1;
85814 }
85815
85816 /* 
85817 ** The code generator calls this routine if is discovers that it is
85818 ** possible to abort a statement prior to completion.  In order to 
85819 ** perform this abort without corrupting the database, we need to make
85820 ** sure that the statement is protected by a statement transaction.
85821 **
85822 ** Technically, we only need to set the mayAbort flag if the
85823 ** isMultiWrite flag was previously set.  There is a time dependency
85824 ** such that the abort must occur after the multiwrite.  This makes
85825 ** some statements involving the REPLACE conflict resolution algorithm
85826 ** go a little faster.  But taking advantage of this time dependency
85827 ** makes it more difficult to prove that the code is correct (in 
85828 ** particular, it prevents us from writing an effective
85829 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
85830 ** to take the safe route and skip the optimization.
85831 */
85832 SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
85833   Parse *pToplevel = sqlite3ParseToplevel(pParse);
85834   pToplevel->mayAbort = 1;
85835 }
85836
85837 /*
85838 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
85839 ** error. The onError parameter determines which (if any) of the statement
85840 ** and/or current transaction is rolled back.
85841 */
85842 SQLITE_PRIVATE void sqlite3HaltConstraint(
85843   Parse *pParse,    /* Parsing context */
85844   int errCode,      /* extended error code */
85845   int onError,      /* Constraint type */
85846   char *p4,         /* Error message */
85847   int p4type        /* P4_STATIC or P4_TRANSIENT */
85848 ){
85849   Vdbe *v = sqlite3GetVdbe(pParse);
85850   assert( (errCode&0xff)==SQLITE_CONSTRAINT );
85851   if( onError==OE_Abort ){
85852     sqlite3MayAbort(pParse);
85853   }
85854   sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
85855 }
85856
85857 /*
85858 ** Check to see if pIndex uses the collating sequence pColl.  Return
85859 ** true if it does and false if it does not.
85860 */
85861 #ifndef SQLITE_OMIT_REINDEX
85862 static int collationMatch(const char *zColl, Index *pIndex){
85863   int i;
85864   assert( zColl!=0 );
85865   for(i=0; i<pIndex->nColumn; i++){
85866     const char *z = pIndex->azColl[i];
85867     assert( z!=0 );
85868     if( 0==sqlite3StrICmp(z, zColl) ){
85869       return 1;
85870     }
85871   }
85872   return 0;
85873 }
85874 #endif
85875
85876 /*
85877 ** Recompute all indices of pTab that use the collating sequence pColl.
85878 ** If pColl==0 then recompute all indices of pTab.
85879 */
85880 #ifndef SQLITE_OMIT_REINDEX
85881 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
85882   Index *pIndex;              /* An index associated with pTab */
85883
85884   for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
85885     if( zColl==0 || collationMatch(zColl, pIndex) ){
85886       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
85887       sqlite3BeginWriteOperation(pParse, 0, iDb);
85888       sqlite3RefillIndex(pParse, pIndex, -1);
85889     }
85890   }
85891 }
85892 #endif
85893
85894 /*
85895 ** Recompute all indices of all tables in all databases where the
85896 ** indices use the collating sequence pColl.  If pColl==0 then recompute
85897 ** all indices everywhere.
85898 */
85899 #ifndef SQLITE_OMIT_REINDEX
85900 static void reindexDatabases(Parse *pParse, char const *zColl){
85901   Db *pDb;                    /* A single database */
85902   int iDb;                    /* The database index number */
85903   sqlite3 *db = pParse->db;   /* The database connection */
85904   HashElem *k;                /* For looping over tables in pDb */
85905   Table *pTab;                /* A table in the database */
85906
85907   assert( sqlite3BtreeHoldsAllMutexes(db) );  /* Needed for schema access */
85908   for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
85909     assert( pDb!=0 );
85910     for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
85911       pTab = (Table*)sqliteHashData(k);
85912       reindexTable(pParse, pTab, zColl);
85913     }
85914   }
85915 }
85916 #endif
85917
85918 /*
85919 ** Generate code for the REINDEX command.
85920 **
85921 **        REINDEX                            -- 1
85922 **        REINDEX  <collation>               -- 2
85923 **        REINDEX  ?<database>.?<tablename>  -- 3
85924 **        REINDEX  ?<database>.?<indexname>  -- 4
85925 **
85926 ** Form 1 causes all indices in all attached databases to be rebuilt.
85927 ** Form 2 rebuilds all indices in all databases that use the named
85928 ** collating function.  Forms 3 and 4 rebuild the named index or all
85929 ** indices associated with the named table.
85930 */
85931 #ifndef SQLITE_OMIT_REINDEX
85932 SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
85933   CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
85934   char *z;                    /* Name of a table or index */
85935   const char *zDb;            /* Name of the database */
85936   Table *pTab;                /* A table in the database */
85937   Index *pIndex;              /* An index associated with pTab */
85938   int iDb;                    /* The database index number */
85939   sqlite3 *db = pParse->db;   /* The database connection */
85940   Token *pObjName;            /* Name of the table or index to be reindexed */
85941
85942   /* Read the database schema. If an error occurs, leave an error message
85943   ** and code in pParse and return NULL. */
85944   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
85945     return;
85946   }
85947
85948   if( pName1==0 ){
85949     reindexDatabases(pParse, 0);
85950     return;
85951   }else if( NEVER(pName2==0) || pName2->z==0 ){
85952     char *zColl;
85953     assert( pName1->z );
85954     zColl = sqlite3NameFromToken(pParse->db, pName1);
85955     if( !zColl ) return;
85956     pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
85957     if( pColl ){
85958       reindexDatabases(pParse, zColl);
85959       sqlite3DbFree(db, zColl);
85960       return;
85961     }
85962     sqlite3DbFree(db, zColl);
85963   }
85964   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
85965   if( iDb<0 ) return;
85966   z = sqlite3NameFromToken(db, pObjName);
85967   if( z==0 ) return;
85968   zDb = db->aDb[iDb].zName;
85969   pTab = sqlite3FindTable(db, z, zDb);
85970   if( pTab ){
85971     reindexTable(pParse, pTab, 0);
85972     sqlite3DbFree(db, z);
85973     return;
85974   }
85975   pIndex = sqlite3FindIndex(db, z, zDb);
85976   sqlite3DbFree(db, z);
85977   if( pIndex ){
85978     sqlite3BeginWriteOperation(pParse, 0, iDb);
85979     sqlite3RefillIndex(pParse, pIndex, -1);
85980     return;
85981   }
85982   sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
85983 }
85984 #endif
85985
85986 /*
85987 ** Return a dynamicly allocated KeyInfo structure that can be used
85988 ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
85989 **
85990 ** If successful, a pointer to the new structure is returned. In this case
85991 ** the caller is responsible for calling sqlite3DbFree(db, ) on the returned 
85992 ** pointer. If an error occurs (out of memory or missing collation 
85993 ** sequence), NULL is returned and the state of pParse updated to reflect
85994 ** the error.
85995 */
85996 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
85997   int i;
85998   int nCol = pIdx->nColumn;
85999   int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
86000   sqlite3 *db = pParse->db;
86001   KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
86002
86003   if( pKey ){
86004     pKey->db = pParse->db;
86005     pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
86006     assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
86007     for(i=0; i<nCol; i++){
86008       char *zColl = pIdx->azColl[i];
86009       assert( zColl );
86010       pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
86011       pKey->aSortOrder[i] = pIdx->aSortOrder[i];
86012     }
86013     pKey->nField = (u16)nCol;
86014   }
86015
86016   if( pParse->nErr ){
86017     sqlite3DbFree(db, pKey);
86018     pKey = 0;
86019   }
86020   return pKey;
86021 }
86022
86023 /************** End of build.c ***********************************************/
86024 /************** Begin file callback.c ****************************************/
86025 /*
86026 ** 2005 May 23 
86027 **
86028 ** The author disclaims copyright to this source code.  In place of
86029 ** a legal notice, here is a blessing:
86030 **
86031 **    May you do good and not evil.
86032 **    May you find forgiveness for yourself and forgive others.
86033 **    May you share freely, never taking more than you give.
86034 **
86035 *************************************************************************
86036 **
86037 ** This file contains functions used to access the internal hash tables
86038 ** of user defined functions and collation sequences.
86039 */
86040
86041
86042 /*
86043 ** Invoke the 'collation needed' callback to request a collation sequence
86044 ** in the encoding enc of name zName, length nName.
86045 */
86046 static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
86047   assert( !db->xCollNeeded || !db->xCollNeeded16 );
86048   if( db->xCollNeeded ){
86049     char *zExternal = sqlite3DbStrDup(db, zName);
86050     if( !zExternal ) return;
86051     db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
86052     sqlite3DbFree(db, zExternal);
86053   }
86054 #ifndef SQLITE_OMIT_UTF16
86055   if( db->xCollNeeded16 ){
86056     char const *zExternal;
86057     sqlite3_value *pTmp = sqlite3ValueNew(db);
86058     sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
86059     zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
86060     if( zExternal ){
86061       db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
86062     }
86063     sqlite3ValueFree(pTmp);
86064   }
86065 #endif
86066 }
86067
86068 /*
86069 ** This routine is called if the collation factory fails to deliver a
86070 ** collation function in the best encoding but there may be other versions
86071 ** of this collation function (for other text encodings) available. Use one
86072 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
86073 ** possible.
86074 */
86075 static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
86076   CollSeq *pColl2;
86077   char *z = pColl->zName;
86078   int i;
86079   static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
86080   for(i=0; i<3; i++){
86081     pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
86082     if( pColl2->xCmp!=0 ){
86083       memcpy(pColl, pColl2, sizeof(CollSeq));
86084       pColl->xDel = 0;         /* Do not copy the destructor */
86085       return SQLITE_OK;
86086     }
86087   }
86088   return SQLITE_ERROR;
86089 }
86090
86091 /*
86092 ** This function is responsible for invoking the collation factory callback
86093 ** or substituting a collation sequence of a different encoding when the
86094 ** requested collation sequence is not available in the desired encoding.
86095 ** 
86096 ** If it is not NULL, then pColl must point to the database native encoding 
86097 ** collation sequence with name zName, length nName.
86098 **
86099 ** The return value is either the collation sequence to be used in database
86100 ** db for collation type name zName, length nName, or NULL, if no collation
86101 ** sequence can be found.  If no collation is found, leave an error message.
86102 **
86103 ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
86104 */
86105 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
86106   Parse *pParse,        /* Parsing context */
86107   u8 enc,               /* The desired encoding for the collating sequence */
86108   CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
86109   const char *zName     /* Collating sequence name */
86110 ){
86111   CollSeq *p;
86112   sqlite3 *db = pParse->db;
86113
86114   p = pColl;
86115   if( !p ){
86116     p = sqlite3FindCollSeq(db, enc, zName, 0);
86117   }
86118   if( !p || !p->xCmp ){
86119     /* No collation sequence of this type for this encoding is registered.
86120     ** Call the collation factory to see if it can supply us with one.
86121     */
86122     callCollNeeded(db, enc, zName);
86123     p = sqlite3FindCollSeq(db, enc, zName, 0);
86124   }
86125   if( p && !p->xCmp && synthCollSeq(db, p) ){
86126     p = 0;
86127   }
86128   assert( !p || p->xCmp );
86129   if( p==0 ){
86130     sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
86131   }
86132   return p;
86133 }
86134
86135 /*
86136 ** This routine is called on a collation sequence before it is used to
86137 ** check that it is defined. An undefined collation sequence exists when
86138 ** a database is loaded that contains references to collation sequences
86139 ** that have not been defined by sqlite3_create_collation() etc.
86140 **
86141 ** If required, this routine calls the 'collation needed' callback to
86142 ** request a definition of the collating sequence. If this doesn't work, 
86143 ** an equivalent collating sequence that uses a text encoding different
86144 ** from the main database is substituted, if one is available.
86145 */
86146 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
86147   if( pColl ){
86148     const char *zName = pColl->zName;
86149     sqlite3 *db = pParse->db;
86150     CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
86151     if( !p ){
86152       return SQLITE_ERROR;
86153     }
86154     assert( p==pColl );
86155   }
86156   return SQLITE_OK;
86157 }
86158
86159
86160
86161 /*
86162 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
86163 ** specified by zName and nName is not found and parameter 'create' is
86164 ** true, then create a new entry. Otherwise return NULL.
86165 **
86166 ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
86167 ** array of three CollSeq structures. The first is the collation sequence
86168 ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
86169 **
86170 ** Stored immediately after the three collation sequences is a copy of
86171 ** the collation sequence name. A pointer to this string is stored in
86172 ** each collation sequence structure.
86173 */
86174 static CollSeq *findCollSeqEntry(
86175   sqlite3 *db,          /* Database connection */
86176   const char *zName,    /* Name of the collating sequence */
86177   int create            /* Create a new entry if true */
86178 ){
86179   CollSeq *pColl;
86180   int nName = sqlite3Strlen30(zName);
86181   pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
86182
86183   if( 0==pColl && create ){
86184     pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
86185     if( pColl ){
86186       CollSeq *pDel = 0;
86187       pColl[0].zName = (char*)&pColl[3];
86188       pColl[0].enc = SQLITE_UTF8;
86189       pColl[1].zName = (char*)&pColl[3];
86190       pColl[1].enc = SQLITE_UTF16LE;
86191       pColl[2].zName = (char*)&pColl[3];
86192       pColl[2].enc = SQLITE_UTF16BE;
86193       memcpy(pColl[0].zName, zName, nName);
86194       pColl[0].zName[nName] = 0;
86195       pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
86196
86197       /* If a malloc() failure occurred in sqlite3HashInsert(), it will 
86198       ** return the pColl pointer to be deleted (because it wasn't added
86199       ** to the hash table).
86200       */
86201       assert( pDel==0 || pDel==pColl );
86202       if( pDel!=0 ){
86203         db->mallocFailed = 1;
86204         sqlite3DbFree(db, pDel);
86205         pColl = 0;
86206       }
86207     }
86208   }
86209   return pColl;
86210 }
86211
86212 /*
86213 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
86214 ** Return the CollSeq* pointer for the collation sequence named zName
86215 ** for the encoding 'enc' from the database 'db'.
86216 **
86217 ** If the entry specified is not found and 'create' is true, then create a
86218 ** new entry.  Otherwise return NULL.
86219 **
86220 ** A separate function sqlite3LocateCollSeq() is a wrapper around
86221 ** this routine.  sqlite3LocateCollSeq() invokes the collation factory
86222 ** if necessary and generates an error message if the collating sequence
86223 ** cannot be found.
86224 **
86225 ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
86226 */
86227 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
86228   sqlite3 *db,
86229   u8 enc,
86230   const char *zName,
86231   int create
86232 ){
86233   CollSeq *pColl;
86234   if( zName ){
86235     pColl = findCollSeqEntry(db, zName, create);
86236   }else{
86237     pColl = db->pDfltColl;
86238   }
86239   assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
86240   assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
86241   if( pColl ) pColl += enc-1;
86242   return pColl;
86243 }
86244
86245 /* During the search for the best function definition, this procedure
86246 ** is called to test how well the function passed as the first argument
86247 ** matches the request for a function with nArg arguments in a system
86248 ** that uses encoding enc. The value returned indicates how well the
86249 ** request is matched. A higher value indicates a better match.
86250 **
86251 ** If nArg is -1 that means to only return a match (non-zero) if p->nArg
86252 ** is also -1.  In other words, we are searching for a function that
86253 ** takes a variable number of arguments.
86254 **
86255 ** If nArg is -2 that means that we are searching for any function 
86256 ** regardless of the number of arguments it uses, so return a positive
86257 ** match score for any
86258 **
86259 ** The returned value is always between 0 and 6, as follows:
86260 **
86261 ** 0: Not a match.
86262 ** 1: UTF8/16 conversion required and function takes any number of arguments.
86263 ** 2: UTF16 byte order change required and function takes any number of args.
86264 ** 3: encoding matches and function takes any number of arguments
86265 ** 4: UTF8/16 conversion required - argument count matches exactly
86266 ** 5: UTF16 byte order conversion required - argument count matches exactly
86267 ** 6: Perfect match:  encoding and argument count match exactly.
86268 **
86269 ** If nArg==(-2) then any function with a non-null xStep or xFunc is
86270 ** a perfect match and any function with both xStep and xFunc NULL is
86271 ** a non-match.
86272 */
86273 #define FUNC_PERFECT_MATCH 6  /* The score for a perfect match */
86274 static int matchQuality(
86275   FuncDef *p,     /* The function we are evaluating for match quality */
86276   int nArg,       /* Desired number of arguments.  (-1)==any */
86277   u8 enc          /* Desired text encoding */
86278 ){
86279   int match;
86280
86281   /* nArg of -2 is a special case */
86282   if( nArg==(-2) ) return (p->xFunc==0 && p->xStep==0) ? 0 : FUNC_PERFECT_MATCH;
86283
86284   /* Wrong number of arguments means "no match" */
86285   if( p->nArg!=nArg && p->nArg>=0 ) return 0;
86286
86287   /* Give a better score to a function with a specific number of arguments
86288   ** than to function that accepts any number of arguments. */
86289   if( p->nArg==nArg ){
86290     match = 4;
86291   }else{
86292     match = 1;
86293   }
86294
86295   /* Bonus points if the text encoding matches */
86296   if( enc==p->iPrefEnc ){
86297     match += 2;  /* Exact encoding match */
86298   }else if( (enc & p->iPrefEnc & 2)!=0 ){
86299     match += 1;  /* Both are UTF16, but with different byte orders */
86300   }
86301
86302   return match;
86303 }
86304
86305 /*
86306 ** Search a FuncDefHash for a function with the given name.  Return
86307 ** a pointer to the matching FuncDef if found, or 0 if there is no match.
86308 */
86309 static FuncDef *functionSearch(
86310   FuncDefHash *pHash,  /* Hash table to search */
86311   int h,               /* Hash of the name */
86312   const char *zFunc,   /* Name of function */
86313   int nFunc            /* Number of bytes in zFunc */
86314 ){
86315   FuncDef *p;
86316   for(p=pHash->a[h]; p; p=p->pHash){
86317     if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
86318       return p;
86319     }
86320   }
86321   return 0;
86322 }
86323
86324 /*
86325 ** Insert a new FuncDef into a FuncDefHash hash table.
86326 */
86327 SQLITE_PRIVATE void sqlite3FuncDefInsert(
86328   FuncDefHash *pHash,  /* The hash table into which to insert */
86329   FuncDef *pDef        /* The function definition to insert */
86330 ){
86331   FuncDef *pOther;
86332   int nName = sqlite3Strlen30(pDef->zName);
86333   u8 c1 = (u8)pDef->zName[0];
86334   int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
86335   pOther = functionSearch(pHash, h, pDef->zName, nName);
86336   if( pOther ){
86337     assert( pOther!=pDef && pOther->pNext!=pDef );
86338     pDef->pNext = pOther->pNext;
86339     pOther->pNext = pDef;
86340   }else{
86341     pDef->pNext = 0;
86342     pDef->pHash = pHash->a[h];
86343     pHash->a[h] = pDef;
86344   }
86345 }
86346   
86347   
86348
86349 /*
86350 ** Locate a user function given a name, a number of arguments and a flag
86351 ** indicating whether the function prefers UTF-16 over UTF-8.  Return a
86352 ** pointer to the FuncDef structure that defines that function, or return
86353 ** NULL if the function does not exist.
86354 **
86355 ** If the createFlag argument is true, then a new (blank) FuncDef
86356 ** structure is created and liked into the "db" structure if a
86357 ** no matching function previously existed.
86358 **
86359 ** If nArg is -2, then the first valid function found is returned.  A
86360 ** function is valid if either xFunc or xStep is non-zero.  The nArg==(-2)
86361 ** case is used to see if zName is a valid function name for some number
86362 ** of arguments.  If nArg is -2, then createFlag must be 0.
86363 **
86364 ** If createFlag is false, then a function with the required name and
86365 ** number of arguments may be returned even if the eTextRep flag does not
86366 ** match that requested.
86367 */
86368 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
86369   sqlite3 *db,       /* An open database */
86370   const char *zName, /* Name of the function.  Not null-terminated */
86371   int nName,         /* Number of characters in the name */
86372   int nArg,          /* Number of arguments.  -1 means any number */
86373   u8 enc,            /* Preferred text encoding */
86374   u8 createFlag      /* Create new entry if true and does not otherwise exist */
86375 ){
86376   FuncDef *p;         /* Iterator variable */
86377   FuncDef *pBest = 0; /* Best match found so far */
86378   int bestScore = 0;  /* Score of best match */
86379   int h;              /* Hash value */
86380
86381   assert( nArg>=(-2) );
86382   assert( nArg>=(-1) || createFlag==0 );
86383   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
86384   h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
86385
86386   /* First search for a match amongst the application-defined functions.
86387   */
86388   p = functionSearch(&db->aFunc, h, zName, nName);
86389   while( p ){
86390     int score = matchQuality(p, nArg, enc);
86391     if( score>bestScore ){
86392       pBest = p;
86393       bestScore = score;
86394     }
86395     p = p->pNext;
86396   }
86397
86398   /* If no match is found, search the built-in functions.
86399   **
86400   ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
86401   ** functions even if a prior app-defined function was found.  And give
86402   ** priority to built-in functions.
86403   **
86404   ** Except, if createFlag is true, that means that we are trying to
86405   ** install a new function.  Whatever FuncDef structure is returned it will
86406   ** have fields overwritten with new information appropriate for the
86407   ** new function.  But the FuncDefs for built-in functions are read-only.
86408   ** So we must not search for built-ins when creating a new function.
86409   */ 
86410   if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
86411     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
86412     bestScore = 0;
86413     p = functionSearch(pHash, h, zName, nName);
86414     while( p ){
86415       int score = matchQuality(p, nArg, enc);
86416       if( score>bestScore ){
86417         pBest = p;
86418         bestScore = score;
86419       }
86420       p = p->pNext;
86421     }
86422   }
86423
86424   /* If the createFlag parameter is true and the search did not reveal an
86425   ** exact match for the name, number of arguments and encoding, then add a
86426   ** new entry to the hash table and return it.
86427   */
86428   if( createFlag && bestScore<FUNC_PERFECT_MATCH && 
86429       (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
86430     pBest->zName = (char *)&pBest[1];
86431     pBest->nArg = (u16)nArg;
86432     pBest->iPrefEnc = enc;
86433     memcpy(pBest->zName, zName, nName);
86434     pBest->zName[nName] = 0;
86435     sqlite3FuncDefInsert(&db->aFunc, pBest);
86436   }
86437
86438   if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
86439     return pBest;
86440   }
86441   return 0;
86442 }
86443
86444 /*
86445 ** Free all resources held by the schema structure. The void* argument points
86446 ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the 
86447 ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
86448 ** of the schema hash tables).
86449 **
86450 ** The Schema.cache_size variable is not cleared.
86451 */
86452 SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
86453   Hash temp1;
86454   Hash temp2;
86455   HashElem *pElem;
86456   Schema *pSchema = (Schema *)p;
86457
86458   temp1 = pSchema->tblHash;
86459   temp2 = pSchema->trigHash;
86460   sqlite3HashInit(&pSchema->trigHash);
86461   sqlite3HashClear(&pSchema->idxHash);
86462   for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
86463     sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
86464   }
86465   sqlite3HashClear(&temp2);
86466   sqlite3HashInit(&pSchema->tblHash);
86467   for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
86468     Table *pTab = sqliteHashData(pElem);
86469     sqlite3DeleteTable(0, pTab);
86470   }
86471   sqlite3HashClear(&temp1);
86472   sqlite3HashClear(&pSchema->fkeyHash);
86473   pSchema->pSeqTab = 0;
86474   if( pSchema->flags & DB_SchemaLoaded ){
86475     pSchema->iGeneration++;
86476     pSchema->flags &= ~DB_SchemaLoaded;
86477   }
86478 }
86479
86480 /*
86481 ** Find and return the schema associated with a BTree.  Create
86482 ** a new one if necessary.
86483 */
86484 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
86485   Schema * p;
86486   if( pBt ){
86487     p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
86488   }else{
86489     p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
86490   }
86491   if( !p ){
86492     db->mallocFailed = 1;
86493   }else if ( 0==p->file_format ){
86494     sqlite3HashInit(&p->tblHash);
86495     sqlite3HashInit(&p->idxHash);
86496     sqlite3HashInit(&p->trigHash);
86497     sqlite3HashInit(&p->fkeyHash);
86498     p->enc = SQLITE_UTF8;
86499   }
86500   return p;
86501 }
86502
86503 /************** End of callback.c ********************************************/
86504 /************** Begin file delete.c ******************************************/
86505 /*
86506 ** 2001 September 15
86507 **
86508 ** The author disclaims copyright to this source code.  In place of
86509 ** a legal notice, here is a blessing:
86510 **
86511 **    May you do good and not evil.
86512 **    May you find forgiveness for yourself and forgive others.
86513 **    May you share freely, never taking more than you give.
86514 **
86515 *************************************************************************
86516 ** This file contains C code routines that are called by the parser
86517 ** in order to generate code for DELETE FROM statements.
86518 */
86519
86520 /*
86521 ** While a SrcList can in general represent multiple tables and subqueries
86522 ** (as in the FROM clause of a SELECT statement) in this case it contains
86523 ** the name of a single table, as one might find in an INSERT, DELETE,
86524 ** or UPDATE statement.  Look up that table in the symbol table and
86525 ** return a pointer.  Set an error message and return NULL if the table 
86526 ** name is not found or if any other error occurs.
86527 **
86528 ** The following fields are initialized appropriate in pSrc:
86529 **
86530 **    pSrc->a[0].pTab       Pointer to the Table object
86531 **    pSrc->a[0].pIndex     Pointer to the INDEXED BY index, if there is one
86532 **
86533 */
86534 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
86535   struct SrcList_item *pItem = pSrc->a;
86536   Table *pTab;
86537   assert( pItem && pSrc->nSrc==1 );
86538   pTab = sqlite3LocateTableItem(pParse, 0, pItem);
86539   sqlite3DeleteTable(pParse->db, pItem->pTab);
86540   pItem->pTab = pTab;
86541   if( pTab ){
86542     pTab->nRef++;
86543   }
86544   if( sqlite3IndexedByLookup(pParse, pItem) ){
86545     pTab = 0;
86546   }
86547   return pTab;
86548 }
86549
86550 /*
86551 ** Check to make sure the given table is writable.  If it is not
86552 ** writable, generate an error message and return 1.  If it is
86553 ** writable return 0;
86554 */
86555 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
86556   /* A table is not writable under the following circumstances:
86557   **
86558   **   1) It is a virtual table and no implementation of the xUpdate method
86559   **      has been provided, or
86560   **   2) It is a system table (i.e. sqlite_master), this call is not
86561   **      part of a nested parse and writable_schema pragma has not 
86562   **      been specified.
86563   **
86564   ** In either case leave an error message in pParse and return non-zero.
86565   */
86566   if( ( IsVirtual(pTab) 
86567      && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
86568    || ( (pTab->tabFlags & TF_Readonly)!=0
86569      && (pParse->db->flags & SQLITE_WriteSchema)==0
86570      && pParse->nested==0 )
86571   ){
86572     sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
86573     return 1;
86574   }
86575
86576 #ifndef SQLITE_OMIT_VIEW
86577   if( !viewOk && pTab->pSelect ){
86578     sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
86579     return 1;
86580   }
86581 #endif
86582   return 0;
86583 }
86584
86585
86586 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
86587 /*
86588 ** Evaluate a view and store its result in an ephemeral table.  The
86589 ** pWhere argument is an optional WHERE clause that restricts the
86590 ** set of rows in the view that are to be added to the ephemeral table.
86591 */
86592 SQLITE_PRIVATE void sqlite3MaterializeView(
86593   Parse *pParse,       /* Parsing context */
86594   Table *pView,        /* View definition */
86595   Expr *pWhere,        /* Optional WHERE clause to be added */
86596   int iCur             /* Cursor number for ephemerial table */
86597 ){
86598   SelectDest dest;
86599   Select *pSel;
86600   SrcList *pFrom;
86601   sqlite3 *db = pParse->db;
86602   int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
86603
86604   pWhere = sqlite3ExprDup(db, pWhere, 0);
86605   pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
86606
86607   if( pFrom ){
86608     assert( pFrom->nSrc==1 );
86609     pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
86610     pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
86611     assert( pFrom->a[0].pOn==0 );
86612     assert( pFrom->a[0].pUsing==0 );
86613   }
86614
86615   pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
86616   if( pSel ) pSel->selFlags |= SF_Materialize;
86617
86618   sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
86619   sqlite3Select(pParse, pSel, &dest);
86620   sqlite3SelectDelete(db, pSel);
86621 }
86622 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
86623
86624 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
86625 /*
86626 ** Generate an expression tree to implement the WHERE, ORDER BY,
86627 ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
86628 **
86629 **     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
86630 **                            \__________________________/
86631 **                               pLimitWhere (pInClause)
86632 */
86633 SQLITE_PRIVATE Expr *sqlite3LimitWhere(
86634   Parse *pParse,               /* The parser context */
86635   SrcList *pSrc,               /* the FROM clause -- which tables to scan */
86636   Expr *pWhere,                /* The WHERE clause.  May be null */
86637   ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
86638   Expr *pLimit,                /* The LIMIT clause.  May be null */
86639   Expr *pOffset,               /* The OFFSET clause.  May be null */
86640   char *zStmtType              /* Either DELETE or UPDATE.  For error messages. */
86641 ){
86642   Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
86643   Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
86644   Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
86645   ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
86646   SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
86647   Select *pSelect = NULL;      /* Complete SELECT tree */
86648
86649   /* Check that there isn't an ORDER BY without a LIMIT clause.
86650   */
86651   if( pOrderBy && (pLimit == 0) ) {
86652     sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
86653     goto limit_where_cleanup_2;
86654   }
86655
86656   /* We only need to generate a select expression if there
86657   ** is a limit/offset term to enforce.
86658   */
86659   if( pLimit == 0 ) {
86660     /* if pLimit is null, pOffset will always be null as well. */
86661     assert( pOffset == 0 );
86662     return pWhere;
86663   }
86664
86665   /* Generate a select expression tree to enforce the limit/offset 
86666   ** term for the DELETE or UPDATE statement.  For example:
86667   **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
86668   ** becomes:
86669   **   DELETE FROM table_a WHERE rowid IN ( 
86670   **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
86671   **   );
86672   */
86673
86674   pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
86675   if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
86676   pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
86677   if( pEList == 0 ) goto limit_where_cleanup_2;
86678
86679   /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
86680   ** and the SELECT subtree. */
86681   pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
86682   if( pSelectSrc == 0 ) {
86683     sqlite3ExprListDelete(pParse->db, pEList);
86684     goto limit_where_cleanup_2;
86685   }
86686
86687   /* generate the SELECT expression tree. */
86688   pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
86689                              pOrderBy,0,pLimit,pOffset);
86690   if( pSelect == 0 ) return 0;
86691
86692   /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
86693   pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
86694   if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
86695   pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
86696   if( pInClause == 0 ) goto limit_where_cleanup_1;
86697
86698   pInClause->x.pSelect = pSelect;
86699   pInClause->flags |= EP_xIsSelect;
86700   sqlite3ExprSetHeight(pParse, pInClause);
86701   return pInClause;
86702
86703   /* something went wrong. clean up anything allocated. */
86704 limit_where_cleanup_1:
86705   sqlite3SelectDelete(pParse->db, pSelect);
86706   return 0;
86707
86708 limit_where_cleanup_2:
86709   sqlite3ExprDelete(pParse->db, pWhere);
86710   sqlite3ExprListDelete(pParse->db, pOrderBy);
86711   sqlite3ExprDelete(pParse->db, pLimit);
86712   sqlite3ExprDelete(pParse->db, pOffset);
86713   return 0;
86714 }
86715 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
86716
86717 /*
86718 ** Generate code for a DELETE FROM statement.
86719 **
86720 **     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
86721 **                 \________/       \________________/
86722 **                  pTabList              pWhere
86723 */
86724 SQLITE_PRIVATE void sqlite3DeleteFrom(
86725   Parse *pParse,         /* The parser context */
86726   SrcList *pTabList,     /* The table from which we should delete things */
86727   Expr *pWhere           /* The WHERE clause.  May be null */
86728 ){
86729   Vdbe *v;               /* The virtual database engine */
86730   Table *pTab;           /* The table from which records will be deleted */
86731   const char *zDb;       /* Name of database holding pTab */
86732   int end, addr = 0;     /* A couple addresses of generated code */
86733   int i;                 /* Loop counter */
86734   WhereInfo *pWInfo;     /* Information about the WHERE clause */
86735   Index *pIdx;           /* For looping over indices of the table */
86736   int iCur;              /* VDBE Cursor number for pTab */
86737   sqlite3 *db;           /* Main database structure */
86738   AuthContext sContext;  /* Authorization context */
86739   NameContext sNC;       /* Name context to resolve expressions in */
86740   int iDb;               /* Database number */
86741   int memCnt = -1;       /* Memory cell used for change counting */
86742   int rcauth;            /* Value returned by authorization callback */
86743
86744 #ifndef SQLITE_OMIT_TRIGGER
86745   int isView;                  /* True if attempting to delete from a view */
86746   Trigger *pTrigger;           /* List of table triggers, if required */
86747 #endif
86748
86749   memset(&sContext, 0, sizeof(sContext));
86750   db = pParse->db;
86751   if( pParse->nErr || db->mallocFailed ){
86752     goto delete_from_cleanup;
86753   }
86754   assert( pTabList->nSrc==1 );
86755
86756   /* Locate the table which we want to delete.  This table has to be
86757   ** put in an SrcList structure because some of the subroutines we
86758   ** will be calling are designed to work with multiple tables and expect
86759   ** an SrcList* parameter instead of just a Table* parameter.
86760   */
86761   pTab = sqlite3SrcListLookup(pParse, pTabList);
86762   if( pTab==0 )  goto delete_from_cleanup;
86763
86764   /* Figure out if we have any triggers and if the table being
86765   ** deleted from is a view
86766   */
86767 #ifndef SQLITE_OMIT_TRIGGER
86768   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
86769   isView = pTab->pSelect!=0;
86770 #else
86771 # define pTrigger 0
86772 # define isView 0
86773 #endif
86774 #ifdef SQLITE_OMIT_VIEW
86775 # undef isView
86776 # define isView 0
86777 #endif
86778
86779   /* If pTab is really a view, make sure it has been initialized.
86780   */
86781   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
86782     goto delete_from_cleanup;
86783   }
86784
86785   if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
86786     goto delete_from_cleanup;
86787   }
86788   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
86789   assert( iDb<db->nDb );
86790   zDb = db->aDb[iDb].zName;
86791   rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
86792   assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
86793   if( rcauth==SQLITE_DENY ){
86794     goto delete_from_cleanup;
86795   }
86796   assert(!isView || pTrigger);
86797
86798   /* Assign  cursor number to the table and all its indices.
86799   */
86800   assert( pTabList->nSrc==1 );
86801   iCur = pTabList->a[0].iCursor = pParse->nTab++;
86802   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
86803     pParse->nTab++;
86804   }
86805
86806   /* Start the view context
86807   */
86808   if( isView ){
86809     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
86810   }
86811
86812   /* Begin generating code.
86813   */
86814   v = sqlite3GetVdbe(pParse);
86815   if( v==0 ){
86816     goto delete_from_cleanup;
86817   }
86818   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
86819   sqlite3BeginWriteOperation(pParse, 1, iDb);
86820
86821   /* If we are trying to delete from a view, realize that view into
86822   ** a ephemeral table.
86823   */
86824 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
86825   if( isView ){
86826     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
86827   }
86828 #endif
86829
86830   /* Resolve the column names in the WHERE clause.
86831   */
86832   memset(&sNC, 0, sizeof(sNC));
86833   sNC.pParse = pParse;
86834   sNC.pSrcList = pTabList;
86835   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
86836     goto delete_from_cleanup;
86837   }
86838
86839   /* Initialize the counter of the number of rows deleted, if
86840   ** we are counting rows.
86841   */
86842   if( db->flags & SQLITE_CountRows ){
86843     memCnt = ++pParse->nMem;
86844     sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
86845   }
86846
86847 #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
86848   /* Special case: A DELETE without a WHERE clause deletes everything.
86849   ** It is easier just to erase the whole table. Prior to version 3.6.5,
86850   ** this optimization caused the row change count (the value returned by 
86851   ** API function sqlite3_count_changes) to be set incorrectly.  */
86852   if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab) 
86853    && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
86854   ){
86855     assert( !isView );
86856     sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
86857                       pTab->zName, P4_STATIC);
86858     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
86859       assert( pIdx->pSchema==pTab->pSchema );
86860       sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
86861     }
86862   }else
86863 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
86864   /* The usual case: There is a WHERE clause so we have to scan through
86865   ** the table and pick which records to delete.
86866   */
86867   {
86868     int iRowSet = ++pParse->nMem;   /* Register for rowset of rows to delete */
86869     int iRowid = ++pParse->nMem;    /* Used for storing rowid values. */
86870     int regRowid;                   /* Actual register containing rowids */
86871
86872     /* Collect rowids of every row to be deleted.
86873     */
86874     sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
86875     pWInfo = sqlite3WhereBegin(
86876         pParse, pTabList, pWhere, 0, 0, WHERE_DUPLICATES_OK, 0
86877     );
86878     if( pWInfo==0 ) goto delete_from_cleanup;
86879     regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid, 0);
86880     sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
86881     if( db->flags & SQLITE_CountRows ){
86882       sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
86883     }
86884     sqlite3WhereEnd(pWInfo);
86885
86886     /* Delete every item whose key was written to the list during the
86887     ** database scan.  We have to delete items after the scan is complete
86888     ** because deleting an item can change the scan order.  */
86889     end = sqlite3VdbeMakeLabel(v);
86890
86891     /* Unless this is a view, open cursors for the table we are 
86892     ** deleting from and all its indices. If this is a view, then the
86893     ** only effect this statement has is to fire the INSTEAD OF 
86894     ** triggers.  */
86895     if( !isView ){
86896       sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
86897     }
86898
86899     addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
86900
86901     /* Delete the row */
86902 #ifndef SQLITE_OMIT_VIRTUALTABLE
86903     if( IsVirtual(pTab) ){
86904       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
86905       sqlite3VtabMakeWritable(pParse, pTab);
86906       sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
86907       sqlite3VdbeChangeP5(v, OE_Abort);
86908       sqlite3MayAbort(pParse);
86909     }else
86910 #endif
86911     {
86912       int count = (pParse->nested==0);    /* True to count changes */
86913       sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);
86914     }
86915
86916     /* End of the delete loop */
86917     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
86918     sqlite3VdbeResolveLabel(v, end);
86919
86920     /* Close the cursors open on the table and its indexes. */
86921     if( !isView && !IsVirtual(pTab) ){
86922       for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
86923         sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
86924       }
86925       sqlite3VdbeAddOp1(v, OP_Close, iCur);
86926     }
86927   }
86928
86929   /* Update the sqlite_sequence table by storing the content of the
86930   ** maximum rowid counter values recorded while inserting into
86931   ** autoincrement tables.
86932   */
86933   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
86934     sqlite3AutoincrementEnd(pParse);
86935   }
86936
86937   /* Return the number of rows that were deleted. If this routine is 
86938   ** generating code because of a call to sqlite3NestedParse(), do not
86939   ** invoke the callback function.
86940   */
86941   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
86942     sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
86943     sqlite3VdbeSetNumCols(v, 1);
86944     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
86945   }
86946
86947 delete_from_cleanup:
86948   sqlite3AuthContextPop(&sContext);
86949   sqlite3SrcListDelete(db, pTabList);
86950   sqlite3ExprDelete(db, pWhere);
86951   return;
86952 }
86953 /* Make sure "isView" and other macros defined above are undefined. Otherwise
86954 ** thely may interfere with compilation of other functions in this file
86955 ** (or in another file, if this file becomes part of the amalgamation).  */
86956 #ifdef isView
86957  #undef isView
86958 #endif
86959 #ifdef pTrigger
86960  #undef pTrigger
86961 #endif
86962
86963 /*
86964 ** This routine generates VDBE code that causes a single row of a
86965 ** single table to be deleted.
86966 **
86967 ** The VDBE must be in a particular state when this routine is called.
86968 ** These are the requirements:
86969 **
86970 **   1.  A read/write cursor pointing to pTab, the table containing the row
86971 **       to be deleted, must be opened as cursor number $iCur.
86972 **
86973 **   2.  Read/write cursors for all indices of pTab must be open as
86974 **       cursor number base+i for the i-th index.
86975 **
86976 **   3.  The record number of the row to be deleted must be stored in
86977 **       memory cell iRowid.
86978 **
86979 ** This routine generates code to remove both the table record and all 
86980 ** index entries that point to that record.
86981 */
86982 SQLITE_PRIVATE void sqlite3GenerateRowDelete(
86983   Parse *pParse,     /* Parsing context */
86984   Table *pTab,       /* Table containing the row to be deleted */
86985   int iCur,          /* Cursor number for the table */
86986   int iRowid,        /* Memory cell that contains the rowid to delete */
86987   int count,         /* If non-zero, increment the row change counter */
86988   Trigger *pTrigger, /* List of triggers to (potentially) fire */
86989   int onconf         /* Default ON CONFLICT policy for triggers */
86990 ){
86991   Vdbe *v = pParse->pVdbe;        /* Vdbe */
86992   int iOld = 0;                   /* First register in OLD.* array */
86993   int iLabel;                     /* Label resolved to end of generated code */
86994
86995   /* Vdbe is guaranteed to have been allocated by this stage. */
86996   assert( v );
86997
86998   /* Seek cursor iCur to the row to delete. If this row no longer exists 
86999   ** (this can happen if a trigger program has already deleted it), do
87000   ** not attempt to delete it or fire any DELETE triggers.  */
87001   iLabel = sqlite3VdbeMakeLabel(v);
87002   sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
87003  
87004   /* If there are any triggers to fire, allocate a range of registers to
87005   ** use for the old.* references in the triggers.  */
87006   if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
87007     u32 mask;                     /* Mask of OLD.* columns in use */
87008     int iCol;                     /* Iterator used while populating OLD.* */
87009
87010     /* TODO: Could use temporary registers here. Also could attempt to
87011     ** avoid copying the contents of the rowid register.  */
87012     mask = sqlite3TriggerColmask(
87013         pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
87014     );
87015     mask |= sqlite3FkOldmask(pParse, pTab);
87016     iOld = pParse->nMem+1;
87017     pParse->nMem += (1 + pTab->nCol);
87018
87019     /* Populate the OLD.* pseudo-table register array. These values will be 
87020     ** used by any BEFORE and AFTER triggers that exist.  */
87021     sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
87022     for(iCol=0; iCol<pTab->nCol; iCol++){
87023       if( mask==0xffffffff || mask&(1<<iCol) ){
87024         sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol, iOld+iCol+1);
87025       }
87026     }
87027
87028     /* Invoke BEFORE DELETE trigger programs. */
87029     sqlite3CodeRowTrigger(pParse, pTrigger, 
87030         TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
87031     );
87032
87033     /* Seek the cursor to the row to be deleted again. It may be that
87034     ** the BEFORE triggers coded above have already removed the row
87035     ** being deleted. Do not attempt to delete the row a second time, and 
87036     ** do not fire AFTER triggers.  */
87037     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
87038
87039     /* Do FK processing. This call checks that any FK constraints that
87040     ** refer to this table (i.e. constraints attached to other tables) 
87041     ** are not violated by deleting this row.  */
87042     sqlite3FkCheck(pParse, pTab, iOld, 0);
87043   }
87044
87045   /* Delete the index and table entries. Skip this step if pTab is really
87046   ** a view (in which case the only effect of the DELETE statement is to
87047   ** fire the INSTEAD OF triggers).  */ 
87048   if( pTab->pSelect==0 ){
87049     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
87050     sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
87051     if( count ){
87052       sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
87053     }
87054   }
87055
87056   /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
87057   ** handle rows (possibly in other tables) that refer via a foreign key
87058   ** to the row just deleted. */ 
87059   sqlite3FkActions(pParse, pTab, 0, iOld);
87060
87061   /* Invoke AFTER DELETE trigger programs. */
87062   sqlite3CodeRowTrigger(pParse, pTrigger, 
87063       TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
87064   );
87065
87066   /* Jump here if the row had already been deleted before any BEFORE
87067   ** trigger programs were invoked. Or if a trigger program throws a 
87068   ** RAISE(IGNORE) exception.  */
87069   sqlite3VdbeResolveLabel(v, iLabel);
87070 }
87071
87072 /*
87073 ** This routine generates VDBE code that causes the deletion of all
87074 ** index entries associated with a single row of a single table.
87075 **
87076 ** The VDBE must be in a particular state when this routine is called.
87077 ** These are the requirements:
87078 **
87079 **   1.  A read/write cursor pointing to pTab, the table containing the row
87080 **       to be deleted, must be opened as cursor number "iCur".
87081 **
87082 **   2.  Read/write cursors for all indices of pTab must be open as
87083 **       cursor number iCur+i for the i-th index.
87084 **
87085 **   3.  The "iCur" cursor must be pointing to the row that is to be
87086 **       deleted.
87087 */
87088 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
87089   Parse *pParse,     /* Parsing and code generating context */
87090   Table *pTab,       /* Table containing the row to be deleted */
87091   int iCur,          /* Cursor number for the table */
87092   int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
87093 ){
87094   int i;
87095   Index *pIdx;
87096   int r1;
87097
87098   for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
87099     if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
87100     r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);
87101     sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);
87102   }
87103 }
87104
87105 /*
87106 ** Generate code that will assemble an index key and put it in register
87107 ** regOut.  The key with be for index pIdx which is an index on pTab.
87108 ** iCur is the index of a cursor open on the pTab table and pointing to
87109 ** the entry that needs indexing.
87110 **
87111 ** Return a register number which is the first in a block of
87112 ** registers that holds the elements of the index key.  The
87113 ** block of registers has already been deallocated by the time
87114 ** this routine returns.
87115 */
87116 SQLITE_PRIVATE int sqlite3GenerateIndexKey(
87117   Parse *pParse,     /* Parsing context */
87118   Index *pIdx,       /* The index for which to generate a key */
87119   int iCur,          /* Cursor number for the pIdx->pTable table */
87120   int regOut,        /* Write the new index key to this register */
87121   int doMakeRec      /* Run the OP_MakeRecord instruction if true */
87122 ){
87123   Vdbe *v = pParse->pVdbe;
87124   int j;
87125   Table *pTab = pIdx->pTable;
87126   int regBase;
87127   int nCol;
87128
87129   nCol = pIdx->nColumn;
87130   regBase = sqlite3GetTempRange(pParse, nCol+1);
87131   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
87132   for(j=0; j<nCol; j++){
87133     int idx = pIdx->aiColumn[j];
87134     if( idx==pTab->iPKey ){
87135       sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
87136     }else{
87137       sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
87138       sqlite3ColumnDefault(v, pTab, idx, -1);
87139     }
87140   }
87141   if( doMakeRec ){
87142     const char *zAff;
87143     if( pTab->pSelect
87144      || OptimizationDisabled(pParse->db, SQLITE_IdxRealAsInt)
87145     ){
87146       zAff = 0;
87147     }else{
87148       zAff = sqlite3IndexAffinityStr(v, pIdx);
87149     }
87150     sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
87151     sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT);
87152   }
87153   sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
87154   return regBase;
87155 }
87156
87157 /************** End of delete.c **********************************************/
87158 /************** Begin file func.c ********************************************/
87159 /*
87160 ** 2002 February 23
87161 **
87162 ** The author disclaims copyright to this source code.  In place of
87163 ** a legal notice, here is a blessing:
87164 **
87165 **    May you do good and not evil.
87166 **    May you find forgiveness for yourself and forgive others.
87167 **    May you share freely, never taking more than you give.
87168 **
87169 *************************************************************************
87170 ** This file contains the C functions that implement various SQL
87171 ** functions of SQLite.  
87172 **
87173 ** There is only one exported symbol in this file - the function
87174 ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
87175 ** All other code has file scope.
87176 */
87177 /* #include <stdlib.h> */
87178 /* #include <assert.h> */
87179
87180 /*
87181 ** Return the collating function associated with a function.
87182 */
87183 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
87184   return context->pColl;
87185 }
87186
87187 /*
87188 ** Indicate that the accumulator load should be skipped on this
87189 ** iteration of the aggregate loop.
87190 */
87191 static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
87192   context->skipFlag = 1;
87193 }
87194
87195 /*
87196 ** Implementation of the non-aggregate min() and max() functions
87197 */
87198 static void minmaxFunc(
87199   sqlite3_context *context,
87200   int argc,
87201   sqlite3_value **argv
87202 ){
87203   int i;
87204   int mask;    /* 0 for min() or 0xffffffff for max() */
87205   int iBest;
87206   CollSeq *pColl;
87207
87208   assert( argc>1 );
87209   mask = sqlite3_user_data(context)==0 ? 0 : -1;
87210   pColl = sqlite3GetFuncCollSeq(context);
87211   assert( pColl );
87212   assert( mask==-1 || mask==0 );
87213   iBest = 0;
87214   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
87215   for(i=1; i<argc; i++){
87216     if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
87217     if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
87218       testcase( mask==0 );
87219       iBest = i;
87220     }
87221   }
87222   sqlite3_result_value(context, argv[iBest]);
87223 }
87224
87225 /*
87226 ** Return the type of the argument.
87227 */
87228 static void typeofFunc(
87229   sqlite3_context *context,
87230   int NotUsed,
87231   sqlite3_value **argv
87232 ){
87233   const char *z = 0;
87234   UNUSED_PARAMETER(NotUsed);
87235   switch( sqlite3_value_type(argv[0]) ){
87236     case SQLITE_INTEGER: z = "integer"; break;
87237     case SQLITE_TEXT:    z = "text";    break;
87238     case SQLITE_FLOAT:   z = "real";    break;
87239     case SQLITE_BLOB:    z = "blob";    break;
87240     default:             z = "null";    break;
87241   }
87242   sqlite3_result_text(context, z, -1, SQLITE_STATIC);
87243 }
87244
87245
87246 /*
87247 ** Implementation of the length() function
87248 */
87249 static void lengthFunc(
87250   sqlite3_context *context,
87251   int argc,
87252   sqlite3_value **argv
87253 ){
87254   int len;
87255
87256   assert( argc==1 );
87257   UNUSED_PARAMETER(argc);
87258   switch( sqlite3_value_type(argv[0]) ){
87259     case SQLITE_BLOB:
87260     case SQLITE_INTEGER:
87261     case SQLITE_FLOAT: {
87262       sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
87263       break;
87264     }
87265     case SQLITE_TEXT: {
87266       const unsigned char *z = sqlite3_value_text(argv[0]);
87267       if( z==0 ) return;
87268       len = 0;
87269       while( *z ){
87270         len++;
87271         SQLITE_SKIP_UTF8(z);
87272       }
87273       sqlite3_result_int(context, len);
87274       break;
87275     }
87276     default: {
87277       sqlite3_result_null(context);
87278       break;
87279     }
87280   }
87281 }
87282
87283 /*
87284 ** Implementation of the abs() function.
87285 **
87286 ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
87287 ** the numeric argument X. 
87288 */
87289 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
87290   assert( argc==1 );
87291   UNUSED_PARAMETER(argc);
87292   switch( sqlite3_value_type(argv[0]) ){
87293     case SQLITE_INTEGER: {
87294       i64 iVal = sqlite3_value_int64(argv[0]);
87295       if( iVal<0 ){
87296         if( (iVal<<1)==0 ){
87297           /* IMP: R-35460-15084 If X is the integer -9223372036854775807 then
87298           ** abs(X) throws an integer overflow error since there is no
87299           ** equivalent positive 64-bit two complement value. */
87300           sqlite3_result_error(context, "integer overflow", -1);
87301           return;
87302         }
87303         iVal = -iVal;
87304       } 
87305       sqlite3_result_int64(context, iVal);
87306       break;
87307     }
87308     case SQLITE_NULL: {
87309       /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
87310       sqlite3_result_null(context);
87311       break;
87312     }
87313     default: {
87314       /* Because sqlite3_value_double() returns 0.0 if the argument is not
87315       ** something that can be converted into a number, we have:
87316       ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
87317       ** cannot be converted to a numeric value. 
87318       */
87319       double rVal = sqlite3_value_double(argv[0]);
87320       if( rVal<0 ) rVal = -rVal;
87321       sqlite3_result_double(context, rVal);
87322       break;
87323     }
87324   }
87325 }
87326
87327 /*
87328 ** Implementation of the instr() function.
87329 **
87330 ** instr(haystack,needle) finds the first occurrence of needle
87331 ** in haystack and returns the number of previous characters plus 1,
87332 ** or 0 if needle does not occur within haystack.
87333 **
87334 ** If both haystack and needle are BLOBs, then the result is one more than
87335 ** the number of bytes in haystack prior to the first occurrence of needle,
87336 ** or 0 if needle never occurs in haystack.
87337 */
87338 static void instrFunc(
87339   sqlite3_context *context,
87340   int argc,
87341   sqlite3_value **argv
87342 ){
87343   const unsigned char *zHaystack;
87344   const unsigned char *zNeedle;
87345   int nHaystack;
87346   int nNeedle;
87347   int typeHaystack, typeNeedle;
87348   int N = 1;
87349   int isText;
87350
87351   UNUSED_PARAMETER(argc);
87352   typeHaystack = sqlite3_value_type(argv[0]);
87353   typeNeedle = sqlite3_value_type(argv[1]);
87354   if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
87355   nHaystack = sqlite3_value_bytes(argv[0]);
87356   nNeedle = sqlite3_value_bytes(argv[1]);
87357   if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
87358     zHaystack = sqlite3_value_blob(argv[0]);
87359     zNeedle = sqlite3_value_blob(argv[1]);
87360     isText = 0;
87361   }else{
87362     zHaystack = sqlite3_value_text(argv[0]);
87363     zNeedle = sqlite3_value_text(argv[1]);
87364     isText = 1;
87365   }
87366   while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
87367     N++;
87368     do{
87369       nHaystack--;
87370       zHaystack++;
87371     }while( isText && (zHaystack[0]&0xc0)==0x80 );
87372   }
87373   if( nNeedle>nHaystack ) N = 0;
87374   sqlite3_result_int(context, N);
87375 }
87376
87377 /*
87378 ** Implementation of the substr() function.
87379 **
87380 ** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
87381 ** p1 is 1-indexed.  So substr(x,1,1) returns the first character
87382 ** of x.  If x is text, then we actually count UTF-8 characters.
87383 ** If x is a blob, then we count bytes.
87384 **
87385 ** If p1 is negative, then we begin abs(p1) from the end of x[].
87386 **
87387 ** If p2 is negative, return the p2 characters preceeding p1.
87388 */
87389 static void substrFunc(
87390   sqlite3_context *context,
87391   int argc,
87392   sqlite3_value **argv
87393 ){
87394   const unsigned char *z;
87395   const unsigned char *z2;
87396   int len;
87397   int p0type;
87398   i64 p1, p2;
87399   int negP2 = 0;
87400
87401   assert( argc==3 || argc==2 );
87402   if( sqlite3_value_type(argv[1])==SQLITE_NULL
87403    || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
87404   ){
87405     return;
87406   }
87407   p0type = sqlite3_value_type(argv[0]);
87408   p1 = sqlite3_value_int(argv[1]);
87409   if( p0type==SQLITE_BLOB ){
87410     len = sqlite3_value_bytes(argv[0]);
87411     z = sqlite3_value_blob(argv[0]);
87412     if( z==0 ) return;
87413     assert( len==sqlite3_value_bytes(argv[0]) );
87414   }else{
87415     z = sqlite3_value_text(argv[0]);
87416     if( z==0 ) return;
87417     len = 0;
87418     if( p1<0 ){
87419       for(z2=z; *z2; len++){
87420         SQLITE_SKIP_UTF8(z2);
87421       }
87422     }
87423   }
87424   if( argc==3 ){
87425     p2 = sqlite3_value_int(argv[2]);
87426     if( p2<0 ){
87427       p2 = -p2;
87428       negP2 = 1;
87429     }
87430   }else{
87431     p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
87432   }
87433   if( p1<0 ){
87434     p1 += len;
87435     if( p1<0 ){
87436       p2 += p1;
87437       if( p2<0 ) p2 = 0;
87438       p1 = 0;
87439     }
87440   }else if( p1>0 ){
87441     p1--;
87442   }else if( p2>0 ){
87443     p2--;
87444   }
87445   if( negP2 ){
87446     p1 -= p2;
87447     if( p1<0 ){
87448       p2 += p1;
87449       p1 = 0;
87450     }
87451   }
87452   assert( p1>=0 && p2>=0 );
87453   if( p0type!=SQLITE_BLOB ){
87454     while( *z && p1 ){
87455       SQLITE_SKIP_UTF8(z);
87456       p1--;
87457     }
87458     for(z2=z; *z2 && p2; p2--){
87459       SQLITE_SKIP_UTF8(z2);
87460     }
87461     sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
87462   }else{
87463     if( p1+p2>len ){
87464       p2 = len-p1;
87465       if( p2<0 ) p2 = 0;
87466     }
87467     sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
87468   }
87469 }
87470
87471 /*
87472 ** Implementation of the round() function
87473 */
87474 #ifndef SQLITE_OMIT_FLOATING_POINT
87475 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
87476   int n = 0;
87477   double r;
87478   char *zBuf;
87479   assert( argc==1 || argc==2 );
87480   if( argc==2 ){
87481     if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
87482     n = sqlite3_value_int(argv[1]);
87483     if( n>30 ) n = 30;
87484     if( n<0 ) n = 0;
87485   }
87486   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
87487   r = sqlite3_value_double(argv[0]);
87488   /* If Y==0 and X will fit in a 64-bit int,
87489   ** handle the rounding directly,
87490   ** otherwise use printf.
87491   */
87492   if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
87493     r = (double)((sqlite_int64)(r+0.5));
87494   }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
87495     r = -(double)((sqlite_int64)((-r)+0.5));
87496   }else{
87497     zBuf = sqlite3_mprintf("%.*f",n,r);
87498     if( zBuf==0 ){
87499       sqlite3_result_error_nomem(context);
87500       return;
87501     }
87502     sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
87503     sqlite3_free(zBuf);
87504   }
87505   sqlite3_result_double(context, r);
87506 }
87507 #endif
87508
87509 /*
87510 ** Allocate nByte bytes of space using sqlite3_malloc(). If the
87511 ** allocation fails, call sqlite3_result_error_nomem() to notify
87512 ** the database handle that malloc() has failed and return NULL.
87513 ** If nByte is larger than the maximum string or blob length, then
87514 ** raise an SQLITE_TOOBIG exception and return NULL.
87515 */
87516 static void *contextMalloc(sqlite3_context *context, i64 nByte){
87517   char *z;
87518   sqlite3 *db = sqlite3_context_db_handle(context);
87519   assert( nByte>0 );
87520   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
87521   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
87522   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
87523     sqlite3_result_error_toobig(context);
87524     z = 0;
87525   }else{
87526     z = sqlite3Malloc((int)nByte);
87527     if( !z ){
87528       sqlite3_result_error_nomem(context);
87529     }
87530   }
87531   return z;
87532 }
87533
87534 /*
87535 ** Implementation of the upper() and lower() SQL functions.
87536 */
87537 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
87538   char *z1;
87539   const char *z2;
87540   int i, n;
87541   UNUSED_PARAMETER(argc);
87542   z2 = (char*)sqlite3_value_text(argv[0]);
87543   n = sqlite3_value_bytes(argv[0]);
87544   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
87545   assert( z2==(char*)sqlite3_value_text(argv[0]) );
87546   if( z2 ){
87547     z1 = contextMalloc(context, ((i64)n)+1);
87548     if( z1 ){
87549       for(i=0; i<n; i++){
87550         z1[i] = (char)sqlite3Toupper(z2[i]);
87551       }
87552       sqlite3_result_text(context, z1, n, sqlite3_free);
87553     }
87554   }
87555 }
87556 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
87557   char *z1;
87558   const char *z2;
87559   int i, n;
87560   UNUSED_PARAMETER(argc);
87561   z2 = (char*)sqlite3_value_text(argv[0]);
87562   n = sqlite3_value_bytes(argv[0]);
87563   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
87564   assert( z2==(char*)sqlite3_value_text(argv[0]) );
87565   if( z2 ){
87566     z1 = contextMalloc(context, ((i64)n)+1);
87567     if( z1 ){
87568       for(i=0; i<n; i++){
87569         z1[i] = sqlite3Tolower(z2[i]);
87570       }
87571       sqlite3_result_text(context, z1, n, sqlite3_free);
87572     }
87573   }
87574 }
87575
87576 /*
87577 ** The COALESCE() and IFNULL() functions are implemented as VDBE code so
87578 ** that unused argument values do not have to be computed.  However, we
87579 ** still need some kind of function implementation for this routines in
87580 ** the function table.  That function implementation will never be called
87581 ** so it doesn't matter what the implementation is.  We might as well use
87582 ** the "version()" function as a substitute.
87583 */
87584 #define ifnullFunc versionFunc   /* Substitute function - never called */
87585
87586 /*
87587 ** Implementation of random().  Return a random integer.  
87588 */
87589 static void randomFunc(
87590   sqlite3_context *context,
87591   int NotUsed,
87592   sqlite3_value **NotUsed2
87593 ){
87594   sqlite_int64 r;
87595   UNUSED_PARAMETER2(NotUsed, NotUsed2);
87596   sqlite3_randomness(sizeof(r), &r);
87597   if( r<0 ){
87598     /* We need to prevent a random number of 0x8000000000000000 
87599     ** (or -9223372036854775808) since when you do abs() of that
87600     ** number of you get the same value back again.  To do this
87601     ** in a way that is testable, mask the sign bit off of negative
87602     ** values, resulting in a positive value.  Then take the 
87603     ** 2s complement of that positive value.  The end result can
87604     ** therefore be no less than -9223372036854775807.
87605     */
87606     r = -(r & LARGEST_INT64);
87607   }
87608   sqlite3_result_int64(context, r);
87609 }
87610
87611 /*
87612 ** Implementation of randomblob(N).  Return a random blob
87613 ** that is N bytes long.
87614 */
87615 static void randomBlob(
87616   sqlite3_context *context,
87617   int argc,
87618   sqlite3_value **argv
87619 ){
87620   int n;
87621   unsigned char *p;
87622   assert( argc==1 );
87623   UNUSED_PARAMETER(argc);
87624   n = sqlite3_value_int(argv[0]);
87625   if( n<1 ){
87626     n = 1;
87627   }
87628   p = contextMalloc(context, n);
87629   if( p ){
87630     sqlite3_randomness(n, p);
87631     sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
87632   }
87633 }
87634
87635 /*
87636 ** Implementation of the last_insert_rowid() SQL function.  The return
87637 ** value is the same as the sqlite3_last_insert_rowid() API function.
87638 */
87639 static void last_insert_rowid(
87640   sqlite3_context *context, 
87641   int NotUsed, 
87642   sqlite3_value **NotUsed2
87643 ){
87644   sqlite3 *db = sqlite3_context_db_handle(context);
87645   UNUSED_PARAMETER2(NotUsed, NotUsed2);
87646   /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
87647   ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
87648   ** function. */
87649   sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
87650 }
87651
87652 /*
87653 ** Implementation of the changes() SQL function.
87654 **
87655 ** IMP: R-62073-11209 The changes() SQL function is a wrapper
87656 ** around the sqlite3_changes() C/C++ function and hence follows the same
87657 ** rules for counting changes.
87658 */
87659 static void changes(
87660   sqlite3_context *context,
87661   int NotUsed,
87662   sqlite3_value **NotUsed2
87663 ){
87664   sqlite3 *db = sqlite3_context_db_handle(context);
87665   UNUSED_PARAMETER2(NotUsed, NotUsed2);
87666   sqlite3_result_int(context, sqlite3_changes(db));
87667 }
87668
87669 /*
87670 ** Implementation of the total_changes() SQL function.  The return value is
87671 ** the same as the sqlite3_total_changes() API function.
87672 */
87673 static void total_changes(
87674   sqlite3_context *context,
87675   int NotUsed,
87676   sqlite3_value **NotUsed2
87677 ){
87678   sqlite3 *db = sqlite3_context_db_handle(context);
87679   UNUSED_PARAMETER2(NotUsed, NotUsed2);
87680   /* IMP: R-52756-41993 This function is a wrapper around the
87681   ** sqlite3_total_changes() C/C++ interface. */
87682   sqlite3_result_int(context, sqlite3_total_changes(db));
87683 }
87684
87685 /*
87686 ** A structure defining how to do GLOB-style comparisons.
87687 */
87688 struct compareInfo {
87689   u8 matchAll;
87690   u8 matchOne;
87691   u8 matchSet;
87692   u8 noCase;
87693 };
87694
87695 /*
87696 ** For LIKE and GLOB matching on EBCDIC machines, assume that every
87697 ** character is exactly one byte in size.  Also, all characters are
87698 ** able to participate in upper-case-to-lower-case mappings in EBCDIC
87699 ** whereas only characters less than 0x80 do in ASCII.
87700 */
87701 #if defined(SQLITE_EBCDIC)
87702 # define sqlite3Utf8Read(A)    (*((*A)++))
87703 # define GlogUpperToLower(A)   A = sqlite3UpperToLower[A]
87704 #else
87705 # define GlogUpperToLower(A)   if( !((A)&~0x7f) ){ A = sqlite3UpperToLower[A]; }
87706 #endif
87707
87708 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
87709 /* The correct SQL-92 behavior is for the LIKE operator to ignore
87710 ** case.  Thus  'a' LIKE 'A' would be true. */
87711 static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
87712 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
87713 ** is case sensitive causing 'a' LIKE 'A' to be false */
87714 static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
87715
87716 /*
87717 ** Compare two UTF-8 strings for equality where the first string can
87718 ** potentially be a "glob" expression.  Return true (1) if they
87719 ** are the same and false (0) if they are different.
87720 **
87721 ** Globbing rules:
87722 **
87723 **      '*'       Matches any sequence of zero or more characters.
87724 **
87725 **      '?'       Matches exactly one character.
87726 **
87727 **     [...]      Matches one character from the enclosed list of
87728 **                characters.
87729 **
87730 **     [^...]     Matches one character not in the enclosed list.
87731 **
87732 ** With the [...] and [^...] matching, a ']' character can be included
87733 ** in the list by making it the first character after '[' or '^'.  A
87734 ** range of characters can be specified using '-'.  Example:
87735 ** "[a-z]" matches any single lower-case letter.  To match a '-', make
87736 ** it the last character in the list.
87737 **
87738 ** This routine is usually quick, but can be N**2 in the worst case.
87739 **
87740 ** Hints: to match '*' or '?', put them in "[]".  Like this:
87741 **
87742 **         abc[*]xyz        Matches "abc*xyz" only
87743 */
87744 static int patternCompare(
87745   const u8 *zPattern,              /* The glob pattern */
87746   const u8 *zString,               /* The string to compare against the glob */
87747   const struct compareInfo *pInfo, /* Information about how to do the compare */
87748   u32 esc                          /* The escape character */
87749 ){
87750   u32 c, c2;
87751   int invert;
87752   int seen;
87753   u8 matchOne = pInfo->matchOne;
87754   u8 matchAll = pInfo->matchAll;
87755   u8 matchSet = pInfo->matchSet;
87756   u8 noCase = pInfo->noCase; 
87757   int prevEscape = 0;     /* True if the previous character was 'escape' */
87758
87759   while( (c = sqlite3Utf8Read(&zPattern))!=0 ){
87760     if( c==matchAll && !prevEscape ){
87761       while( (c=sqlite3Utf8Read(&zPattern)) == matchAll
87762                || c == matchOne ){
87763         if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
87764           return 0;
87765         }
87766       }
87767       if( c==0 ){
87768         return 1;
87769       }else if( c==esc ){
87770         c = sqlite3Utf8Read(&zPattern);
87771         if( c==0 ){
87772           return 0;
87773         }
87774       }else if( c==matchSet ){
87775         assert( esc==0 );         /* This is GLOB, not LIKE */
87776         assert( matchSet<0x80 );  /* '[' is a single-byte character */
87777         while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
87778           SQLITE_SKIP_UTF8(zString);
87779         }
87780         return *zString!=0;
87781       }
87782       while( (c2 = sqlite3Utf8Read(&zString))!=0 ){
87783         if( noCase ){
87784           GlogUpperToLower(c2);
87785           GlogUpperToLower(c);
87786           while( c2 != 0 && c2 != c ){
87787             c2 = sqlite3Utf8Read(&zString);
87788             GlogUpperToLower(c2);
87789           }
87790         }else{
87791           while( c2 != 0 && c2 != c ){
87792             c2 = sqlite3Utf8Read(&zString);
87793           }
87794         }
87795         if( c2==0 ) return 0;
87796         if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
87797       }
87798       return 0;
87799     }else if( c==matchOne && !prevEscape ){
87800       if( sqlite3Utf8Read(&zString)==0 ){
87801         return 0;
87802       }
87803     }else if( c==matchSet ){
87804       u32 prior_c = 0;
87805       assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
87806       seen = 0;
87807       invert = 0;
87808       c = sqlite3Utf8Read(&zString);
87809       if( c==0 ) return 0;
87810       c2 = sqlite3Utf8Read(&zPattern);
87811       if( c2=='^' ){
87812         invert = 1;
87813         c2 = sqlite3Utf8Read(&zPattern);
87814       }
87815       if( c2==']' ){
87816         if( c==']' ) seen = 1;
87817         c2 = sqlite3Utf8Read(&zPattern);
87818       }
87819       while( c2 && c2!=']' ){
87820         if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
87821           c2 = sqlite3Utf8Read(&zPattern);
87822           if( c>=prior_c && c<=c2 ) seen = 1;
87823           prior_c = 0;
87824         }else{
87825           if( c==c2 ){
87826             seen = 1;
87827           }
87828           prior_c = c2;
87829         }
87830         c2 = sqlite3Utf8Read(&zPattern);
87831       }
87832       if( c2==0 || (seen ^ invert)==0 ){
87833         return 0;
87834       }
87835     }else if( esc==c && !prevEscape ){
87836       prevEscape = 1;
87837     }else{
87838       c2 = sqlite3Utf8Read(&zString);
87839       if( noCase ){
87840         GlogUpperToLower(c);
87841         GlogUpperToLower(c2);
87842       }
87843       if( c!=c2 ){
87844         return 0;
87845       }
87846       prevEscape = 0;
87847     }
87848   }
87849   return *zString==0;
87850 }
87851
87852 /*
87853 ** The sqlite3_strglob() interface.
87854 */
87855 SQLITE_API int sqlite3_strglob(const char *zGlobPattern, const char *zString){
87856   return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, 0)==0;
87857 }
87858
87859 /*
87860 ** Count the number of times that the LIKE operator (or GLOB which is
87861 ** just a variation of LIKE) gets called.  This is used for testing
87862 ** only.
87863 */
87864 #ifdef SQLITE_TEST
87865 SQLITE_API int sqlite3_like_count = 0;
87866 #endif
87867
87868
87869 /*
87870 ** Implementation of the like() SQL function.  This function implements
87871 ** the build-in LIKE operator.  The first argument to the function is the
87872 ** pattern and the second argument is the string.  So, the SQL statements:
87873 **
87874 **       A LIKE B
87875 **
87876 ** is implemented as like(B,A).
87877 **
87878 ** This same function (with a different compareInfo structure) computes
87879 ** the GLOB operator.
87880 */
87881 static void likeFunc(
87882   sqlite3_context *context, 
87883   int argc, 
87884   sqlite3_value **argv
87885 ){
87886   const unsigned char *zA, *zB;
87887   u32 escape = 0;
87888   int nPat;
87889   sqlite3 *db = sqlite3_context_db_handle(context);
87890
87891   zB = sqlite3_value_text(argv[0]);
87892   zA = sqlite3_value_text(argv[1]);
87893
87894   /* Limit the length of the LIKE or GLOB pattern to avoid problems
87895   ** of deep recursion and N*N behavior in patternCompare().
87896   */
87897   nPat = sqlite3_value_bytes(argv[0]);
87898   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
87899   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
87900   if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
87901     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
87902     return;
87903   }
87904   assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
87905
87906   if( argc==3 ){
87907     /* The escape character string must consist of a single UTF-8 character.
87908     ** Otherwise, return an error.
87909     */
87910     const unsigned char *zEsc = sqlite3_value_text(argv[2]);
87911     if( zEsc==0 ) return;
87912     if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
87913       sqlite3_result_error(context, 
87914           "ESCAPE expression must be a single character", -1);
87915       return;
87916     }
87917     escape = sqlite3Utf8Read(&zEsc);
87918   }
87919   if( zA && zB ){
87920     struct compareInfo *pInfo = sqlite3_user_data(context);
87921 #ifdef SQLITE_TEST
87922     sqlite3_like_count++;
87923 #endif
87924     
87925     sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
87926   }
87927 }
87928
87929 /*
87930 ** Implementation of the NULLIF(x,y) function.  The result is the first
87931 ** argument if the arguments are different.  The result is NULL if the
87932 ** arguments are equal to each other.
87933 */
87934 static void nullifFunc(
87935   sqlite3_context *context,
87936   int NotUsed,
87937   sqlite3_value **argv
87938 ){
87939   CollSeq *pColl = sqlite3GetFuncCollSeq(context);
87940   UNUSED_PARAMETER(NotUsed);
87941   if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
87942     sqlite3_result_value(context, argv[0]);
87943   }
87944 }
87945
87946 /*
87947 ** Implementation of the sqlite_version() function.  The result is the version
87948 ** of the SQLite library that is running.
87949 */
87950 static void versionFunc(
87951   sqlite3_context *context,
87952   int NotUsed,
87953   sqlite3_value **NotUsed2
87954 ){
87955   UNUSED_PARAMETER2(NotUsed, NotUsed2);
87956   /* IMP: R-48699-48617 This function is an SQL wrapper around the
87957   ** sqlite3_libversion() C-interface. */
87958   sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
87959 }
87960
87961 /*
87962 ** Implementation of the sqlite_source_id() function. The result is a string
87963 ** that identifies the particular version of the source code used to build
87964 ** SQLite.
87965 */
87966 static void sourceidFunc(
87967   sqlite3_context *context,
87968   int NotUsed,
87969   sqlite3_value **NotUsed2
87970 ){
87971   UNUSED_PARAMETER2(NotUsed, NotUsed2);
87972   /* IMP: R-24470-31136 This function is an SQL wrapper around the
87973   ** sqlite3_sourceid() C interface. */
87974   sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
87975 }
87976
87977 /*
87978 ** Implementation of the sqlite_log() function.  This is a wrapper around
87979 ** sqlite3_log().  The return value is NULL.  The function exists purely for
87980 ** its side-effects.
87981 */
87982 static void errlogFunc(
87983   sqlite3_context *context,
87984   int argc,
87985   sqlite3_value **argv
87986 ){
87987   UNUSED_PARAMETER(argc);
87988   UNUSED_PARAMETER(context);
87989   sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
87990 }
87991
87992 /*
87993 ** Implementation of the sqlite_compileoption_used() function.
87994 ** The result is an integer that identifies if the compiler option
87995 ** was used to build SQLite.
87996 */
87997 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
87998 static void compileoptionusedFunc(
87999   sqlite3_context *context,
88000   int argc,
88001   sqlite3_value **argv
88002 ){
88003   const char *zOptName;
88004   assert( argc==1 );
88005   UNUSED_PARAMETER(argc);
88006   /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
88007   ** function is a wrapper around the sqlite3_compileoption_used() C/C++
88008   ** function.
88009   */
88010   if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
88011     sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
88012   }
88013 }
88014 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
88015
88016 /*
88017 ** Implementation of the sqlite_compileoption_get() function. 
88018 ** The result is a string that identifies the compiler options 
88019 ** used to build SQLite.
88020 */
88021 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
88022 static void compileoptiongetFunc(
88023   sqlite3_context *context,
88024   int argc,
88025   sqlite3_value **argv
88026 ){
88027   int n;
88028   assert( argc==1 );
88029   UNUSED_PARAMETER(argc);
88030   /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
88031   ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
88032   */
88033   n = sqlite3_value_int(argv[0]);
88034   sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
88035 }
88036 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
88037
88038 /* Array for converting from half-bytes (nybbles) into ASCII hex
88039 ** digits. */
88040 static const char hexdigits[] = {
88041   '0', '1', '2', '3', '4', '5', '6', '7',
88042   '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' 
88043 };
88044
88045 /*
88046 ** EXPERIMENTAL - This is not an official function.  The interface may
88047 ** change.  This function may disappear.  Do not write code that depends
88048 ** on this function.
88049 **
88050 ** Implementation of the QUOTE() function.  This function takes a single
88051 ** argument.  If the argument is numeric, the return value is the same as
88052 ** the argument.  If the argument is NULL, the return value is the string
88053 ** "NULL".  Otherwise, the argument is enclosed in single quotes with
88054 ** single-quote escapes.
88055 */
88056 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
88057   assert( argc==1 );
88058   UNUSED_PARAMETER(argc);
88059   switch( sqlite3_value_type(argv[0]) ){
88060     case SQLITE_FLOAT: {
88061       double r1, r2;
88062       char zBuf[50];
88063       r1 = sqlite3_value_double(argv[0]);
88064       sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
88065       sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
88066       if( r1!=r2 ){
88067         sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
88068       }
88069       sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
88070       break;
88071     }
88072     case SQLITE_INTEGER: {
88073       sqlite3_result_value(context, argv[0]);
88074       break;
88075     }
88076     case SQLITE_BLOB: {
88077       char *zText = 0;
88078       char const *zBlob = sqlite3_value_blob(argv[0]);
88079       int nBlob = sqlite3_value_bytes(argv[0]);
88080       assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
88081       zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4); 
88082       if( zText ){
88083         int i;
88084         for(i=0; i<nBlob; i++){
88085           zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
88086           zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
88087         }
88088         zText[(nBlob*2)+2] = '\'';
88089         zText[(nBlob*2)+3] = '\0';
88090         zText[0] = 'X';
88091         zText[1] = '\'';
88092         sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
88093         sqlite3_free(zText);
88094       }
88095       break;
88096     }
88097     case SQLITE_TEXT: {
88098       int i,j;
88099       u64 n;
88100       const unsigned char *zArg = sqlite3_value_text(argv[0]);
88101       char *z;
88102
88103       if( zArg==0 ) return;
88104       for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
88105       z = contextMalloc(context, ((i64)i)+((i64)n)+3);
88106       if( z ){
88107         z[0] = '\'';
88108         for(i=0, j=1; zArg[i]; i++){
88109           z[j++] = zArg[i];
88110           if( zArg[i]=='\'' ){
88111             z[j++] = '\'';
88112           }
88113         }
88114         z[j++] = '\'';
88115         z[j] = 0;
88116         sqlite3_result_text(context, z, j, sqlite3_free);
88117       }
88118       break;
88119     }
88120     default: {
88121       assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
88122       sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
88123       break;
88124     }
88125   }
88126 }
88127
88128 /*
88129 ** The unicode() function.  Return the integer unicode code-point value
88130 ** for the first character of the input string. 
88131 */
88132 static void unicodeFunc(
88133   sqlite3_context *context,
88134   int argc,
88135   sqlite3_value **argv
88136 ){
88137   const unsigned char *z = sqlite3_value_text(argv[0]);
88138   (void)argc;
88139   if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
88140 }
88141
88142 /*
88143 ** The char() function takes zero or more arguments, each of which is
88144 ** an integer.  It constructs a string where each character of the string
88145 ** is the unicode character for the corresponding integer argument.
88146 */
88147 static void charFunc(
88148   sqlite3_context *context,
88149   int argc,
88150   sqlite3_value **argv
88151 ){
88152   unsigned char *z, *zOut;
88153   int i;
88154   zOut = z = sqlite3_malloc( argc*4 );
88155   if( z==0 ){
88156     sqlite3_result_error_nomem(context);
88157     return;
88158   }
88159   for(i=0; i<argc; i++){
88160     sqlite3_int64 x;
88161     unsigned c;
88162     x = sqlite3_value_int64(argv[i]);
88163     if( x<0 || x>0x10ffff ) x = 0xfffd;
88164     c = (unsigned)(x & 0x1fffff);
88165     if( c<0x00080 ){
88166       *zOut++ = (u8)(c&0xFF);
88167     }else if( c<0x00800 ){
88168       *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
88169       *zOut++ = 0x80 + (u8)(c & 0x3F);
88170     }else if( c<0x10000 ){
88171       *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
88172       *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
88173       *zOut++ = 0x80 + (u8)(c & 0x3F);
88174     }else{
88175       *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
88176       *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
88177       *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
88178       *zOut++ = 0x80 + (u8)(c & 0x3F);
88179     }                                                    \
88180   }
88181   sqlite3_result_text(context, (char*)z, (int)(zOut-z), sqlite3_free);
88182 }
88183
88184 /*
88185 ** The hex() function.  Interpret the argument as a blob.  Return
88186 ** a hexadecimal rendering as text.
88187 */
88188 static void hexFunc(
88189   sqlite3_context *context,
88190   int argc,
88191   sqlite3_value **argv
88192 ){
88193   int i, n;
88194   const unsigned char *pBlob;
88195   char *zHex, *z;
88196   assert( argc==1 );
88197   UNUSED_PARAMETER(argc);
88198   pBlob = sqlite3_value_blob(argv[0]);
88199   n = sqlite3_value_bytes(argv[0]);
88200   assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
88201   z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
88202   if( zHex ){
88203     for(i=0; i<n; i++, pBlob++){
88204       unsigned char c = *pBlob;
88205       *(z++) = hexdigits[(c>>4)&0xf];
88206       *(z++) = hexdigits[c&0xf];
88207     }
88208     *z = 0;
88209     sqlite3_result_text(context, zHex, n*2, sqlite3_free);
88210   }
88211 }
88212
88213 /*
88214 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
88215 */
88216 static void zeroblobFunc(
88217   sqlite3_context *context,
88218   int argc,
88219   sqlite3_value **argv
88220 ){
88221   i64 n;
88222   sqlite3 *db = sqlite3_context_db_handle(context);
88223   assert( argc==1 );
88224   UNUSED_PARAMETER(argc);
88225   n = sqlite3_value_int64(argv[0]);
88226   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
88227   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
88228   if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
88229     sqlite3_result_error_toobig(context);
88230   }else{
88231     sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
88232   }
88233 }
88234
88235 /*
88236 ** The replace() function.  Three arguments are all strings: call
88237 ** them A, B, and C. The result is also a string which is derived
88238 ** from A by replacing every occurance of B with C.  The match
88239 ** must be exact.  Collating sequences are not used.
88240 */
88241 static void replaceFunc(
88242   sqlite3_context *context,
88243   int argc,
88244   sqlite3_value **argv
88245 ){
88246   const unsigned char *zStr;        /* The input string A */
88247   const unsigned char *zPattern;    /* The pattern string B */
88248   const unsigned char *zRep;        /* The replacement string C */
88249   unsigned char *zOut;              /* The output */
88250   int nStr;                /* Size of zStr */
88251   int nPattern;            /* Size of zPattern */
88252   int nRep;                /* Size of zRep */
88253   i64 nOut;                /* Maximum size of zOut */
88254   int loopLimit;           /* Last zStr[] that might match zPattern[] */
88255   int i, j;                /* Loop counters */
88256
88257   assert( argc==3 );
88258   UNUSED_PARAMETER(argc);
88259   zStr = sqlite3_value_text(argv[0]);
88260   if( zStr==0 ) return;
88261   nStr = sqlite3_value_bytes(argv[0]);
88262   assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
88263   zPattern = sqlite3_value_text(argv[1]);
88264   if( zPattern==0 ){
88265     assert( sqlite3_value_type(argv[1])==SQLITE_NULL
88266             || sqlite3_context_db_handle(context)->mallocFailed );
88267     return;
88268   }
88269   if( zPattern[0]==0 ){
88270     assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
88271     sqlite3_result_value(context, argv[0]);
88272     return;
88273   }
88274   nPattern = sqlite3_value_bytes(argv[1]);
88275   assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
88276   zRep = sqlite3_value_text(argv[2]);
88277   if( zRep==0 ) return;
88278   nRep = sqlite3_value_bytes(argv[2]);
88279   assert( zRep==sqlite3_value_text(argv[2]) );
88280   nOut = nStr + 1;
88281   assert( nOut<SQLITE_MAX_LENGTH );
88282   zOut = contextMalloc(context, (i64)nOut);
88283   if( zOut==0 ){
88284     return;
88285   }
88286   loopLimit = nStr - nPattern;  
88287   for(i=j=0; i<=loopLimit; i++){
88288     if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
88289       zOut[j++] = zStr[i];
88290     }else{
88291       u8 *zOld;
88292       sqlite3 *db = sqlite3_context_db_handle(context);
88293       nOut += nRep - nPattern;
88294       testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
88295       testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
88296       if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
88297         sqlite3_result_error_toobig(context);
88298         sqlite3_free(zOut);
88299         return;
88300       }
88301       zOld = zOut;
88302       zOut = sqlite3_realloc(zOut, (int)nOut);
88303       if( zOut==0 ){
88304         sqlite3_result_error_nomem(context);
88305         sqlite3_free(zOld);
88306         return;
88307       }
88308       memcpy(&zOut[j], zRep, nRep);
88309       j += nRep;
88310       i += nPattern-1;
88311     }
88312   }
88313   assert( j+nStr-i+1==nOut );
88314   memcpy(&zOut[j], &zStr[i], nStr-i);
88315   j += nStr - i;
88316   assert( j<=nOut );
88317   zOut[j] = 0;
88318   sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
88319 }
88320
88321 /*
88322 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
88323 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
88324 */
88325 static void trimFunc(
88326   sqlite3_context *context,
88327   int argc,
88328   sqlite3_value **argv
88329 ){
88330   const unsigned char *zIn;         /* Input string */
88331   const unsigned char *zCharSet;    /* Set of characters to trim */
88332   int nIn;                          /* Number of bytes in input */
88333   int flags;                        /* 1: trimleft  2: trimright  3: trim */
88334   int i;                            /* Loop counter */
88335   unsigned char *aLen = 0;          /* Length of each character in zCharSet */
88336   unsigned char **azChar = 0;       /* Individual characters in zCharSet */
88337   int nChar;                        /* Number of characters in zCharSet */
88338
88339   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
88340     return;
88341   }
88342   zIn = sqlite3_value_text(argv[0]);
88343   if( zIn==0 ) return;
88344   nIn = sqlite3_value_bytes(argv[0]);
88345   assert( zIn==sqlite3_value_text(argv[0]) );
88346   if( argc==1 ){
88347     static const unsigned char lenOne[] = { 1 };
88348     static unsigned char * const azOne[] = { (u8*)" " };
88349     nChar = 1;
88350     aLen = (u8*)lenOne;
88351     azChar = (unsigned char **)azOne;
88352     zCharSet = 0;
88353   }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
88354     return;
88355   }else{
88356     const unsigned char *z;
88357     for(z=zCharSet, nChar=0; *z; nChar++){
88358       SQLITE_SKIP_UTF8(z);
88359     }
88360     if( nChar>0 ){
88361       azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
88362       if( azChar==0 ){
88363         return;
88364       }
88365       aLen = (unsigned char*)&azChar[nChar];
88366       for(z=zCharSet, nChar=0; *z; nChar++){
88367         azChar[nChar] = (unsigned char *)z;
88368         SQLITE_SKIP_UTF8(z);
88369         aLen[nChar] = (u8)(z - azChar[nChar]);
88370       }
88371     }
88372   }
88373   if( nChar>0 ){
88374     flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
88375     if( flags & 1 ){
88376       while( nIn>0 ){
88377         int len = 0;
88378         for(i=0; i<nChar; i++){
88379           len = aLen[i];
88380           if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
88381         }
88382         if( i>=nChar ) break;
88383         zIn += len;
88384         nIn -= len;
88385       }
88386     }
88387     if( flags & 2 ){
88388       while( nIn>0 ){
88389         int len = 0;
88390         for(i=0; i<nChar; i++){
88391           len = aLen[i];
88392           if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
88393         }
88394         if( i>=nChar ) break;
88395         nIn -= len;
88396       }
88397     }
88398     if( zCharSet ){
88399       sqlite3_free(azChar);
88400     }
88401   }
88402   sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
88403 }
88404
88405
88406 /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
88407 ** is only available if the SQLITE_SOUNDEX compile-time option is used
88408 ** when SQLite is built.
88409 */
88410 #ifdef SQLITE_SOUNDEX
88411 /*
88412 ** Compute the soundex encoding of a word.
88413 **
88414 ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
88415 ** soundex encoding of the string X. 
88416 */
88417 static void soundexFunc(
88418   sqlite3_context *context,
88419   int argc,
88420   sqlite3_value **argv
88421 ){
88422   char zResult[8];
88423   const u8 *zIn;
88424   int i, j;
88425   static const unsigned char iCode[] = {
88426     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
88427     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
88428     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
88429     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
88430     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
88431     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
88432     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
88433     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
88434   };
88435   assert( argc==1 );
88436   zIn = (u8*)sqlite3_value_text(argv[0]);
88437   if( zIn==0 ) zIn = (u8*)"";
88438   for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
88439   if( zIn[i] ){
88440     u8 prevcode = iCode[zIn[i]&0x7f];
88441     zResult[0] = sqlite3Toupper(zIn[i]);
88442     for(j=1; j<4 && zIn[i]; i++){
88443       int code = iCode[zIn[i]&0x7f];
88444       if( code>0 ){
88445         if( code!=prevcode ){
88446           prevcode = code;
88447           zResult[j++] = code + '0';
88448         }
88449       }else{
88450         prevcode = 0;
88451       }
88452     }
88453     while( j<4 ){
88454       zResult[j++] = '0';
88455     }
88456     zResult[j] = 0;
88457     sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
88458   }else{
88459     /* IMP: R-64894-50321 The string "?000" is returned if the argument
88460     ** is NULL or contains no ASCII alphabetic characters. */
88461     sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
88462   }
88463 }
88464 #endif /* SQLITE_SOUNDEX */
88465
88466 #ifndef SQLITE_OMIT_LOAD_EXTENSION
88467 /*
88468 ** A function that loads a shared-library extension then returns NULL.
88469 */
88470 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
88471   const char *zFile = (const char *)sqlite3_value_text(argv[0]);
88472   const char *zProc;
88473   sqlite3 *db = sqlite3_context_db_handle(context);
88474   char *zErrMsg = 0;
88475
88476   if( argc==2 ){
88477     zProc = (const char *)sqlite3_value_text(argv[1]);
88478   }else{
88479     zProc = 0;
88480   }
88481   if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
88482     sqlite3_result_error(context, zErrMsg, -1);
88483     sqlite3_free(zErrMsg);
88484   }
88485 }
88486 #endif
88487
88488
88489 /*
88490 ** An instance of the following structure holds the context of a
88491 ** sum() or avg() aggregate computation.
88492 */
88493 typedef struct SumCtx SumCtx;
88494 struct SumCtx {
88495   double rSum;      /* Floating point sum */
88496   i64 iSum;         /* Integer sum */   
88497   i64 cnt;          /* Number of elements summed */
88498   u8 overflow;      /* True if integer overflow seen */
88499   u8 approx;        /* True if non-integer value was input to the sum */
88500 };
88501
88502 /*
88503 ** Routines used to compute the sum, average, and total.
88504 **
88505 ** The SUM() function follows the (broken) SQL standard which means
88506 ** that it returns NULL if it sums over no inputs.  TOTAL returns
88507 ** 0.0 in that case.  In addition, TOTAL always returns a float where
88508 ** SUM might return an integer if it never encounters a floating point
88509 ** value.  TOTAL never fails, but SUM might through an exception if
88510 ** it overflows an integer.
88511 */
88512 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
88513   SumCtx *p;
88514   int type;
88515   assert( argc==1 );
88516   UNUSED_PARAMETER(argc);
88517   p = sqlite3_aggregate_context(context, sizeof(*p));
88518   type = sqlite3_value_numeric_type(argv[0]);
88519   if( p && type!=SQLITE_NULL ){
88520     p->cnt++;
88521     if( type==SQLITE_INTEGER ){
88522       i64 v = sqlite3_value_int64(argv[0]);
88523       p->rSum += v;
88524       if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
88525         p->overflow = 1;
88526       }
88527     }else{
88528       p->rSum += sqlite3_value_double(argv[0]);
88529       p->approx = 1;
88530     }
88531   }
88532 }
88533 static void sumFinalize(sqlite3_context *context){
88534   SumCtx *p;
88535   p = sqlite3_aggregate_context(context, 0);
88536   if( p && p->cnt>0 ){
88537     if( p->overflow ){
88538       sqlite3_result_error(context,"integer overflow",-1);
88539     }else if( p->approx ){
88540       sqlite3_result_double(context, p->rSum);
88541     }else{
88542       sqlite3_result_int64(context, p->iSum);
88543     }
88544   }
88545 }
88546 static void avgFinalize(sqlite3_context *context){
88547   SumCtx *p;
88548   p = sqlite3_aggregate_context(context, 0);
88549   if( p && p->cnt>0 ){
88550     sqlite3_result_double(context, p->rSum/(double)p->cnt);
88551   }
88552 }
88553 static void totalFinalize(sqlite3_context *context){
88554   SumCtx *p;
88555   p = sqlite3_aggregate_context(context, 0);
88556   /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
88557   sqlite3_result_double(context, p ? p->rSum : (double)0);
88558 }
88559
88560 /*
88561 ** The following structure keeps track of state information for the
88562 ** count() aggregate function.
88563 */
88564 typedef struct CountCtx CountCtx;
88565 struct CountCtx {
88566   i64 n;
88567 };
88568
88569 /*
88570 ** Routines to implement the count() aggregate function.
88571 */
88572 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
88573   CountCtx *p;
88574   p = sqlite3_aggregate_context(context, sizeof(*p));
88575   if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
88576     p->n++;
88577   }
88578
88579 #ifndef SQLITE_OMIT_DEPRECATED
88580   /* The sqlite3_aggregate_count() function is deprecated.  But just to make
88581   ** sure it still operates correctly, verify that its count agrees with our 
88582   ** internal count when using count(*) and when the total count can be
88583   ** expressed as a 32-bit integer. */
88584   assert( argc==1 || p==0 || p->n>0x7fffffff
88585           || p->n==sqlite3_aggregate_count(context) );
88586 #endif
88587 }   
88588 static void countFinalize(sqlite3_context *context){
88589   CountCtx *p;
88590   p = sqlite3_aggregate_context(context, 0);
88591   sqlite3_result_int64(context, p ? p->n : 0);
88592 }
88593
88594 /*
88595 ** Routines to implement min() and max() aggregate functions.
88596 */
88597 static void minmaxStep(
88598   sqlite3_context *context, 
88599   int NotUsed, 
88600   sqlite3_value **argv
88601 ){
88602   Mem *pArg  = (Mem *)argv[0];
88603   Mem *pBest;
88604   UNUSED_PARAMETER(NotUsed);
88605
88606   pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
88607   if( !pBest ) return;
88608
88609   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
88610     if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
88611   }else if( pBest->flags ){
88612     int max;
88613     int cmp;
88614     CollSeq *pColl = sqlite3GetFuncCollSeq(context);
88615     /* This step function is used for both the min() and max() aggregates,
88616     ** the only difference between the two being that the sense of the
88617     ** comparison is inverted. For the max() aggregate, the
88618     ** sqlite3_user_data() function returns (void *)-1. For min() it
88619     ** returns (void *)db, where db is the sqlite3* database pointer.
88620     ** Therefore the next statement sets variable 'max' to 1 for the max()
88621     ** aggregate, or 0 for min().
88622     */
88623     max = sqlite3_user_data(context)!=0;
88624     cmp = sqlite3MemCompare(pBest, pArg, pColl);
88625     if( (max && cmp<0) || (!max && cmp>0) ){
88626       sqlite3VdbeMemCopy(pBest, pArg);
88627     }else{
88628       sqlite3SkipAccumulatorLoad(context);
88629     }
88630   }else{
88631     sqlite3VdbeMemCopy(pBest, pArg);
88632   }
88633 }
88634 static void minMaxFinalize(sqlite3_context *context){
88635   sqlite3_value *pRes;
88636   pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
88637   if( pRes ){
88638     if( pRes->flags ){
88639       sqlite3_result_value(context, pRes);
88640     }
88641     sqlite3VdbeMemRelease(pRes);
88642   }
88643 }
88644
88645 /*
88646 ** group_concat(EXPR, ?SEPARATOR?)
88647 */
88648 static void groupConcatStep(
88649   sqlite3_context *context,
88650   int argc,
88651   sqlite3_value **argv
88652 ){
88653   const char *zVal;
88654   StrAccum *pAccum;
88655   const char *zSep;
88656   int nVal, nSep;
88657   assert( argc==1 || argc==2 );
88658   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
88659   pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
88660
88661   if( pAccum ){
88662     sqlite3 *db = sqlite3_context_db_handle(context);
88663     int firstTerm = pAccum->useMalloc==0;
88664     pAccum->useMalloc = 2;
88665     pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
88666     if( !firstTerm ){
88667       if( argc==2 ){
88668         zSep = (char*)sqlite3_value_text(argv[1]);
88669         nSep = sqlite3_value_bytes(argv[1]);
88670       }else{
88671         zSep = ",";
88672         nSep = 1;
88673       }
88674       sqlite3StrAccumAppend(pAccum, zSep, nSep);
88675     }
88676     zVal = (char*)sqlite3_value_text(argv[0]);
88677     nVal = sqlite3_value_bytes(argv[0]);
88678     sqlite3StrAccumAppend(pAccum, zVal, nVal);
88679   }
88680 }
88681 static void groupConcatFinalize(sqlite3_context *context){
88682   StrAccum *pAccum;
88683   pAccum = sqlite3_aggregate_context(context, 0);
88684   if( pAccum ){
88685     if( pAccum->tooBig ){
88686       sqlite3_result_error_toobig(context);
88687     }else if( pAccum->mallocFailed ){
88688       sqlite3_result_error_nomem(context);
88689     }else{    
88690       sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1, 
88691                           sqlite3_free);
88692     }
88693   }
88694 }
88695
88696 /*
88697 ** This routine does per-connection function registration.  Most
88698 ** of the built-in functions above are part of the global function set.
88699 ** This routine only deals with those that are not global.
88700 */
88701 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
88702   int rc = sqlite3_overload_function(db, "MATCH", 2);
88703   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
88704   if( rc==SQLITE_NOMEM ){
88705     db->mallocFailed = 1;
88706   }
88707 }
88708
88709 /*
88710 ** Set the LIKEOPT flag on the 2-argument function with the given name.
88711 */
88712 static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
88713   FuncDef *pDef;
88714   pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
88715                              2, SQLITE_UTF8, 0);
88716   if( ALWAYS(pDef) ){
88717     pDef->flags = flagVal;
88718   }
88719 }
88720
88721 /*
88722 ** Register the built-in LIKE and GLOB functions.  The caseSensitive
88723 ** parameter determines whether or not the LIKE operator is case
88724 ** sensitive.  GLOB is always case sensitive.
88725 */
88726 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
88727   struct compareInfo *pInfo;
88728   if( caseSensitive ){
88729     pInfo = (struct compareInfo*)&likeInfoAlt;
88730   }else{
88731     pInfo = (struct compareInfo*)&likeInfoNorm;
88732   }
88733   sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
88734   sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
88735   sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8, 
88736       (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
88737   setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
88738   setLikeOptFlag(db, "like", 
88739       caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
88740 }
88741
88742 /*
88743 ** pExpr points to an expression which implements a function.  If
88744 ** it is appropriate to apply the LIKE optimization to that function
88745 ** then set aWc[0] through aWc[2] to the wildcard characters and
88746 ** return TRUE.  If the function is not a LIKE-style function then
88747 ** return FALSE.
88748 */
88749 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
88750   FuncDef *pDef;
88751   if( pExpr->op!=TK_FUNCTION 
88752    || !pExpr->x.pList 
88753    || pExpr->x.pList->nExpr!=2
88754   ){
88755     return 0;
88756   }
88757   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
88758   pDef = sqlite3FindFunction(db, pExpr->u.zToken, 
88759                              sqlite3Strlen30(pExpr->u.zToken),
88760                              2, SQLITE_UTF8, 0);
88761   if( NEVER(pDef==0) || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
88762     return 0;
88763   }
88764
88765   /* The memcpy() statement assumes that the wildcard characters are
88766   ** the first three statements in the compareInfo structure.  The
88767   ** asserts() that follow verify that assumption
88768   */
88769   memcpy(aWc, pDef->pUserData, 3);
88770   assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
88771   assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
88772   assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
88773   *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
88774   return 1;
88775 }
88776
88777 /*
88778 ** All all of the FuncDef structures in the aBuiltinFunc[] array above
88779 ** to the global function hash table.  This occurs at start-time (as
88780 ** a consequence of calling sqlite3_initialize()).
88781 **
88782 ** After this routine runs
88783 */
88784 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
88785   /*
88786   ** The following array holds FuncDef structures for all of the functions
88787   ** defined in this file.
88788   **
88789   ** The array cannot be constant since changes are made to the
88790   ** FuncDef.pHash elements at start-time.  The elements of this array
88791   ** are read-only after initialization is complete.
88792   */
88793   static SQLITE_WSD FuncDef aBuiltinFunc[] = {
88794     FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
88795     FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
88796     FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
88797     FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
88798     FUNCTION(trim,               1, 3, 0, trimFunc         ),
88799     FUNCTION(trim,               2, 3, 0, trimFunc         ),
88800     FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
88801     FUNCTION(min,                0, 0, 1, 0                ),
88802     AGGREGATE(min,               1, 0, 1, minmaxStep,      minMaxFinalize ),
88803     FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
88804     FUNCTION(max,                0, 1, 1, 0                ),
88805     AGGREGATE(max,               1, 1, 1, minmaxStep,      minMaxFinalize ),
88806     FUNCTION2(typeof,            1, 0, 0, typeofFunc,  SQLITE_FUNC_TYPEOF),
88807     FUNCTION2(length,            1, 0, 0, lengthFunc,  SQLITE_FUNC_LENGTH),
88808     FUNCTION(instr,              2, 0, 0, instrFunc        ),
88809     FUNCTION(substr,             2, 0, 0, substrFunc       ),
88810     FUNCTION(substr,             3, 0, 0, substrFunc       ),
88811     FUNCTION(unicode,            1, 0, 0, unicodeFunc      ),
88812     FUNCTION(char,              -1, 0, 0, charFunc         ),
88813     FUNCTION(abs,                1, 0, 0, absFunc          ),
88814 #ifndef SQLITE_OMIT_FLOATING_POINT
88815     FUNCTION(round,              1, 0, 0, roundFunc        ),
88816     FUNCTION(round,              2, 0, 0, roundFunc        ),
88817 #endif
88818     FUNCTION(upper,              1, 0, 0, upperFunc        ),
88819     FUNCTION(lower,              1, 0, 0, lowerFunc        ),
88820     FUNCTION(coalesce,           1, 0, 0, 0                ),
88821     FUNCTION(coalesce,           0, 0, 0, 0                ),
88822     FUNCTION2(coalesce,         -1, 0, 0, ifnullFunc,  SQLITE_FUNC_COALESCE),
88823     FUNCTION(hex,                1, 0, 0, hexFunc          ),
88824     FUNCTION2(ifnull,            2, 0, 0, ifnullFunc,  SQLITE_FUNC_COALESCE),
88825     FUNCTION(random,             0, 0, 0, randomFunc       ),
88826     FUNCTION(randomblob,         1, 0, 0, randomBlob       ),
88827     FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
88828     FUNCTION(sqlite_version,     0, 0, 0, versionFunc      ),
88829     FUNCTION(sqlite_source_id,   0, 0, 0, sourceidFunc     ),
88830     FUNCTION(sqlite_log,         2, 0, 0, errlogFunc       ),
88831 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
88832     FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
88833     FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
88834 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
88835     FUNCTION(quote,              1, 0, 0, quoteFunc        ),
88836     FUNCTION(last_insert_rowid,  0, 0, 0, last_insert_rowid),
88837     FUNCTION(changes,            0, 0, 0, changes          ),
88838     FUNCTION(total_changes,      0, 0, 0, total_changes    ),
88839     FUNCTION(replace,            3, 0, 0, replaceFunc      ),
88840     FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
88841   #ifdef SQLITE_SOUNDEX
88842     FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
88843   #endif
88844   #ifndef SQLITE_OMIT_LOAD_EXTENSION
88845     FUNCTION(load_extension,     1, 0, 0, loadExt          ),
88846     FUNCTION(load_extension,     2, 0, 0, loadExt          ),
88847   #endif
88848     AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
88849     AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
88850     AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
88851  /* AGGREGATE(count,             0, 0, 0, countStep,       countFinalize  ), */
88852     {0,SQLITE_UTF8,SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0,0},
88853     AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
88854     AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
88855     AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
88856   
88857     LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
88858   #ifdef SQLITE_CASE_SENSITIVE_LIKE
88859     LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
88860     LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
88861   #else
88862     LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
88863     LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
88864   #endif
88865   };
88866
88867   int i;
88868   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
88869   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
88870
88871   for(i=0; i<ArraySize(aBuiltinFunc); i++){
88872     sqlite3FuncDefInsert(pHash, &aFunc[i]);
88873   }
88874   sqlite3RegisterDateTimeFunctions();
88875 #ifndef SQLITE_OMIT_ALTERTABLE
88876   sqlite3AlterFunctions();
88877 #endif
88878 }
88879
88880 /************** End of func.c ************************************************/
88881 /************** Begin file fkey.c ********************************************/
88882 /*
88883 **
88884 ** The author disclaims copyright to this source code.  In place of
88885 ** a legal notice, here is a blessing:
88886 **
88887 **    May you do good and not evil.
88888 **    May you find forgiveness for yourself and forgive others.
88889 **    May you share freely, never taking more than you give.
88890 **
88891 *************************************************************************
88892 ** This file contains code used by the compiler to add foreign key
88893 ** support to compiled SQL statements.
88894 */
88895
88896 #ifndef SQLITE_OMIT_FOREIGN_KEY
88897 #ifndef SQLITE_OMIT_TRIGGER
88898
88899 /*
88900 ** Deferred and Immediate FKs
88901 ** --------------------------
88902 **
88903 ** Foreign keys in SQLite come in two flavours: deferred and immediate.
88904 ** If an immediate foreign key constraint is violated,
88905 ** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
88906 ** statement transaction rolled back. If a 
88907 ** deferred foreign key constraint is violated, no action is taken 
88908 ** immediately. However if the application attempts to commit the 
88909 ** transaction before fixing the constraint violation, the attempt fails.
88910 **
88911 ** Deferred constraints are implemented using a simple counter associated
88912 ** with the database handle. The counter is set to zero each time a 
88913 ** database transaction is opened. Each time a statement is executed 
88914 ** that causes a foreign key violation, the counter is incremented. Each
88915 ** time a statement is executed that removes an existing violation from
88916 ** the database, the counter is decremented. When the transaction is
88917 ** committed, the commit fails if the current value of the counter is
88918 ** greater than zero. This scheme has two big drawbacks:
88919 **
88920 **   * When a commit fails due to a deferred foreign key constraint, 
88921 **     there is no way to tell which foreign constraint is not satisfied,
88922 **     or which row it is not satisfied for.
88923 **
88924 **   * If the database contains foreign key violations when the 
88925 **     transaction is opened, this may cause the mechanism to malfunction.
88926 **
88927 ** Despite these problems, this approach is adopted as it seems simpler
88928 ** than the alternatives.
88929 **
88930 ** INSERT operations:
88931 **
88932 **   I.1) For each FK for which the table is the child table, search
88933 **        the parent table for a match. If none is found increment the
88934 **        constraint counter.
88935 **
88936 **   I.2) For each FK for which the table is the parent table, 
88937 **        search the child table for rows that correspond to the new
88938 **        row in the parent table. Decrement the counter for each row
88939 **        found (as the constraint is now satisfied).
88940 **
88941 ** DELETE operations:
88942 **
88943 **   D.1) For each FK for which the table is the child table, 
88944 **        search the parent table for a row that corresponds to the 
88945 **        deleted row in the child table. If such a row is not found, 
88946 **        decrement the counter.
88947 **
88948 **   D.2) For each FK for which the table is the parent table, search 
88949 **        the child table for rows that correspond to the deleted row 
88950 **        in the parent table. For each found increment the counter.
88951 **
88952 ** UPDATE operations:
88953 **
88954 **   An UPDATE command requires that all 4 steps above are taken, but only
88955 **   for FK constraints for which the affected columns are actually 
88956 **   modified (values must be compared at runtime).
88957 **
88958 ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
88959 ** This simplifies the implementation a bit.
88960 **
88961 ** For the purposes of immediate FK constraints, the OR REPLACE conflict
88962 ** resolution is considered to delete rows before the new row is inserted.
88963 ** If a delete caused by OR REPLACE violates an FK constraint, an exception
88964 ** is thrown, even if the FK constraint would be satisfied after the new 
88965 ** row is inserted.
88966 **
88967 ** Immediate constraints are usually handled similarly. The only difference 
88968 ** is that the counter used is stored as part of each individual statement
88969 ** object (struct Vdbe). If, after the statement has run, its immediate
88970 ** constraint counter is greater than zero,
88971 ** it returns SQLITE_CONSTRAINT_FOREIGNKEY
88972 ** and the statement transaction is rolled back. An exception is an INSERT
88973 ** statement that inserts a single row only (no triggers). In this case,
88974 ** instead of using a counter, an exception is thrown immediately if the
88975 ** INSERT violates a foreign key constraint. This is necessary as such
88976 ** an INSERT does not open a statement transaction.
88977 **
88978 ** TODO: How should dropping a table be handled? How should renaming a 
88979 ** table be handled?
88980 **
88981 **
88982 ** Query API Notes
88983 ** ---------------
88984 **
88985 ** Before coding an UPDATE or DELETE row operation, the code-generator
88986 ** for those two operations needs to know whether or not the operation
88987 ** requires any FK processing and, if so, which columns of the original
88988 ** row are required by the FK processing VDBE code (i.e. if FKs were
88989 ** implemented using triggers, which of the old.* columns would be 
88990 ** accessed). No information is required by the code-generator before
88991 ** coding an INSERT operation. The functions used by the UPDATE/DELETE
88992 ** generation code to query for this information are:
88993 **
88994 **   sqlite3FkRequired() - Test to see if FK processing is required.
88995 **   sqlite3FkOldmask()  - Query for the set of required old.* columns.
88996 **
88997 **
88998 ** Externally accessible module functions
88999 ** --------------------------------------
89000 **
89001 **   sqlite3FkCheck()    - Check for foreign key violations.
89002 **   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
89003 **   sqlite3FkDelete()   - Delete an FKey structure.
89004 */
89005
89006 /*
89007 ** VDBE Calling Convention
89008 ** -----------------------
89009 **
89010 ** Example:
89011 **
89012 **   For the following INSERT statement:
89013 **
89014 **     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
89015 **     INSERT INTO t1 VALUES(1, 2, 3.1);
89016 **
89017 **   Register (x):        2    (type integer)
89018 **   Register (x+1):      1    (type integer)
89019 **   Register (x+2):      NULL (type NULL)
89020 **   Register (x+3):      3.1  (type real)
89021 */
89022
89023 /*
89024 ** A foreign key constraint requires that the key columns in the parent
89025 ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
89026 ** Given that pParent is the parent table for foreign key constraint pFKey, 
89027 ** search the schema for a unique index on the parent key columns. 
89028 **
89029 ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY 
89030 ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx 
89031 ** is set to point to the unique index. 
89032 ** 
89033 ** If the parent key consists of a single column (the foreign key constraint
89034 ** is not a composite foreign key), output variable *paiCol is set to NULL.
89035 ** Otherwise, it is set to point to an allocated array of size N, where
89036 ** N is the number of columns in the parent key. The first element of the
89037 ** array is the index of the child table column that is mapped by the FK
89038 ** constraint to the parent table column stored in the left-most column
89039 ** of index *ppIdx. The second element of the array is the index of the
89040 ** child table column that corresponds to the second left-most column of
89041 ** *ppIdx, and so on.
89042 **
89043 ** If the required index cannot be found, either because:
89044 **
89045 **   1) The named parent key columns do not exist, or
89046 **
89047 **   2) The named parent key columns do exist, but are not subject to a
89048 **      UNIQUE or PRIMARY KEY constraint, or
89049 **
89050 **   3) No parent key columns were provided explicitly as part of the
89051 **      foreign key definition, and the parent table does not have a
89052 **      PRIMARY KEY, or
89053 **
89054 **   4) No parent key columns were provided explicitly as part of the
89055 **      foreign key definition, and the PRIMARY KEY of the parent table 
89056 **      consists of a a different number of columns to the child key in 
89057 **      the child table.
89058 **
89059 ** then non-zero is returned, and a "foreign key mismatch" error loaded
89060 ** into pParse. If an OOM error occurs, non-zero is returned and the
89061 ** pParse->db->mallocFailed flag is set.
89062 */
89063 SQLITE_PRIVATE int sqlite3FkLocateIndex(
89064   Parse *pParse,                  /* Parse context to store any error in */
89065   Table *pParent,                 /* Parent table of FK constraint pFKey */
89066   FKey *pFKey,                    /* Foreign key to find index for */
89067   Index **ppIdx,                  /* OUT: Unique index on parent table */
89068   int **paiCol                    /* OUT: Map of index columns in pFKey */
89069 ){
89070   Index *pIdx = 0;                    /* Value to return via *ppIdx */
89071   int *aiCol = 0;                     /* Value to return via *paiCol */
89072   int nCol = pFKey->nCol;             /* Number of columns in parent key */
89073   char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
89074
89075   /* The caller is responsible for zeroing output parameters. */
89076   assert( ppIdx && *ppIdx==0 );
89077   assert( !paiCol || *paiCol==0 );
89078   assert( pParse );
89079
89080   /* If this is a non-composite (single column) foreign key, check if it 
89081   ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx 
89082   ** and *paiCol set to zero and return early. 
89083   **
89084   ** Otherwise, for a composite foreign key (more than one column), allocate
89085   ** space for the aiCol array (returned via output parameter *paiCol).
89086   ** Non-composite foreign keys do not require the aiCol array.
89087   */
89088   if( nCol==1 ){
89089     /* The FK maps to the IPK if any of the following are true:
89090     **
89091     **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly 
89092     **      mapped to the primary key of table pParent, or
89093     **   2) The FK is explicitly mapped to a column declared as INTEGER
89094     **      PRIMARY KEY.
89095     */
89096     if( pParent->iPKey>=0 ){
89097       if( !zKey ) return 0;
89098       if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
89099     }
89100   }else if( paiCol ){
89101     assert( nCol>1 );
89102     aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
89103     if( !aiCol ) return 1;
89104     *paiCol = aiCol;
89105   }
89106
89107   for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
89108     if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){ 
89109       /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
89110       ** of columns. If each indexed column corresponds to a foreign key
89111       ** column of pFKey, then this index is a winner.  */
89112
89113       if( zKey==0 ){
89114         /* If zKey is NULL, then this foreign key is implicitly mapped to 
89115         ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be 
89116         ** identified by the test (Index.autoIndex==2).  */
89117         if( pIdx->autoIndex==2 ){
89118           if( aiCol ){
89119             int i;
89120             for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
89121           }
89122           break;
89123         }
89124       }else{
89125         /* If zKey is non-NULL, then this foreign key was declared to
89126         ** map to an explicit list of columns in table pParent. Check if this
89127         ** index matches those columns. Also, check that the index uses
89128         ** the default collation sequences for each column. */
89129         int i, j;
89130         for(i=0; i<nCol; i++){
89131           int iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
89132           char *zDfltColl;                  /* Def. collation for column */
89133           char *zIdxCol;                    /* Name of indexed column */
89134
89135           /* If the index uses a collation sequence that is different from
89136           ** the default collation sequence for the column, this index is
89137           ** unusable. Bail out early in this case.  */
89138           zDfltColl = pParent->aCol[iCol].zColl;
89139           if( !zDfltColl ){
89140             zDfltColl = "BINARY";
89141           }
89142           if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
89143
89144           zIdxCol = pParent->aCol[iCol].zName;
89145           for(j=0; j<nCol; j++){
89146             if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
89147               if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
89148               break;
89149             }
89150           }
89151           if( j==nCol ) break;
89152         }
89153         if( i==nCol ) break;      /* pIdx is usable */
89154       }
89155     }
89156   }
89157
89158   if( !pIdx ){
89159     if( !pParse->disableTriggers ){
89160       sqlite3ErrorMsg(pParse,
89161            "foreign key mismatch - \"%w\" referencing \"%w\"",
89162            pFKey->pFrom->zName, pFKey->zTo);
89163     }
89164     sqlite3DbFree(pParse->db, aiCol);
89165     return 1;
89166   }
89167
89168   *ppIdx = pIdx;
89169   return 0;
89170 }
89171
89172 /*
89173 ** This function is called when a row is inserted into or deleted from the 
89174 ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed 
89175 ** on the child table of pFKey, this function is invoked twice for each row
89176 ** affected - once to "delete" the old row, and then again to "insert" the
89177 ** new row.
89178 **
89179 ** Each time it is called, this function generates VDBE code to locate the
89180 ** row in the parent table that corresponds to the row being inserted into 
89181 ** or deleted from the child table. If the parent row can be found, no 
89182 ** special action is taken. Otherwise, if the parent row can *not* be
89183 ** found in the parent table:
89184 **
89185 **   Operation | FK type   | Action taken
89186 **   --------------------------------------------------------------------------
89187 **   INSERT      immediate   Increment the "immediate constraint counter".
89188 **
89189 **   DELETE      immediate   Decrement the "immediate constraint counter".
89190 **
89191 **   INSERT      deferred    Increment the "deferred constraint counter".
89192 **
89193 **   DELETE      deferred    Decrement the "deferred constraint counter".
89194 **
89195 ** These operations are identified in the comment at the top of this file 
89196 ** (fkey.c) as "I.1" and "D.1".
89197 */
89198 static void fkLookupParent(
89199   Parse *pParse,        /* Parse context */
89200   int iDb,              /* Index of database housing pTab */
89201   Table *pTab,          /* Parent table of FK pFKey */
89202   Index *pIdx,          /* Unique index on parent key columns in pTab */
89203   FKey *pFKey,          /* Foreign key constraint */
89204   int *aiCol,           /* Map from parent key columns to child table columns */
89205   int regData,          /* Address of array containing child table row */
89206   int nIncr,            /* Increment constraint counter by this */
89207   int isIgnore          /* If true, pretend pTab contains all NULL values */
89208 ){
89209   int i;                                    /* Iterator variable */
89210   Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
89211   int iCur = pParse->nTab - 1;              /* Cursor number to use */
89212   int iOk = sqlite3VdbeMakeLabel(v);        /* jump here if parent key found */
89213
89214   /* If nIncr is less than zero, then check at runtime if there are any
89215   ** outstanding constraints to resolve. If there are not, there is no need
89216   ** to check if deleting this row resolves any outstanding violations.
89217   **
89218   ** Check if any of the key columns in the child table row are NULL. If 
89219   ** any are, then the constraint is considered satisfied. No need to 
89220   ** search for a matching row in the parent table.  */
89221   if( nIncr<0 ){
89222     sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
89223   }
89224   for(i=0; i<pFKey->nCol; i++){
89225     int iReg = aiCol[i] + regData + 1;
89226     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
89227   }
89228
89229   if( isIgnore==0 ){
89230     if( pIdx==0 ){
89231       /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
89232       ** column of the parent table (table pTab).  */
89233       int iMustBeInt;               /* Address of MustBeInt instruction */
89234       int regTemp = sqlite3GetTempReg(pParse);
89235   
89236       /* Invoke MustBeInt to coerce the child key value to an integer (i.e. 
89237       ** apply the affinity of the parent key). If this fails, then there
89238       ** is no matching parent key. Before using MustBeInt, make a copy of
89239       ** the value. Otherwise, the value inserted into the child key column
89240       ** will have INTEGER affinity applied to it, which may not be correct.  */
89241       sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
89242       iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
89243   
89244       /* If the parent table is the same as the child table, and we are about
89245       ** to increment the constraint-counter (i.e. this is an INSERT operation),
89246       ** then check if the row being inserted matches itself. If so, do not
89247       ** increment the constraint-counter.  */
89248       if( pTab==pFKey->pFrom && nIncr==1 ){
89249         sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);
89250       }
89251   
89252       sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
89253       sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
89254       sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
89255       sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
89256       sqlite3VdbeJumpHere(v, iMustBeInt);
89257       sqlite3ReleaseTempReg(pParse, regTemp);
89258     }else{
89259       int nCol = pFKey->nCol;
89260       int regTemp = sqlite3GetTempRange(pParse, nCol);
89261       int regRec = sqlite3GetTempReg(pParse);
89262       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
89263   
89264       sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
89265       sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
89266       for(i=0; i<nCol; i++){
89267         sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
89268       }
89269   
89270       /* If the parent table is the same as the child table, and we are about
89271       ** to increment the constraint-counter (i.e. this is an INSERT operation),
89272       ** then check if the row being inserted matches itself. If so, do not
89273       ** increment the constraint-counter. 
89274       **
89275       ** If any of the parent-key values are NULL, then the row cannot match 
89276       ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
89277       ** of the parent-key values are NULL (at this point it is known that
89278       ** none of the child key values are).
89279       */
89280       if( pTab==pFKey->pFrom && nIncr==1 ){
89281         int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
89282         for(i=0; i<nCol; i++){
89283           int iChild = aiCol[i]+1+regData;
89284           int iParent = pIdx->aiColumn[i]+1+regData;
89285           assert( aiCol[i]!=pTab->iPKey );
89286           if( pIdx->aiColumn[i]==pTab->iPKey ){
89287             /* The parent key is a composite key that includes the IPK column */
89288             iParent = regData;
89289           }
89290           sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);
89291           sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
89292         }
89293         sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
89294       }
89295   
89296       sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
89297       sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v,pIdx), P4_TRANSIENT);
89298       sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0);
89299   
89300       sqlite3ReleaseTempReg(pParse, regRec);
89301       sqlite3ReleaseTempRange(pParse, regTemp, nCol);
89302     }
89303   }
89304
89305   if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
89306     /* Special case: If this is an INSERT statement that will insert exactly
89307     ** one row into the table, raise a constraint immediately instead of
89308     ** incrementing a counter. This is necessary as the VM code is being
89309     ** generated for will not open a statement transaction.  */
89310     assert( nIncr==1 );
89311     sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
89312         OE_Abort, "foreign key constraint failed", P4_STATIC
89313     );
89314   }else{
89315     if( nIncr>0 && pFKey->isDeferred==0 ){
89316       sqlite3ParseToplevel(pParse)->mayAbort = 1;
89317     }
89318     sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
89319   }
89320
89321   sqlite3VdbeResolveLabel(v, iOk);
89322   sqlite3VdbeAddOp1(v, OP_Close, iCur);
89323 }
89324
89325 /*
89326 ** This function is called to generate code executed when a row is deleted
89327 ** from the parent table of foreign key constraint pFKey and, if pFKey is 
89328 ** deferred, when a row is inserted into the same table. When generating
89329 ** code for an SQL UPDATE operation, this function may be called twice -
89330 ** once to "delete" the old row and once to "insert" the new row.
89331 **
89332 ** The code generated by this function scans through the rows in the child
89333 ** table that correspond to the parent table row being deleted or inserted.
89334 ** For each child row found, one of the following actions is taken:
89335 **
89336 **   Operation | FK type   | Action taken
89337 **   --------------------------------------------------------------------------
89338 **   DELETE      immediate   Increment the "immediate constraint counter".
89339 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
89340 **                           throw a "foreign key constraint failed" exception.
89341 **
89342 **   INSERT      immediate   Decrement the "immediate constraint counter".
89343 **
89344 **   DELETE      deferred    Increment the "deferred constraint counter".
89345 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
89346 **                           throw a "foreign key constraint failed" exception.
89347 **
89348 **   INSERT      deferred    Decrement the "deferred constraint counter".
89349 **
89350 ** These operations are identified in the comment at the top of this file 
89351 ** (fkey.c) as "I.2" and "D.2".
89352 */
89353 static void fkScanChildren(
89354   Parse *pParse,                  /* Parse context */
89355   SrcList *pSrc,                  /* SrcList containing the table to scan */
89356   Table *pTab,
89357   Index *pIdx,                    /* Foreign key index */
89358   FKey *pFKey,                    /* Foreign key relationship */
89359   int *aiCol,                     /* Map from pIdx cols to child table cols */
89360   int regData,                    /* Referenced table data starts here */
89361   int nIncr                       /* Amount to increment deferred counter by */
89362 ){
89363   sqlite3 *db = pParse->db;       /* Database handle */
89364   int i;                          /* Iterator variable */
89365   Expr *pWhere = 0;               /* WHERE clause to scan with */
89366   NameContext sNameContext;       /* Context used to resolve WHERE clause */
89367   WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
89368   int iFkIfZero = 0;              /* Address of OP_FkIfZero */
89369   Vdbe *v = sqlite3GetVdbe(pParse);
89370
89371   assert( !pIdx || pIdx->pTable==pTab );
89372
89373   if( nIncr<0 ){
89374     iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
89375   }
89376
89377   /* Create an Expr object representing an SQL expression like:
89378   **
89379   **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
89380   **
89381   ** The collation sequence used for the comparison should be that of
89382   ** the parent key columns. The affinity of the parent key column should
89383   ** be applied to each child key value before the comparison takes place.
89384   */
89385   for(i=0; i<pFKey->nCol; i++){
89386     Expr *pLeft;                  /* Value from parent table row */
89387     Expr *pRight;                 /* Column ref to child table */
89388     Expr *pEq;                    /* Expression (pLeft = pRight) */
89389     int iCol;                     /* Index of column in child table */ 
89390     const char *zCol;             /* Name of column in child table */
89391
89392     pLeft = sqlite3Expr(db, TK_REGISTER, 0);
89393     if( pLeft ){
89394       /* Set the collation sequence and affinity of the LHS of each TK_EQ
89395       ** expression to the parent key column defaults.  */
89396       if( pIdx ){
89397         Column *pCol;
89398         const char *zColl;
89399         iCol = pIdx->aiColumn[i];
89400         pCol = &pTab->aCol[iCol];
89401         if( pTab->iPKey==iCol ) iCol = -1;
89402         pLeft->iTable = regData+iCol+1;
89403         pLeft->affinity = pCol->affinity;
89404         zColl = pCol->zColl;
89405         if( zColl==0 ) zColl = db->pDfltColl->zName;
89406         pLeft = sqlite3ExprAddCollateString(pParse, pLeft, zColl);
89407       }else{
89408         pLeft->iTable = regData;
89409         pLeft->affinity = SQLITE_AFF_INTEGER;
89410       }
89411     }
89412     iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
89413     assert( iCol>=0 );
89414     zCol = pFKey->pFrom->aCol[iCol].zName;
89415     pRight = sqlite3Expr(db, TK_ID, zCol);
89416     pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
89417     pWhere = sqlite3ExprAnd(db, pWhere, pEq);
89418   }
89419
89420   /* If the child table is the same as the parent table, and this scan
89421   ** is taking place as part of a DELETE operation (operation D.2), omit the
89422   ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE 
89423   ** clause, where $rowid is the rowid of the row being deleted.  */
89424   if( pTab==pFKey->pFrom && nIncr>0 ){
89425     Expr *pEq;                    /* Expression (pLeft = pRight) */
89426     Expr *pLeft;                  /* Value from parent table row */
89427     Expr *pRight;                 /* Column ref to child table */
89428     pLeft = sqlite3Expr(db, TK_REGISTER, 0);
89429     pRight = sqlite3Expr(db, TK_COLUMN, 0);
89430     if( pLeft && pRight ){
89431       pLeft->iTable = regData;
89432       pLeft->affinity = SQLITE_AFF_INTEGER;
89433       pRight->iTable = pSrc->a[0].iCursor;
89434       pRight->iColumn = -1;
89435     }
89436     pEq = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
89437     pWhere = sqlite3ExprAnd(db, pWhere, pEq);
89438   }
89439
89440   /* Resolve the references in the WHERE clause. */
89441   memset(&sNameContext, 0, sizeof(NameContext));
89442   sNameContext.pSrcList = pSrc;
89443   sNameContext.pParse = pParse;
89444   sqlite3ResolveExprNames(&sNameContext, pWhere);
89445
89446   /* Create VDBE to loop through the entries in pSrc that match the WHERE
89447   ** clause. If the constraint is not deferred, throw an exception for
89448   ** each row found. Otherwise, for deferred constraints, increment the
89449   ** deferred constraint counter by nIncr for each row selected.  */
89450   pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
89451   if( nIncr>0 && pFKey->isDeferred==0 ){
89452     sqlite3ParseToplevel(pParse)->mayAbort = 1;
89453   }
89454   sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
89455   if( pWInfo ){
89456     sqlite3WhereEnd(pWInfo);
89457   }
89458
89459   /* Clean up the WHERE clause constructed above. */
89460   sqlite3ExprDelete(db, pWhere);
89461   if( iFkIfZero ){
89462     sqlite3VdbeJumpHere(v, iFkIfZero);
89463   }
89464 }
89465
89466 /*
89467 ** This function returns a pointer to the head of a linked list of FK
89468 ** constraints for which table pTab is the parent table. For example,
89469 ** given the following schema:
89470 **
89471 **   CREATE TABLE t1(a PRIMARY KEY);
89472 **   CREATE TABLE t2(b REFERENCES t1(a);
89473 **
89474 ** Calling this function with table "t1" as an argument returns a pointer
89475 ** to the FKey structure representing the foreign key constraint on table
89476 ** "t2". Calling this function with "t2" as the argument would return a
89477 ** NULL pointer (as there are no FK constraints for which t2 is the parent
89478 ** table).
89479 */
89480 SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
89481   int nName = sqlite3Strlen30(pTab->zName);
89482   return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
89483 }
89484
89485 /*
89486 ** The second argument is a Trigger structure allocated by the 
89487 ** fkActionTrigger() routine. This function deletes the Trigger structure
89488 ** and all of its sub-components.
89489 **
89490 ** The Trigger structure or any of its sub-components may be allocated from
89491 ** the lookaside buffer belonging to database handle dbMem.
89492 */
89493 static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
89494   if( p ){
89495     TriggerStep *pStep = p->step_list;
89496     sqlite3ExprDelete(dbMem, pStep->pWhere);
89497     sqlite3ExprListDelete(dbMem, pStep->pExprList);
89498     sqlite3SelectDelete(dbMem, pStep->pSelect);
89499     sqlite3ExprDelete(dbMem, p->pWhen);
89500     sqlite3DbFree(dbMem, p);
89501   }
89502 }
89503
89504 /*
89505 ** This function is called to generate code that runs when table pTab is
89506 ** being dropped from the database. The SrcList passed as the second argument
89507 ** to this function contains a single entry guaranteed to resolve to
89508 ** table pTab.
89509 **
89510 ** Normally, no code is required. However, if either
89511 **
89512 **   (a) The table is the parent table of a FK constraint, or
89513 **   (b) The table is the child table of a deferred FK constraint and it is
89514 **       determined at runtime that there are outstanding deferred FK 
89515 **       constraint violations in the database,
89516 **
89517 ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
89518 ** the table from the database. Triggers are disabled while running this
89519 ** DELETE, but foreign key actions are not.
89520 */
89521 SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
89522   sqlite3 *db = pParse->db;
89523   if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
89524     int iSkip = 0;
89525     Vdbe *v = sqlite3GetVdbe(pParse);
89526
89527     assert( v );                  /* VDBE has already been allocated */
89528     if( sqlite3FkReferences(pTab)==0 ){
89529       /* Search for a deferred foreign key constraint for which this table
89530       ** is the child table. If one cannot be found, return without 
89531       ** generating any VDBE code. If one can be found, then jump over
89532       ** the entire DELETE if there are no outstanding deferred constraints
89533       ** when this statement is run.  */
89534       FKey *p;
89535       for(p=pTab->pFKey; p; p=p->pNextFrom){
89536         if( p->isDeferred ) break;
89537       }
89538       if( !p ) return;
89539       iSkip = sqlite3VdbeMakeLabel(v);
89540       sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);
89541     }
89542
89543     pParse->disableTriggers = 1;
89544     sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
89545     pParse->disableTriggers = 0;
89546
89547     /* If the DELETE has generated immediate foreign key constraint 
89548     ** violations, halt the VDBE and return an error at this point, before
89549     ** any modifications to the schema are made. This is because statement
89550     ** transactions are not able to rollback schema changes.  */
89551     sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
89552     sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
89553         OE_Abort, "foreign key constraint failed", P4_STATIC
89554     );
89555
89556     if( iSkip ){
89557       sqlite3VdbeResolveLabel(v, iSkip);
89558     }
89559   }
89560 }
89561
89562 /*
89563 ** This function is called when inserting, deleting or updating a row of
89564 ** table pTab to generate VDBE code to perform foreign key constraint 
89565 ** processing for the operation.
89566 **
89567 ** For a DELETE operation, parameter regOld is passed the index of the
89568 ** first register in an array of (pTab->nCol+1) registers containing the
89569 ** rowid of the row being deleted, followed by each of the column values
89570 ** of the row being deleted, from left to right. Parameter regNew is passed
89571 ** zero in this case.
89572 **
89573 ** For an INSERT operation, regOld is passed zero and regNew is passed the
89574 ** first register of an array of (pTab->nCol+1) registers containing the new
89575 ** row data.
89576 **
89577 ** For an UPDATE operation, this function is called twice. Once before
89578 ** the original record is deleted from the table using the calling convention
89579 ** described for DELETE. Then again after the original record is deleted
89580 ** but before the new record is inserted using the INSERT convention. 
89581 */
89582 SQLITE_PRIVATE void sqlite3FkCheck(
89583   Parse *pParse,                  /* Parse context */
89584   Table *pTab,                    /* Row is being deleted from this table */ 
89585   int regOld,                     /* Previous row data is stored here */
89586   int regNew                      /* New row data is stored here */
89587 ){
89588   sqlite3 *db = pParse->db;       /* Database handle */
89589   FKey *pFKey;                    /* Used to iterate through FKs */
89590   int iDb;                        /* Index of database containing pTab */
89591   const char *zDb;                /* Name of database containing pTab */
89592   int isIgnoreErrors = pParse->disableTriggers;
89593
89594   /* Exactly one of regOld and regNew should be non-zero. */
89595   assert( (regOld==0)!=(regNew==0) );
89596
89597   /* If foreign-keys are disabled, this function is a no-op. */
89598   if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
89599
89600   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
89601   zDb = db->aDb[iDb].zName;
89602
89603   /* Loop through all the foreign key constraints for which pTab is the
89604   ** child table (the table that the foreign key definition is part of).  */
89605   for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
89606     Table *pTo;                   /* Parent table of foreign key pFKey */
89607     Index *pIdx = 0;              /* Index on key columns in pTo */
89608     int *aiFree = 0;
89609     int *aiCol;
89610     int iCol;
89611     int i;
89612     int isIgnore = 0;
89613
89614     /* Find the parent table of this foreign key. Also find a unique index 
89615     ** on the parent key columns in the parent table. If either of these 
89616     ** schema items cannot be located, set an error in pParse and return 
89617     ** early.  */
89618     if( pParse->disableTriggers ){
89619       pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
89620     }else{
89621       pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
89622     }
89623     if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
89624       assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
89625       if( !isIgnoreErrors || db->mallocFailed ) return;
89626       if( pTo==0 ){
89627         /* If isIgnoreErrors is true, then a table is being dropped. In this
89628         ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
89629         ** before actually dropping it in order to check FK constraints.
89630         ** If the parent table of an FK constraint on the current table is
89631         ** missing, behave as if it is empty. i.e. decrement the relevant
89632         ** FK counter for each row of the current table with non-NULL keys.
89633         */
89634         Vdbe *v = sqlite3GetVdbe(pParse);
89635         int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
89636         for(i=0; i<pFKey->nCol; i++){
89637           int iReg = pFKey->aCol[i].iFrom + regOld + 1;
89638           sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump);
89639         }
89640         sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
89641       }
89642       continue;
89643     }
89644     assert( pFKey->nCol==1 || (aiFree && pIdx) );
89645
89646     if( aiFree ){
89647       aiCol = aiFree;
89648     }else{
89649       iCol = pFKey->aCol[0].iFrom;
89650       aiCol = &iCol;
89651     }
89652     for(i=0; i<pFKey->nCol; i++){
89653       if( aiCol[i]==pTab->iPKey ){
89654         aiCol[i] = -1;
89655       }
89656 #ifndef SQLITE_OMIT_AUTHORIZATION
89657       /* Request permission to read the parent key columns. If the 
89658       ** authorization callback returns SQLITE_IGNORE, behave as if any
89659       ** values read from the parent table are NULL. */
89660       if( db->xAuth ){
89661         int rcauth;
89662         char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
89663         rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
89664         isIgnore = (rcauth==SQLITE_IGNORE);
89665       }
89666 #endif
89667     }
89668
89669     /* Take a shared-cache advisory read-lock on the parent table. Allocate 
89670     ** a cursor to use to search the unique index on the parent key columns 
89671     ** in the parent table.  */
89672     sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
89673     pParse->nTab++;
89674
89675     if( regOld!=0 ){
89676       /* A row is being removed from the child table. Search for the parent.
89677       ** If the parent does not exist, removing the child row resolves an 
89678       ** outstanding foreign key constraint violation. */
89679       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
89680     }
89681     if( regNew!=0 ){
89682       /* A row is being added to the child table. If a parent row cannot
89683       ** be found, adding the child row has violated the FK constraint. */ 
89684       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
89685     }
89686
89687     sqlite3DbFree(db, aiFree);
89688   }
89689
89690   /* Loop through all the foreign key constraints that refer to this table */
89691   for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
89692     Index *pIdx = 0;              /* Foreign key index for pFKey */
89693     SrcList *pSrc;
89694     int *aiCol = 0;
89695
89696     if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
89697       assert( regOld==0 && regNew!=0 );
89698       /* Inserting a single row into a parent table cannot cause an immediate
89699       ** foreign key violation. So do nothing in this case.  */
89700       continue;
89701     }
89702
89703     if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
89704       if( !isIgnoreErrors || db->mallocFailed ) return;
89705       continue;
89706     }
89707     assert( aiCol || pFKey->nCol==1 );
89708
89709     /* Create a SrcList structure containing a single table (the table 
89710     ** the foreign key that refers to this table is attached to). This
89711     ** is required for the sqlite3WhereXXX() interface.  */
89712     pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
89713     if( pSrc ){
89714       struct SrcList_item *pItem = pSrc->a;
89715       pItem->pTab = pFKey->pFrom;
89716       pItem->zName = pFKey->pFrom->zName;
89717       pItem->pTab->nRef++;
89718       pItem->iCursor = pParse->nTab++;
89719   
89720       if( regNew!=0 ){
89721         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
89722       }
89723       if( regOld!=0 ){
89724         /* If there is a RESTRICT action configured for the current operation
89725         ** on the parent table of this FK, then throw an exception 
89726         ** immediately if the FK constraint is violated, even if this is a
89727         ** deferred trigger. That's what RESTRICT means. To defer checking
89728         ** the constraint, the FK should specify NO ACTION (represented
89729         ** using OE_None). NO ACTION is the default.  */
89730         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
89731       }
89732       pItem->zName = 0;
89733       sqlite3SrcListDelete(db, pSrc);
89734     }
89735     sqlite3DbFree(db, aiCol);
89736   }
89737 }
89738
89739 #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
89740
89741 /*
89742 ** This function is called before generating code to update or delete a 
89743 ** row contained in table pTab.
89744 */
89745 SQLITE_PRIVATE u32 sqlite3FkOldmask(
89746   Parse *pParse,                  /* Parse context */
89747   Table *pTab                     /* Table being modified */
89748 ){
89749   u32 mask = 0;
89750   if( pParse->db->flags&SQLITE_ForeignKeys ){
89751     FKey *p;
89752     int i;
89753     for(p=pTab->pFKey; p; p=p->pNextFrom){
89754       for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
89755     }
89756     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
89757       Index *pIdx = 0;
89758       sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
89759       if( pIdx ){
89760         for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
89761       }
89762     }
89763   }
89764   return mask;
89765 }
89766
89767 /*
89768 ** This function is called before generating code to update or delete a 
89769 ** row contained in table pTab. If the operation is a DELETE, then
89770 ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
89771 ** to an array of size N, where N is the number of columns in table pTab.
89772 ** If the i'th column is not modified by the UPDATE, then the corresponding 
89773 ** entry in the aChange[] array is set to -1. If the column is modified,
89774 ** the value is 0 or greater. Parameter chngRowid is set to true if the
89775 ** UPDATE statement modifies the rowid fields of the table.
89776 **
89777 ** If any foreign key processing will be required, this function returns
89778 ** true. If there is no foreign key related processing, this function 
89779 ** returns false.
89780 */
89781 SQLITE_PRIVATE int sqlite3FkRequired(
89782   Parse *pParse,                  /* Parse context */
89783   Table *pTab,                    /* Table being modified */
89784   int *aChange,                   /* Non-NULL for UPDATE operations */
89785   int chngRowid                   /* True for UPDATE that affects rowid */
89786 ){
89787   if( pParse->db->flags&SQLITE_ForeignKeys ){
89788     if( !aChange ){
89789       /* A DELETE operation. Foreign key processing is required if the 
89790       ** table in question is either the child or parent table for any 
89791       ** foreign key constraint.  */
89792       return (sqlite3FkReferences(pTab) || pTab->pFKey);
89793     }else{
89794       /* This is an UPDATE. Foreign key processing is only required if the
89795       ** operation modifies one or more child or parent key columns. */
89796       int i;
89797       FKey *p;
89798
89799       /* Check if any child key columns are being modified. */
89800       for(p=pTab->pFKey; p; p=p->pNextFrom){
89801         for(i=0; i<p->nCol; i++){
89802           int iChildKey = p->aCol[i].iFrom;
89803           if( aChange[iChildKey]>=0 ) return 1;
89804           if( iChildKey==pTab->iPKey && chngRowid ) return 1;
89805         }
89806       }
89807
89808       /* Check if any parent key columns are being modified. */
89809       for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
89810         for(i=0; i<p->nCol; i++){
89811           char *zKey = p->aCol[i].zCol;
89812           int iKey;
89813           for(iKey=0; iKey<pTab->nCol; iKey++){
89814             Column *pCol = &pTab->aCol[iKey];
89815             if( (zKey ? !sqlite3StrICmp(pCol->zName, zKey)
89816                       : (pCol->colFlags & COLFLAG_PRIMKEY)!=0) ){
89817               if( aChange[iKey]>=0 ) return 1;
89818               if( iKey==pTab->iPKey && chngRowid ) return 1;
89819             }
89820           }
89821         }
89822       }
89823     }
89824   }
89825   return 0;
89826 }
89827
89828 /*
89829 ** This function is called when an UPDATE or DELETE operation is being 
89830 ** compiled on table pTab, which is the parent table of foreign-key pFKey.
89831 ** If the current operation is an UPDATE, then the pChanges parameter is
89832 ** passed a pointer to the list of columns being modified. If it is a
89833 ** DELETE, pChanges is passed a NULL pointer.
89834 **
89835 ** It returns a pointer to a Trigger structure containing a trigger
89836 ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
89837 ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
89838 ** returned (these actions require no special handling by the triggers
89839 ** sub-system, code for them is created by fkScanChildren()).
89840 **
89841 ** For example, if pFKey is the foreign key and pTab is table "p" in 
89842 ** the following schema:
89843 **
89844 **   CREATE TABLE p(pk PRIMARY KEY);
89845 **   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
89846 **
89847 ** then the returned trigger structure is equivalent to:
89848 **
89849 **   CREATE TRIGGER ... DELETE ON p BEGIN
89850 **     DELETE FROM c WHERE ck = old.pk;
89851 **   END;
89852 **
89853 ** The returned pointer is cached as part of the foreign key object. It
89854 ** is eventually freed along with the rest of the foreign key object by 
89855 ** sqlite3FkDelete().
89856 */
89857 static Trigger *fkActionTrigger(
89858   Parse *pParse,                  /* Parse context */
89859   Table *pTab,                    /* Table being updated or deleted from */
89860   FKey *pFKey,                    /* Foreign key to get action for */
89861   ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
89862 ){
89863   sqlite3 *db = pParse->db;       /* Database handle */
89864   int action;                     /* One of OE_None, OE_Cascade etc. */
89865   Trigger *pTrigger;              /* Trigger definition to return */
89866   int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
89867
89868   action = pFKey->aAction[iAction];
89869   pTrigger = pFKey->apTrigger[iAction];
89870
89871   if( action!=OE_None && !pTrigger ){
89872     u8 enableLookaside;           /* Copy of db->lookaside.bEnabled */
89873     char const *zFrom;            /* Name of child table */
89874     int nFrom;                    /* Length in bytes of zFrom */
89875     Index *pIdx = 0;              /* Parent key index for this FK */
89876     int *aiCol = 0;               /* child table cols -> parent key cols */
89877     TriggerStep *pStep = 0;        /* First (only) step of trigger program */
89878     Expr *pWhere = 0;             /* WHERE clause of trigger step */
89879     ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
89880     Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
89881     int i;                        /* Iterator variable */
89882     Expr *pWhen = 0;              /* WHEN clause for the trigger */
89883
89884     if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
89885     assert( aiCol || pFKey->nCol==1 );
89886
89887     for(i=0; i<pFKey->nCol; i++){
89888       Token tOld = { "old", 3 };  /* Literal "old" token */
89889       Token tNew = { "new", 3 };  /* Literal "new" token */
89890       Token tFromCol;             /* Name of column in child table */
89891       Token tToCol;               /* Name of column in parent table */
89892       int iFromCol;               /* Idx of column in child table */
89893       Expr *pEq;                  /* tFromCol = OLD.tToCol */
89894
89895       iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
89896       assert( iFromCol>=0 );
89897       tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
89898       tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
89899
89900       tToCol.n = sqlite3Strlen30(tToCol.z);
89901       tFromCol.n = sqlite3Strlen30(tFromCol.z);
89902
89903       /* Create the expression "OLD.zToCol = zFromCol". It is important
89904       ** that the "OLD.zToCol" term is on the LHS of the = operator, so
89905       ** that the affinity and collation sequence associated with the
89906       ** parent table are used for the comparison. */
89907       pEq = sqlite3PExpr(pParse, TK_EQ,
89908           sqlite3PExpr(pParse, TK_DOT, 
89909             sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
89910             sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
89911           , 0),
89912           sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
89913       , 0);
89914       pWhere = sqlite3ExprAnd(db, pWhere, pEq);
89915
89916       /* For ON UPDATE, construct the next term of the WHEN clause.
89917       ** The final WHEN clause will be like this:
89918       **
89919       **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
89920       */
89921       if( pChanges ){
89922         pEq = sqlite3PExpr(pParse, TK_IS,
89923             sqlite3PExpr(pParse, TK_DOT, 
89924               sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
89925               sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
89926               0),
89927             sqlite3PExpr(pParse, TK_DOT, 
89928               sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
89929               sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
89930               0),
89931             0);
89932         pWhen = sqlite3ExprAnd(db, pWhen, pEq);
89933       }
89934   
89935       if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
89936         Expr *pNew;
89937         if( action==OE_Cascade ){
89938           pNew = sqlite3PExpr(pParse, TK_DOT, 
89939             sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
89940             sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
89941           , 0);
89942         }else if( action==OE_SetDflt ){
89943           Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
89944           if( pDflt ){
89945             pNew = sqlite3ExprDup(db, pDflt, 0);
89946           }else{
89947             pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
89948           }
89949         }else{
89950           pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
89951         }
89952         pList = sqlite3ExprListAppend(pParse, pList, pNew);
89953         sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
89954       }
89955     }
89956     sqlite3DbFree(db, aiCol);
89957
89958     zFrom = pFKey->pFrom->zName;
89959     nFrom = sqlite3Strlen30(zFrom);
89960
89961     if( action==OE_Restrict ){
89962       Token tFrom;
89963       Expr *pRaise; 
89964
89965       tFrom.z = zFrom;
89966       tFrom.n = nFrom;
89967       pRaise = sqlite3Expr(db, TK_RAISE, "foreign key constraint failed");
89968       if( pRaise ){
89969         pRaise->affinity = OE_Abort;
89970       }
89971       pSelect = sqlite3SelectNew(pParse, 
89972           sqlite3ExprListAppend(pParse, 0, pRaise),
89973           sqlite3SrcListAppend(db, 0, &tFrom, 0),
89974           pWhere,
89975           0, 0, 0, 0, 0, 0
89976       );
89977       pWhere = 0;
89978     }
89979
89980     /* Disable lookaside memory allocation */
89981     enableLookaside = db->lookaside.bEnabled;
89982     db->lookaside.bEnabled = 0;
89983
89984     pTrigger = (Trigger *)sqlite3DbMallocZero(db, 
89985         sizeof(Trigger) +         /* struct Trigger */
89986         sizeof(TriggerStep) +     /* Single step in trigger program */
89987         nFrom + 1                 /* Space for pStep->target.z */
89988     );
89989     if( pTrigger ){
89990       pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
89991       pStep->target.z = (char *)&pStep[1];
89992       pStep->target.n = nFrom;
89993       memcpy((char *)pStep->target.z, zFrom, nFrom);
89994   
89995       pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
89996       pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
89997       pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
89998       if( pWhen ){
89999         pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
90000         pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
90001       }
90002     }
90003
90004     /* Re-enable the lookaside buffer, if it was disabled earlier. */
90005     db->lookaside.bEnabled = enableLookaside;
90006
90007     sqlite3ExprDelete(db, pWhere);
90008     sqlite3ExprDelete(db, pWhen);
90009     sqlite3ExprListDelete(db, pList);
90010     sqlite3SelectDelete(db, pSelect);
90011     if( db->mallocFailed==1 ){
90012       fkTriggerDelete(db, pTrigger);
90013       return 0;
90014     }
90015     assert( pStep!=0 );
90016
90017     switch( action ){
90018       case OE_Restrict:
90019         pStep->op = TK_SELECT; 
90020         break;
90021       case OE_Cascade: 
90022         if( !pChanges ){ 
90023           pStep->op = TK_DELETE; 
90024           break; 
90025         }
90026       default:
90027         pStep->op = TK_UPDATE;
90028     }
90029     pStep->pTrig = pTrigger;
90030     pTrigger->pSchema = pTab->pSchema;
90031     pTrigger->pTabSchema = pTab->pSchema;
90032     pFKey->apTrigger[iAction] = pTrigger;
90033     pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
90034   }
90035
90036   return pTrigger;
90037 }
90038
90039 /*
90040 ** This function is called when deleting or updating a row to implement
90041 ** any required CASCADE, SET NULL or SET DEFAULT actions.
90042 */
90043 SQLITE_PRIVATE void sqlite3FkActions(
90044   Parse *pParse,                  /* Parse context */
90045   Table *pTab,                    /* Table being updated or deleted from */
90046   ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
90047   int regOld                      /* Address of array containing old row */
90048 ){
90049   /* If foreign-key support is enabled, iterate through all FKs that 
90050   ** refer to table pTab. If there is an action associated with the FK 
90051   ** for this operation (either update or delete), invoke the associated 
90052   ** trigger sub-program.  */
90053   if( pParse->db->flags&SQLITE_ForeignKeys ){
90054     FKey *pFKey;                  /* Iterator variable */
90055     for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
90056       Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges);
90057       if( pAction ){
90058         sqlite3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0);
90059       }
90060     }
90061   }
90062 }
90063
90064 #endif /* ifndef SQLITE_OMIT_TRIGGER */
90065
90066 /*
90067 ** Free all memory associated with foreign key definitions attached to
90068 ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
90069 ** hash table.
90070 */
90071 SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
90072   FKey *pFKey;                    /* Iterator variable */
90073   FKey *pNext;                    /* Copy of pFKey->pNextFrom */
90074
90075   assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
90076   for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
90077
90078     /* Remove the FK from the fkeyHash hash table. */
90079     if( !db || db->pnBytesFreed==0 ){
90080       if( pFKey->pPrevTo ){
90081         pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
90082       }else{
90083         void *p = (void *)pFKey->pNextTo;
90084         const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
90085         sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), p);
90086       }
90087       if( pFKey->pNextTo ){
90088         pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
90089       }
90090     }
90091
90092     /* EV: R-30323-21917 Each foreign key constraint in SQLite is
90093     ** classified as either immediate or deferred.
90094     */
90095     assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
90096
90097     /* Delete any triggers created to implement actions for this FK. */
90098 #ifndef SQLITE_OMIT_TRIGGER
90099     fkTriggerDelete(db, pFKey->apTrigger[0]);
90100     fkTriggerDelete(db, pFKey->apTrigger[1]);
90101 #endif
90102
90103     pNext = pFKey->pNextFrom;
90104     sqlite3DbFree(db, pFKey);
90105   }
90106 }
90107 #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
90108
90109 /************** End of fkey.c ************************************************/
90110 /************** Begin file insert.c ******************************************/
90111 /*
90112 ** 2001 September 15
90113 **
90114 ** The author disclaims copyright to this source code.  In place of
90115 ** a legal notice, here is a blessing:
90116 **
90117 **    May you do good and not evil.
90118 **    May you find forgiveness for yourself and forgive others.
90119 **    May you share freely, never taking more than you give.
90120 **
90121 *************************************************************************
90122 ** This file contains C code routines that are called by the parser
90123 ** to handle INSERT statements in SQLite.
90124 */
90125
90126 /*
90127 ** Generate code that will open a table for reading.
90128 */
90129 SQLITE_PRIVATE void sqlite3OpenTable(
90130   Parse *p,       /* Generate code into this VDBE */
90131   int iCur,       /* The cursor number of the table */
90132   int iDb,        /* The database index in sqlite3.aDb[] */
90133   Table *pTab,    /* The table to be opened */
90134   int opcode      /* OP_OpenRead or OP_OpenWrite */
90135 ){
90136   Vdbe *v;
90137   assert( !IsVirtual(pTab) );
90138   v = sqlite3GetVdbe(p);
90139   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
90140   sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
90141   sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
90142   sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
90143   VdbeComment((v, "%s", pTab->zName));
90144 }
90145
90146 /*
90147 ** Return a pointer to the column affinity string associated with index
90148 ** pIdx. A column affinity string has one character for each column in 
90149 ** the table, according to the affinity of the column:
90150 **
90151 **  Character      Column affinity
90152 **  ------------------------------
90153 **  'a'            TEXT
90154 **  'b'            NONE
90155 **  'c'            NUMERIC
90156 **  'd'            INTEGER
90157 **  'e'            REAL
90158 **
90159 ** An extra 'd' is appended to the end of the string to cover the
90160 ** rowid that appears as the last column in every index.
90161 **
90162 ** Memory for the buffer containing the column index affinity string
90163 ** is managed along with the rest of the Index structure. It will be
90164 ** released when sqlite3DeleteIndex() is called.
90165 */
90166 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
90167   if( !pIdx->zColAff ){
90168     /* The first time a column affinity string for a particular index is
90169     ** required, it is allocated and populated here. It is then stored as
90170     ** a member of the Index structure for subsequent use.
90171     **
90172     ** The column affinity string will eventually be deleted by
90173     ** sqliteDeleteIndex() when the Index structure itself is cleaned
90174     ** up.
90175     */
90176     int n;
90177     Table *pTab = pIdx->pTable;
90178     sqlite3 *db = sqlite3VdbeDb(v);
90179     pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+2);
90180     if( !pIdx->zColAff ){
90181       db->mallocFailed = 1;
90182       return 0;
90183     }
90184     for(n=0; n<pIdx->nColumn; n++){
90185       pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
90186     }
90187     pIdx->zColAff[n++] = SQLITE_AFF_INTEGER;
90188     pIdx->zColAff[n] = 0;
90189   }
90190  
90191   return pIdx->zColAff;
90192 }
90193
90194 /*
90195 ** Set P4 of the most recently inserted opcode to a column affinity
90196 ** string for table pTab. A column affinity string has one character
90197 ** for each column indexed by the index, according to the affinity of the
90198 ** column:
90199 **
90200 **  Character      Column affinity
90201 **  ------------------------------
90202 **  'a'            TEXT
90203 **  'b'            NONE
90204 **  'c'            NUMERIC
90205 **  'd'            INTEGER
90206 **  'e'            REAL
90207 */
90208 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
90209   /* The first time a column affinity string for a particular table
90210   ** is required, it is allocated and populated here. It is then 
90211   ** stored as a member of the Table structure for subsequent use.
90212   **
90213   ** The column affinity string will eventually be deleted by
90214   ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
90215   */
90216   if( !pTab->zColAff ){
90217     char *zColAff;
90218     int i;
90219     sqlite3 *db = sqlite3VdbeDb(v);
90220
90221     zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
90222     if( !zColAff ){
90223       db->mallocFailed = 1;
90224       return;
90225     }
90226
90227     for(i=0; i<pTab->nCol; i++){
90228       zColAff[i] = pTab->aCol[i].affinity;
90229     }
90230     zColAff[pTab->nCol] = '\0';
90231
90232     pTab->zColAff = zColAff;
90233   }
90234
90235   sqlite3VdbeChangeP4(v, -1, pTab->zColAff, P4_TRANSIENT);
90236 }
90237
90238 /*
90239 ** Return non-zero if the table pTab in database iDb or any of its indices
90240 ** have been opened at any point in the VDBE program beginning at location
90241 ** iStartAddr throught the end of the program.  This is used to see if 
90242 ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can 
90243 ** run without using temporary table for the results of the SELECT. 
90244 */
90245 static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
90246   Vdbe *v = sqlite3GetVdbe(p);
90247   int i;
90248   int iEnd = sqlite3VdbeCurrentAddr(v);
90249 #ifndef SQLITE_OMIT_VIRTUALTABLE
90250   VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
90251 #endif
90252
90253   for(i=iStartAddr; i<iEnd; i++){
90254     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
90255     assert( pOp!=0 );
90256     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
90257       Index *pIndex;
90258       int tnum = pOp->p2;
90259       if( tnum==pTab->tnum ){
90260         return 1;
90261       }
90262       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
90263         if( tnum==pIndex->tnum ){
90264           return 1;
90265         }
90266       }
90267     }
90268 #ifndef SQLITE_OMIT_VIRTUALTABLE
90269     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
90270       assert( pOp->p4.pVtab!=0 );
90271       assert( pOp->p4type==P4_VTAB );
90272       return 1;
90273     }
90274 #endif
90275   }
90276   return 0;
90277 }
90278
90279 #ifndef SQLITE_OMIT_AUTOINCREMENT
90280 /*
90281 ** Locate or create an AutoincInfo structure associated with table pTab
90282 ** which is in database iDb.  Return the register number for the register
90283 ** that holds the maximum rowid.
90284 **
90285 ** There is at most one AutoincInfo structure per table even if the
90286 ** same table is autoincremented multiple times due to inserts within
90287 ** triggers.  A new AutoincInfo structure is created if this is the
90288 ** first use of table pTab.  On 2nd and subsequent uses, the original
90289 ** AutoincInfo structure is used.
90290 **
90291 ** Three memory locations are allocated:
90292 **
90293 **   (1)  Register to hold the name of the pTab table.
90294 **   (2)  Register to hold the maximum ROWID of pTab.
90295 **   (3)  Register to hold the rowid in sqlite_sequence of pTab
90296 **
90297 ** The 2nd register is the one that is returned.  That is all the
90298 ** insert routine needs to know about.
90299 */
90300 static int autoIncBegin(
90301   Parse *pParse,      /* Parsing context */
90302   int iDb,            /* Index of the database holding pTab */
90303   Table *pTab         /* The table we are writing to */
90304 ){
90305   int memId = 0;      /* Register holding maximum rowid */
90306   if( pTab->tabFlags & TF_Autoincrement ){
90307     Parse *pToplevel = sqlite3ParseToplevel(pParse);
90308     AutoincInfo *pInfo;
90309
90310     pInfo = pToplevel->pAinc;
90311     while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
90312     if( pInfo==0 ){
90313       pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
90314       if( pInfo==0 ) return 0;
90315       pInfo->pNext = pToplevel->pAinc;
90316       pToplevel->pAinc = pInfo;
90317       pInfo->pTab = pTab;
90318       pInfo->iDb = iDb;
90319       pToplevel->nMem++;                  /* Register to hold name of table */
90320       pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
90321       pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
90322     }
90323     memId = pInfo->regCtr;
90324   }
90325   return memId;
90326 }
90327
90328 /*
90329 ** This routine generates code that will initialize all of the
90330 ** register used by the autoincrement tracker.  
90331 */
90332 SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
90333   AutoincInfo *p;            /* Information about an AUTOINCREMENT */
90334   sqlite3 *db = pParse->db;  /* The database connection */
90335   Db *pDb;                   /* Database only autoinc table */
90336   int memId;                 /* Register holding max rowid */
90337   int addr;                  /* A VDBE address */
90338   Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
90339
90340   /* This routine is never called during trigger-generation.  It is
90341   ** only called from the top-level */
90342   assert( pParse->pTriggerTab==0 );
90343   assert( pParse==sqlite3ParseToplevel(pParse) );
90344
90345   assert( v );   /* We failed long ago if this is not so */
90346   for(p = pParse->pAinc; p; p = p->pNext){
90347     pDb = &db->aDb[p->iDb];
90348     memId = p->regCtr;
90349     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
90350     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
90351     sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);
90352     addr = sqlite3VdbeCurrentAddr(v);
90353     sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
90354     sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
90355     sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
90356     sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
90357     sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
90358     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
90359     sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
90360     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
90361     sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
90362     sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
90363     sqlite3VdbeAddOp0(v, OP_Close);
90364   }
90365 }
90366
90367 /*
90368 ** Update the maximum rowid for an autoincrement calculation.
90369 **
90370 ** This routine should be called when the top of the stack holds a
90371 ** new rowid that is about to be inserted.  If that new rowid is
90372 ** larger than the maximum rowid in the memId memory cell, then the
90373 ** memory cell is updated.  The stack is unchanged.
90374 */
90375 static void autoIncStep(Parse *pParse, int memId, int regRowid){
90376   if( memId>0 ){
90377     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
90378   }
90379 }
90380
90381 /*
90382 ** This routine generates the code needed to write autoincrement
90383 ** maximum rowid values back into the sqlite_sequence register.
90384 ** Every statement that might do an INSERT into an autoincrement
90385 ** table (either directly or through triggers) needs to call this
90386 ** routine just before the "exit" code.
90387 */
90388 SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
90389   AutoincInfo *p;
90390   Vdbe *v = pParse->pVdbe;
90391   sqlite3 *db = pParse->db;
90392
90393   assert( v );
90394   for(p = pParse->pAinc; p; p = p->pNext){
90395     Db *pDb = &db->aDb[p->iDb];
90396     int j1, j2, j3, j4, j5;
90397     int iRec;
90398     int memId = p->regCtr;
90399
90400     iRec = sqlite3GetTempReg(pParse);
90401     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
90402     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
90403     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
90404     j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
90405     j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
90406     j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
90407     sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
90408     sqlite3VdbeJumpHere(v, j2);
90409     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
90410     j5 = sqlite3VdbeAddOp0(v, OP_Goto);
90411     sqlite3VdbeJumpHere(v, j4);
90412     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
90413     sqlite3VdbeJumpHere(v, j1);
90414     sqlite3VdbeJumpHere(v, j5);
90415     sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
90416     sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
90417     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
90418     sqlite3VdbeAddOp0(v, OP_Close);
90419     sqlite3ReleaseTempReg(pParse, iRec);
90420   }
90421 }
90422 #else
90423 /*
90424 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
90425 ** above are all no-ops
90426 */
90427 # define autoIncBegin(A,B,C) (0)
90428 # define autoIncStep(A,B,C)
90429 #endif /* SQLITE_OMIT_AUTOINCREMENT */
90430
90431
90432 /*
90433 ** Generate code for a co-routine that will evaluate a subquery one
90434 ** row at a time.
90435 **
90436 ** The pSelect parameter is the subquery that the co-routine will evaluation.
90437 ** Information about the location of co-routine and the registers it will use
90438 ** is returned by filling in the pDest object.
90439 **
90440 ** Registers are allocated as follows:
90441 **
90442 **   pDest->iSDParm      The register holding the next entry-point of the
90443 **                       co-routine.  Run the co-routine to its next breakpoint
90444 **                       by calling "OP_Yield $X" where $X is pDest->iSDParm.
90445 **
90446 **   pDest->iSDParm+1    The register holding the "completed" flag for the
90447 **                       co-routine. This register is 0 if the previous Yield
90448 **                       generated a new result row, or 1 if the subquery
90449 **                       has completed.  If the Yield is called again
90450 **                       after this register becomes 1, then the VDBE will
90451 **                       halt with an SQLITE_INTERNAL error.
90452 **
90453 **   pDest->iSdst        First result register.
90454 **
90455 **   pDest->nSdst        Number of result registers.
90456 **
90457 ** This routine handles all of the register allocation and fills in the
90458 ** pDest structure appropriately.
90459 **
90460 ** Here is a schematic of the generated code assuming that X is the 
90461 ** co-routine entry-point register reg[pDest->iSDParm], that EOF is the
90462 ** completed flag reg[pDest->iSDParm+1], and R and S are the range of
90463 ** registers that hold the result set, reg[pDest->iSdst] through
90464 ** reg[pDest->iSdst+pDest->nSdst-1]:
90465 **
90466 **         X <- A
90467 **         EOF <- 0
90468 **         goto B
90469 **      A: setup for the SELECT
90470 **         loop rows in the SELECT
90471 **           load results into registers R..S
90472 **           yield X
90473 **         end loop
90474 **         cleanup after the SELECT
90475 **         EOF <- 1
90476 **         yield X
90477 **         halt-error
90478 **      B:
90479 **
90480 ** To use this subroutine, the caller generates code as follows:
90481 **
90482 **         [ Co-routine generated by this subroutine, shown above ]
90483 **      S: yield X
90484 **         if EOF goto E
90485 **         if skip this row, goto C
90486 **         if terminate loop, goto E
90487 **         deal with this row
90488 **      C: goto S
90489 **      E:
90490 */
90491 SQLITE_PRIVATE int sqlite3CodeCoroutine(Parse *pParse, Select *pSelect, SelectDest *pDest){
90492   int regYield;       /* Register holding co-routine entry-point */
90493   int regEof;         /* Register holding co-routine completion flag */
90494   int addrTop;        /* Top of the co-routine */
90495   int j1;             /* Jump instruction */
90496   int rc;             /* Result code */
90497   Vdbe *v;            /* VDBE under construction */
90498
90499   regYield = ++pParse->nMem;
90500   regEof = ++pParse->nMem;
90501   v = sqlite3GetVdbe(pParse);
90502   addrTop = sqlite3VdbeCurrentAddr(v);
90503   sqlite3VdbeAddOp2(v, OP_Integer, addrTop+2, regYield); /* X <- A */
90504   VdbeComment((v, "Co-routine entry point"));
90505   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);           /* EOF <- 0 */
90506   VdbeComment((v, "Co-routine completion flag"));
90507   sqlite3SelectDestInit(pDest, SRT_Coroutine, regYield);
90508   j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
90509   rc = sqlite3Select(pParse, pSelect, pDest);
90510   assert( pParse->nErr==0 || rc );
90511   if( pParse->db->mallocFailed && rc==SQLITE_OK ) rc = SQLITE_NOMEM;
90512   if( rc ) return rc;
90513   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);            /* EOF <- 1 */
90514   sqlite3VdbeAddOp1(v, OP_Yield, regYield);   /* yield X */
90515   sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
90516   VdbeComment((v, "End of coroutine"));
90517   sqlite3VdbeJumpHere(v, j1);                             /* label B: */
90518   return rc;
90519 }
90520
90521
90522
90523 /* Forward declaration */
90524 static int xferOptimization(
90525   Parse *pParse,        /* Parser context */
90526   Table *pDest,         /* The table we are inserting into */
90527   Select *pSelect,      /* A SELECT statement to use as the data source */
90528   int onError,          /* How to handle constraint errors */
90529   int iDbDest           /* The database of pDest */
90530 );
90531
90532 /*
90533 ** This routine is call to handle SQL of the following forms:
90534 **
90535 **    insert into TABLE (IDLIST) values(EXPRLIST)
90536 **    insert into TABLE (IDLIST) select
90537 **
90538 ** The IDLIST following the table name is always optional.  If omitted,
90539 ** then a list of all columns for the table is substituted.  The IDLIST
90540 ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
90541 **
90542 ** The pList parameter holds EXPRLIST in the first form of the INSERT
90543 ** statement above, and pSelect is NULL.  For the second form, pList is
90544 ** NULL and pSelect is a pointer to the select statement used to generate
90545 ** data for the insert.
90546 **
90547 ** The code generated follows one of four templates.  For a simple
90548 ** select with data coming from a VALUES clause, the code executes
90549 ** once straight down through.  Pseudo-code follows (we call this
90550 ** the "1st template"):
90551 **
90552 **         open write cursor to <table> and its indices
90553 **         puts VALUES clause expressions onto the stack
90554 **         write the resulting record into <table>
90555 **         cleanup
90556 **
90557 ** The three remaining templates assume the statement is of the form
90558 **
90559 **   INSERT INTO <table> SELECT ...
90560 **
90561 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
90562 ** in other words if the SELECT pulls all columns from a single table
90563 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
90564 ** if <table2> and <table1> are distinct tables but have identical
90565 ** schemas, including all the same indices, then a special optimization
90566 ** is invoked that copies raw records from <table2> over to <table1>.
90567 ** See the xferOptimization() function for the implementation of this
90568 ** template.  This is the 2nd template.
90569 **
90570 **         open a write cursor to <table>
90571 **         open read cursor on <table2>
90572 **         transfer all records in <table2> over to <table>
90573 **         close cursors
90574 **         foreach index on <table>
90575 **           open a write cursor on the <table> index
90576 **           open a read cursor on the corresponding <table2> index
90577 **           transfer all records from the read to the write cursors
90578 **           close cursors
90579 **         end foreach
90580 **
90581 ** The 3rd template is for when the second template does not apply
90582 ** and the SELECT clause does not read from <table> at any time.
90583 ** The generated code follows this template:
90584 **
90585 **         EOF <- 0
90586 **         X <- A
90587 **         goto B
90588 **      A: setup for the SELECT
90589 **         loop over the rows in the SELECT
90590 **           load values into registers R..R+n
90591 **           yield X
90592 **         end loop
90593 **         cleanup after the SELECT
90594 **         EOF <- 1
90595 **         yield X
90596 **         goto A
90597 **      B: open write cursor to <table> and its indices
90598 **      C: yield X
90599 **         if EOF goto D
90600 **         insert the select result into <table> from R..R+n
90601 **         goto C
90602 **      D: cleanup
90603 **
90604 ** The 4th template is used if the insert statement takes its
90605 ** values from a SELECT but the data is being inserted into a table
90606 ** that is also read as part of the SELECT.  In the third form,
90607 ** we have to use a intermediate table to store the results of
90608 ** the select.  The template is like this:
90609 **
90610 **         EOF <- 0
90611 **         X <- A
90612 **         goto B
90613 **      A: setup for the SELECT
90614 **         loop over the tables in the SELECT
90615 **           load value into register R..R+n
90616 **           yield X
90617 **         end loop
90618 **         cleanup after the SELECT
90619 **         EOF <- 1
90620 **         yield X
90621 **         halt-error
90622 **      B: open temp table
90623 **      L: yield X
90624 **         if EOF goto M
90625 **         insert row from R..R+n into temp table
90626 **         goto L
90627 **      M: open write cursor to <table> and its indices
90628 **         rewind temp table
90629 **      C: loop over rows of intermediate table
90630 **           transfer values form intermediate table into <table>
90631 **         end loop
90632 **      D: cleanup
90633 */
90634 SQLITE_PRIVATE void sqlite3Insert(
90635   Parse *pParse,        /* Parser context */
90636   SrcList *pTabList,    /* Name of table into which we are inserting */
90637   ExprList *pList,      /* List of values to be inserted */
90638   Select *pSelect,      /* A SELECT statement to use as the data source */
90639   IdList *pColumn,      /* Column names corresponding to IDLIST. */
90640   int onError           /* How to handle constraint errors */
90641 ){
90642   sqlite3 *db;          /* The main database structure */
90643   Table *pTab;          /* The table to insert into.  aka TABLE */
90644   char *zTab;           /* Name of the table into which we are inserting */
90645   const char *zDb;      /* Name of the database holding this table */
90646   int i, j, idx;        /* Loop counters */
90647   Vdbe *v;              /* Generate code into this virtual machine */
90648   Index *pIdx;          /* For looping over indices of the table */
90649   int nColumn;          /* Number of columns in the data */
90650   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
90651   int baseCur = 0;      /* VDBE Cursor number for pTab */
90652   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
90653   int endOfLoop;        /* Label for the end of the insertion loop */
90654   int useTempTable = 0; /* Store SELECT results in intermediate table */
90655   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
90656   int addrInsTop = 0;   /* Jump to label "D" */
90657   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
90658   int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
90659   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
90660   int iDb;              /* Index of database holding TABLE */
90661   Db *pDb;              /* The database containing table being inserted into */
90662   int appendFlag = 0;   /* True if the insert is likely to be an append */
90663
90664   /* Register allocations */
90665   int regFromSelect = 0;/* Base register for data coming from SELECT */
90666   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
90667   int regRowCount = 0;  /* Memory cell used for the row counter */
90668   int regIns;           /* Block of regs holding rowid+data being inserted */
90669   int regRowid;         /* registers holding insert rowid */
90670   int regData;          /* register holding first column to insert */
90671   int regEof = 0;       /* Register recording end of SELECT data */
90672   int *aRegIdx = 0;     /* One register allocated to each index */
90673
90674 #ifndef SQLITE_OMIT_TRIGGER
90675   int isView;                 /* True if attempting to insert into a view */
90676   Trigger *pTrigger;          /* List of triggers on pTab, if required */
90677   int tmask;                  /* Mask of trigger times */
90678 #endif
90679
90680   db = pParse->db;
90681   memset(&dest, 0, sizeof(dest));
90682   if( pParse->nErr || db->mallocFailed ){
90683     goto insert_cleanup;
90684   }
90685
90686   /* Locate the table into which we will be inserting new information.
90687   */
90688   assert( pTabList->nSrc==1 );
90689   zTab = pTabList->a[0].zName;
90690   if( NEVER(zTab==0) ) goto insert_cleanup;
90691   pTab = sqlite3SrcListLookup(pParse, pTabList);
90692   if( pTab==0 ){
90693     goto insert_cleanup;
90694   }
90695   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
90696   assert( iDb<db->nDb );
90697   pDb = &db->aDb[iDb];
90698   zDb = pDb->zName;
90699   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
90700     goto insert_cleanup;
90701   }
90702
90703   /* Figure out if we have any triggers and if the table being
90704   ** inserted into is a view
90705   */
90706 #ifndef SQLITE_OMIT_TRIGGER
90707   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
90708   isView = pTab->pSelect!=0;
90709 #else
90710 # define pTrigger 0
90711 # define tmask 0
90712 # define isView 0
90713 #endif
90714 #ifdef SQLITE_OMIT_VIEW
90715 # undef isView
90716 # define isView 0
90717 #endif
90718   assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
90719
90720   /* If pTab is really a view, make sure it has been initialized.
90721   ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual 
90722   ** module table).
90723   */
90724   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
90725     goto insert_cleanup;
90726   }
90727
90728   /* Ensure that:
90729   *  (a) the table is not read-only, 
90730   *  (b) that if it is a view then ON INSERT triggers exist
90731   */
90732   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
90733     goto insert_cleanup;
90734   }
90735
90736   /* Allocate a VDBE
90737   */
90738   v = sqlite3GetVdbe(pParse);
90739   if( v==0 ) goto insert_cleanup;
90740   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
90741   sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
90742
90743 #ifndef SQLITE_OMIT_XFER_OPT
90744   /* If the statement is of the form
90745   **
90746   **       INSERT INTO <table1> SELECT * FROM <table2>;
90747   **
90748   ** Then special optimizations can be applied that make the transfer
90749   ** very fast and which reduce fragmentation of indices.
90750   **
90751   ** This is the 2nd template.
90752   */
90753   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
90754     assert( !pTrigger );
90755     assert( pList==0 );
90756     goto insert_end;
90757   }
90758 #endif /* SQLITE_OMIT_XFER_OPT */
90759
90760   /* If this is an AUTOINCREMENT table, look up the sequence number in the
90761   ** sqlite_sequence table and store it in memory cell regAutoinc.
90762   */
90763   regAutoinc = autoIncBegin(pParse, iDb, pTab);
90764
90765   /* Figure out how many columns of data are supplied.  If the data
90766   ** is coming from a SELECT statement, then generate a co-routine that
90767   ** produces a single row of the SELECT on each invocation.  The
90768   ** co-routine is the common header to the 3rd and 4th templates.
90769   */
90770   if( pSelect ){
90771     /* Data is coming from a SELECT.  Generate a co-routine to run that
90772     ** SELECT. */
90773     int rc = sqlite3CodeCoroutine(pParse, pSelect, &dest);
90774     if( rc ) goto insert_cleanup;
90775
90776     regEof = dest.iSDParm + 1;
90777     regFromSelect = dest.iSdst;
90778     assert( pSelect->pEList );
90779     nColumn = pSelect->pEList->nExpr;
90780     assert( dest.nSdst==nColumn );
90781
90782     /* Set useTempTable to TRUE if the result of the SELECT statement
90783     ** should be written into a temporary table (template 4).  Set to
90784     ** FALSE if each* row of the SELECT can be written directly into
90785     ** the destination table (template 3).
90786     **
90787     ** A temp table must be used if the table being updated is also one
90788     ** of the tables being read by the SELECT statement.  Also use a 
90789     ** temp table in the case of row triggers.
90790     */
90791     if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
90792       useTempTable = 1;
90793     }
90794
90795     if( useTempTable ){
90796       /* Invoke the coroutine to extract information from the SELECT
90797       ** and add it to a transient table srcTab.  The code generated
90798       ** here is from the 4th template:
90799       **
90800       **      B: open temp table
90801       **      L: yield X
90802       **         if EOF goto M
90803       **         insert row from R..R+n into temp table
90804       **         goto L
90805       **      M: ...
90806       */
90807       int regRec;          /* Register to hold packed record */
90808       int regTempRowid;    /* Register to hold temp table ROWID */
90809       int addrTop;         /* Label "L" */
90810       int addrIf;          /* Address of jump to M */
90811
90812       srcTab = pParse->nTab++;
90813       regRec = sqlite3GetTempReg(pParse);
90814       regTempRowid = sqlite3GetTempReg(pParse);
90815       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
90816       addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
90817       addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
90818       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
90819       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
90820       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
90821       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
90822       sqlite3VdbeJumpHere(v, addrIf);
90823       sqlite3ReleaseTempReg(pParse, regRec);
90824       sqlite3ReleaseTempReg(pParse, regTempRowid);
90825     }
90826   }else{
90827     /* This is the case if the data for the INSERT is coming from a VALUES
90828     ** clause
90829     */
90830     NameContext sNC;
90831     memset(&sNC, 0, sizeof(sNC));
90832     sNC.pParse = pParse;
90833     srcTab = -1;
90834     assert( useTempTable==0 );
90835     nColumn = pList ? pList->nExpr : 0;
90836     for(i=0; i<nColumn; i++){
90837       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
90838         goto insert_cleanup;
90839       }
90840     }
90841   }
90842
90843   /* Make sure the number of columns in the source data matches the number
90844   ** of columns to be inserted into the table.
90845   */
90846   if( IsVirtual(pTab) ){
90847     for(i=0; i<pTab->nCol; i++){
90848       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
90849     }
90850   }
90851   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
90852     sqlite3ErrorMsg(pParse, 
90853        "table %S has %d columns but %d values were supplied",
90854        pTabList, 0, pTab->nCol-nHidden, nColumn);
90855     goto insert_cleanup;
90856   }
90857   if( pColumn!=0 && nColumn!=pColumn->nId ){
90858     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
90859     goto insert_cleanup;
90860   }
90861
90862   /* If the INSERT statement included an IDLIST term, then make sure
90863   ** all elements of the IDLIST really are columns of the table and 
90864   ** remember the column indices.
90865   **
90866   ** If the table has an INTEGER PRIMARY KEY column and that column
90867   ** is named in the IDLIST, then record in the keyColumn variable
90868   ** the index into IDLIST of the primary key column.  keyColumn is
90869   ** the index of the primary key as it appears in IDLIST, not as
90870   ** is appears in the original table.  (The index of the primary
90871   ** key in the original table is pTab->iPKey.)
90872   */
90873   if( pColumn ){
90874     for(i=0; i<pColumn->nId; i++){
90875       pColumn->a[i].idx = -1;
90876     }
90877     for(i=0; i<pColumn->nId; i++){
90878       for(j=0; j<pTab->nCol; j++){
90879         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
90880           pColumn->a[i].idx = j;
90881           if( j==pTab->iPKey ){
90882             keyColumn = i;
90883           }
90884           break;
90885         }
90886       }
90887       if( j>=pTab->nCol ){
90888         if( sqlite3IsRowid(pColumn->a[i].zName) ){
90889           keyColumn = i;
90890         }else{
90891           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
90892               pTabList, 0, pColumn->a[i].zName);
90893           pParse->checkSchema = 1;
90894           goto insert_cleanup;
90895         }
90896       }
90897     }
90898   }
90899
90900   /* If there is no IDLIST term but the table has an integer primary
90901   ** key, the set the keyColumn variable to the primary key column index
90902   ** in the original table definition.
90903   */
90904   if( pColumn==0 && nColumn>0 ){
90905     keyColumn = pTab->iPKey;
90906   }
90907     
90908   /* Initialize the count of rows to be inserted
90909   */
90910   if( db->flags & SQLITE_CountRows ){
90911     regRowCount = ++pParse->nMem;
90912     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
90913   }
90914
90915   /* If this is not a view, open the table and and all indices */
90916   if( !isView ){
90917     int nIdx;
90918
90919     baseCur = pParse->nTab;
90920     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
90921     aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
90922     if( aRegIdx==0 ){
90923       goto insert_cleanup;
90924     }
90925     for(i=0; i<nIdx; i++){
90926       aRegIdx[i] = ++pParse->nMem;
90927     }
90928   }
90929
90930   /* This is the top of the main insertion loop */
90931   if( useTempTable ){
90932     /* This block codes the top of loop only.  The complete loop is the
90933     ** following pseudocode (template 4):
90934     **
90935     **         rewind temp table
90936     **      C: loop over rows of intermediate table
90937     **           transfer values form intermediate table into <table>
90938     **         end loop
90939     **      D: ...
90940     */
90941     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
90942     addrCont = sqlite3VdbeCurrentAddr(v);
90943   }else if( pSelect ){
90944     /* This block codes the top of loop only.  The complete loop is the
90945     ** following pseudocode (template 3):
90946     **
90947     **      C: yield X
90948     **         if EOF goto D
90949     **         insert the select result into <table> from R..R+n
90950     **         goto C
90951     **      D: ...
90952     */
90953     addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
90954     addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
90955   }
90956
90957   /* Allocate registers for holding the rowid of the new row,
90958   ** the content of the new row, and the assemblied row record.
90959   */
90960   regRowid = regIns = pParse->nMem+1;
90961   pParse->nMem += pTab->nCol + 1;
90962   if( IsVirtual(pTab) ){
90963     regRowid++;
90964     pParse->nMem++;
90965   }
90966   regData = regRowid+1;
90967
90968   /* Run the BEFORE and INSTEAD OF triggers, if there are any
90969   */
90970   endOfLoop = sqlite3VdbeMakeLabel(v);
90971   if( tmask & TRIGGER_BEFORE ){
90972     int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
90973
90974     /* build the NEW.* reference row.  Note that if there is an INTEGER
90975     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
90976     ** translated into a unique ID for the row.  But on a BEFORE trigger,
90977     ** we do not know what the unique ID will be (because the insert has
90978     ** not happened yet) so we substitute a rowid of -1
90979     */
90980     if( keyColumn<0 ){
90981       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
90982     }else{
90983       int j1;
90984       if( useTempTable ){
90985         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
90986       }else{
90987         assert( pSelect==0 );  /* Otherwise useTempTable is true */
90988         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
90989       }
90990       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
90991       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
90992       sqlite3VdbeJumpHere(v, j1);
90993       sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
90994     }
90995
90996     /* Cannot have triggers on a virtual table. If it were possible,
90997     ** this block would have to account for hidden column.
90998     */
90999     assert( !IsVirtual(pTab) );
91000
91001     /* Create the new column data
91002     */
91003     for(i=0; i<pTab->nCol; i++){
91004       if( pColumn==0 ){
91005         j = i;
91006       }else{
91007         for(j=0; j<pColumn->nId; j++){
91008           if( pColumn->a[j].idx==i ) break;
91009         }
91010       }
91011       if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
91012         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
91013       }else if( useTempTable ){
91014         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1); 
91015       }else{
91016         assert( pSelect==0 ); /* Otherwise useTempTable is true */
91017         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
91018       }
91019     }
91020
91021     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
91022     ** do not attempt any conversions before assembling the record.
91023     ** If this is a real table, attempt conversions as required by the
91024     ** table column affinities.
91025     */
91026     if( !isView ){
91027       sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
91028       sqlite3TableAffinityStr(v, pTab);
91029     }
91030
91031     /* Fire BEFORE or INSTEAD OF triggers */
91032     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE, 
91033         pTab, regCols-pTab->nCol-1, onError, endOfLoop);
91034
91035     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
91036   }
91037
91038   /* Push the record number for the new entry onto the stack.  The
91039   ** record number is a randomly generate integer created by NewRowid
91040   ** except when the table has an INTEGER PRIMARY KEY column, in which
91041   ** case the record number is the same as that column. 
91042   */
91043   if( !isView ){
91044     if( IsVirtual(pTab) ){
91045       /* The row that the VUpdate opcode will delete: none */
91046       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
91047     }
91048     if( keyColumn>=0 ){
91049       if( useTempTable ){
91050         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
91051       }else if( pSelect ){
91052         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
91053       }else{
91054         VdbeOp *pOp;
91055         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
91056         pOp = sqlite3VdbeGetOp(v, -1);
91057         if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
91058           appendFlag = 1;
91059           pOp->opcode = OP_NewRowid;
91060           pOp->p1 = baseCur;
91061           pOp->p2 = regRowid;
91062           pOp->p3 = regAutoinc;
91063         }
91064       }
91065       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
91066       ** to generate a unique primary key value.
91067       */
91068       if( !appendFlag ){
91069         int j1;
91070         if( !IsVirtual(pTab) ){
91071           j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
91072           sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
91073           sqlite3VdbeJumpHere(v, j1);
91074         }else{
91075           j1 = sqlite3VdbeCurrentAddr(v);
91076           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
91077         }
91078         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
91079       }
91080     }else if( IsVirtual(pTab) ){
91081       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
91082     }else{
91083       sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
91084       appendFlag = 1;
91085     }
91086     autoIncStep(pParse, regAutoinc, regRowid);
91087
91088     /* Push onto the stack, data for all columns of the new entry, beginning
91089     ** with the first column.
91090     */
91091     nHidden = 0;
91092     for(i=0; i<pTab->nCol; i++){
91093       int iRegStore = regRowid+1+i;
91094       if( i==pTab->iPKey ){
91095         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
91096         ** Whenever this column is read, the record number will be substituted
91097         ** in its place.  So will fill this column with a NULL to avoid
91098         ** taking up data space with information that will never be used. */
91099         sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
91100         continue;
91101       }
91102       if( pColumn==0 ){
91103         if( IsHiddenColumn(&pTab->aCol[i]) ){
91104           assert( IsVirtual(pTab) );
91105           j = -1;
91106           nHidden++;
91107         }else{
91108           j = i - nHidden;
91109         }
91110       }else{
91111         for(j=0; j<pColumn->nId; j++){
91112           if( pColumn->a[j].idx==i ) break;
91113         }
91114       }
91115       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
91116         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
91117       }else if( useTempTable ){
91118         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); 
91119       }else if( pSelect ){
91120         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
91121       }else{
91122         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
91123       }
91124     }
91125
91126     /* Generate code to check constraints and generate index keys and
91127     ** do the insertion.
91128     */
91129 #ifndef SQLITE_OMIT_VIRTUALTABLE
91130     if( IsVirtual(pTab) ){
91131       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
91132       sqlite3VtabMakeWritable(pParse, pTab);
91133       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
91134       sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
91135       sqlite3MayAbort(pParse);
91136     }else
91137 #endif
91138     {
91139       int isReplace;    /* Set to true if constraints may cause a replace */
91140       sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
91141           keyColumn>=0, 0, onError, endOfLoop, &isReplace
91142       );
91143       sqlite3FkCheck(pParse, pTab, 0, regIns);
91144       sqlite3CompleteInsertion(
91145           pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
91146       );
91147     }
91148   }
91149
91150   /* Update the count of rows that are inserted
91151   */
91152   if( (db->flags & SQLITE_CountRows)!=0 ){
91153     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
91154   }
91155
91156   if( pTrigger ){
91157     /* Code AFTER triggers */
91158     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER, 
91159         pTab, regData-2-pTab->nCol, onError, endOfLoop);
91160   }
91161
91162   /* The bottom of the main insertion loop, if the data source
91163   ** is a SELECT statement.
91164   */
91165   sqlite3VdbeResolveLabel(v, endOfLoop);
91166   if( useTempTable ){
91167     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
91168     sqlite3VdbeJumpHere(v, addrInsTop);
91169     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
91170   }else if( pSelect ){
91171     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
91172     sqlite3VdbeJumpHere(v, addrInsTop);
91173   }
91174
91175   if( !IsVirtual(pTab) && !isView ){
91176     /* Close all tables opened */
91177     sqlite3VdbeAddOp1(v, OP_Close, baseCur);
91178     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
91179       sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
91180     }
91181   }
91182
91183 insert_end:
91184   /* Update the sqlite_sequence table by storing the content of the
91185   ** maximum rowid counter values recorded while inserting into
91186   ** autoincrement tables.
91187   */
91188   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
91189     sqlite3AutoincrementEnd(pParse);
91190   }
91191
91192   /*
91193   ** Return the number of rows inserted. If this routine is 
91194   ** generating code because of a call to sqlite3NestedParse(), do not
91195   ** invoke the callback function.
91196   */
91197   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
91198     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
91199     sqlite3VdbeSetNumCols(v, 1);
91200     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
91201   }
91202
91203 insert_cleanup:
91204   sqlite3SrcListDelete(db, pTabList);
91205   sqlite3ExprListDelete(db, pList);
91206   sqlite3SelectDelete(db, pSelect);
91207   sqlite3IdListDelete(db, pColumn);
91208   sqlite3DbFree(db, aRegIdx);
91209 }
91210
91211 /* Make sure "isView" and other macros defined above are undefined. Otherwise
91212 ** thely may interfere with compilation of other functions in this file
91213 ** (or in another file, if this file becomes part of the amalgamation).  */
91214 #ifdef isView
91215  #undef isView
91216 #endif
91217 #ifdef pTrigger
91218  #undef pTrigger
91219 #endif
91220 #ifdef tmask
91221  #undef tmask
91222 #endif
91223
91224
91225 /*
91226 ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
91227 **
91228 ** The input is a range of consecutive registers as follows:
91229 **
91230 **    1.  The rowid of the row after the update.
91231 **
91232 **    2.  The data in the first column of the entry after the update.
91233 **
91234 **    i.  Data from middle columns...
91235 **
91236 **    N.  The data in the last column of the entry after the update.
91237 **
91238 ** The regRowid parameter is the index of the register containing (1).
91239 **
91240 ** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
91241 ** the address of a register containing the rowid before the update takes
91242 ** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
91243 ** is false, indicating an INSERT statement, then a non-zero rowidChng 
91244 ** indicates that the rowid was explicitly specified as part of the
91245 ** INSERT statement. If rowidChng is false, it means that  the rowid is
91246 ** computed automatically in an insert or that the rowid value is not 
91247 ** modified by an update.
91248 **
91249 ** The code generated by this routine store new index entries into
91250 ** registers identified by aRegIdx[].  No index entry is created for
91251 ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
91252 ** the same as the order of indices on the linked list of indices
91253 ** attached to the table.
91254 **
91255 ** This routine also generates code to check constraints.  NOT NULL,
91256 ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
91257 ** then the appropriate action is performed.  There are five possible
91258 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
91259 **
91260 **  Constraint type  Action       What Happens
91261 **  ---------------  ----------   ----------------------------------------
91262 **  any              ROLLBACK     The current transaction is rolled back and
91263 **                                sqlite3_exec() returns immediately with a
91264 **                                return code of SQLITE_CONSTRAINT.
91265 **
91266 **  any              ABORT        Back out changes from the current command
91267 **                                only (do not do a complete rollback) then
91268 **                                cause sqlite3_exec() to return immediately
91269 **                                with SQLITE_CONSTRAINT.
91270 **
91271 **  any              FAIL         Sqlite3_exec() returns immediately with a
91272 **                                return code of SQLITE_CONSTRAINT.  The
91273 **                                transaction is not rolled back and any
91274 **                                prior changes are retained.
91275 **
91276 **  any              IGNORE       The record number and data is popped from
91277 **                                the stack and there is an immediate jump
91278 **                                to label ignoreDest.
91279 **
91280 **  NOT NULL         REPLACE      The NULL value is replace by the default
91281 **                                value for that column.  If the default value
91282 **                                is NULL, the action is the same as ABORT.
91283 **
91284 **  UNIQUE           REPLACE      The other row that conflicts with the row
91285 **                                being inserted is removed.
91286 **
91287 **  CHECK            REPLACE      Illegal.  The results in an exception.
91288 **
91289 ** Which action to take is determined by the overrideError parameter.
91290 ** Or if overrideError==OE_Default, then the pParse->onError parameter
91291 ** is used.  Or if pParse->onError==OE_Default then the onError value
91292 ** for the constraint is used.
91293 **
91294 ** The calling routine must open a read/write cursor for pTab with
91295 ** cursor number "baseCur".  All indices of pTab must also have open
91296 ** read/write cursors with cursor number baseCur+i for the i-th cursor.
91297 ** Except, if there is no possibility of a REPLACE action then
91298 ** cursors do not need to be open for indices where aRegIdx[i]==0.
91299 */
91300 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
91301   Parse *pParse,      /* The parser context */
91302   Table *pTab,        /* the table into which we are inserting */
91303   int baseCur,        /* Index of a read/write cursor pointing at pTab */
91304   int regRowid,       /* Index of the range of input registers */
91305   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
91306   int rowidChng,      /* True if the rowid might collide with existing entry */
91307   int isUpdate,       /* True for UPDATE, False for INSERT */
91308   int overrideError,  /* Override onError to this if not OE_Default */
91309   int ignoreDest,     /* Jump to this label on an OE_Ignore resolution */
91310   int *pbMayReplace   /* OUT: Set to true if constraint may cause a replace */
91311 ){
91312   int i;              /* loop counter */
91313   Vdbe *v;            /* VDBE under constrution */
91314   int nCol;           /* Number of columns */
91315   int onError;        /* Conflict resolution strategy */
91316   int j1;             /* Addresss of jump instruction */
91317   int j2 = 0, j3;     /* Addresses of jump instructions */
91318   int regData;        /* Register containing first data column */
91319   int iCur;           /* Table cursor number */
91320   Index *pIdx;         /* Pointer to one of the indices */
91321   sqlite3 *db;         /* Database connection */
91322   int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
91323   int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
91324
91325   db = pParse->db;
91326   v = sqlite3GetVdbe(pParse);
91327   assert( v!=0 );
91328   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
91329   nCol = pTab->nCol;
91330   regData = regRowid + 1;
91331
91332   /* Test all NOT NULL constraints.
91333   */
91334   for(i=0; i<nCol; i++){
91335     if( i==pTab->iPKey ){
91336       continue;
91337     }
91338     onError = pTab->aCol[i].notNull;
91339     if( onError==OE_None ) continue;
91340     if( overrideError!=OE_Default ){
91341       onError = overrideError;
91342     }else if( onError==OE_Default ){
91343       onError = OE_Abort;
91344     }
91345     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
91346       onError = OE_Abort;
91347     }
91348     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
91349         || onError==OE_Ignore || onError==OE_Replace );
91350     switch( onError ){
91351       case OE_Abort:
91352         sqlite3MayAbort(pParse);
91353       case OE_Rollback:
91354       case OE_Fail: {
91355         char *zMsg;
91356         sqlite3VdbeAddOp3(v, OP_HaltIfNull,
91357                           SQLITE_CONSTRAINT_NOTNULL, onError, regData+i);
91358         zMsg = sqlite3MPrintf(db, "%s.%s may not be NULL",
91359                               pTab->zName, pTab->aCol[i].zName);
91360         sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
91361         break;
91362       }
91363       case OE_Ignore: {
91364         sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
91365         break;
91366       }
91367       default: {
91368         assert( onError==OE_Replace );
91369         j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
91370         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
91371         sqlite3VdbeJumpHere(v, j1);
91372         break;
91373       }
91374     }
91375   }
91376
91377   /* Test all CHECK constraints
91378   */
91379 #ifndef SQLITE_OMIT_CHECK
91380   if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
91381     ExprList *pCheck = pTab->pCheck;
91382     pParse->ckBase = regData;
91383     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
91384     for(i=0; i<pCheck->nExpr; i++){
91385       int allOk = sqlite3VdbeMakeLabel(v);
91386       sqlite3ExprIfTrue(pParse, pCheck->a[i].pExpr, allOk, SQLITE_JUMPIFNULL);
91387       if( onError==OE_Ignore ){
91388         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
91389       }else{
91390         char *zConsName = pCheck->a[i].zName;
91391         if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
91392         if( zConsName ){
91393           zConsName = sqlite3MPrintf(db, "constraint %s failed", zConsName);
91394         }else{
91395           zConsName = 0;
91396         }
91397         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
91398                               onError, zConsName, P4_DYNAMIC);
91399       }
91400       sqlite3VdbeResolveLabel(v, allOk);
91401     }
91402   }
91403 #endif /* !defined(SQLITE_OMIT_CHECK) */
91404
91405   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
91406   ** of the new record does not previously exist.  Except, if this
91407   ** is an UPDATE and the primary key is not changing, that is OK.
91408   */
91409   if( rowidChng ){
91410     onError = pTab->keyConf;
91411     if( overrideError!=OE_Default ){
91412       onError = overrideError;
91413     }else if( onError==OE_Default ){
91414       onError = OE_Abort;
91415     }
91416     
91417     if( isUpdate ){
91418       j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
91419     }
91420     j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
91421     switch( onError ){
91422       default: {
91423         onError = OE_Abort;
91424         /* Fall thru into the next case */
91425       }
91426       case OE_Rollback:
91427       case OE_Abort:
91428       case OE_Fail: {
91429         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_PRIMARYKEY,
91430            onError, "PRIMARY KEY must be unique", P4_STATIC);
91431         break;
91432       }
91433       case OE_Replace: {
91434         /* If there are DELETE triggers on this table and the
91435         ** recursive-triggers flag is set, call GenerateRowDelete() to
91436         ** remove the conflicting row from the table. This will fire
91437         ** the triggers and remove both the table and index b-tree entries.
91438         **
91439         ** Otherwise, if there are no triggers or the recursive-triggers
91440         ** flag is not set, but the table has one or more indexes, call 
91441         ** GenerateRowIndexDelete(). This removes the index b-tree entries 
91442         ** only. The table b-tree entry will be replaced by the new entry 
91443         ** when it is inserted.  
91444         **
91445         ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
91446         ** also invoke MultiWrite() to indicate that this VDBE may require
91447         ** statement rollback (if the statement is aborted after the delete
91448         ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
91449         ** but being more selective here allows statements like:
91450         **
91451         **   REPLACE INTO t(rowid) VALUES($newrowid)
91452         **
91453         ** to run without a statement journal if there are no indexes on the
91454         ** table.
91455         */
91456         Trigger *pTrigger = 0;
91457         if( db->flags&SQLITE_RecTriggers ){
91458           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
91459         }
91460         if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
91461           sqlite3MultiWrite(pParse);
91462           sqlite3GenerateRowDelete(
91463               pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
91464           );
91465         }else if( pTab->pIndex ){
91466           sqlite3MultiWrite(pParse);
91467           sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
91468         }
91469         seenReplace = 1;
91470         break;
91471       }
91472       case OE_Ignore: {
91473         assert( seenReplace==0 );
91474         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
91475         break;
91476       }
91477     }
91478     sqlite3VdbeJumpHere(v, j3);
91479     if( isUpdate ){
91480       sqlite3VdbeJumpHere(v, j2);
91481     }
91482   }
91483
91484   /* Test all UNIQUE constraints by creating entries for each UNIQUE
91485   ** index and making sure that duplicate entries do not already exist.
91486   ** Add the new records to the indices as we go.
91487   */
91488   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
91489     int regIdx;
91490     int regR;
91491
91492     if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */
91493
91494     /* Create a key for accessing the index entry */
91495     regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
91496     for(i=0; i<pIdx->nColumn; i++){
91497       int idx = pIdx->aiColumn[i];
91498       if( idx==pTab->iPKey ){
91499         sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
91500       }else{
91501         sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
91502       }
91503     }
91504     sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
91505     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
91506     sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
91507     sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
91508
91509     /* Find out what action to take in case there is an indexing conflict */
91510     onError = pIdx->onError;
91511     if( onError==OE_None ){ 
91512       sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
91513       continue;  /* pIdx is not a UNIQUE index */
91514     }
91515     if( overrideError!=OE_Default ){
91516       onError = overrideError;
91517     }else if( onError==OE_Default ){
91518       onError = OE_Abort;
91519     }
91520     if( seenReplace ){
91521       if( onError==OE_Ignore ) onError = OE_Replace;
91522       else if( onError==OE_Fail ) onError = OE_Abort;
91523     }
91524     
91525     /* Check to see if the new index entry will be unique */
91526     regR = sqlite3GetTempReg(pParse);
91527     sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
91528     j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
91529                            regR, SQLITE_INT_TO_PTR(regIdx),
91530                            P4_INT32);
91531     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
91532
91533     /* Generate code that executes if the new index entry is not unique */
91534     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
91535         || onError==OE_Ignore || onError==OE_Replace );
91536     switch( onError ){
91537       case OE_Rollback:
91538       case OE_Abort:
91539       case OE_Fail: {
91540         int j;
91541         StrAccum errMsg;
91542         const char *zSep;
91543         char *zErr;
91544
91545         sqlite3StrAccumInit(&errMsg, 0, 0, 200);
91546         errMsg.db = db;
91547         zSep = pIdx->nColumn>1 ? "columns " : "column ";
91548         for(j=0; j<pIdx->nColumn; j++){
91549           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
91550           sqlite3StrAccumAppend(&errMsg, zSep, -1);
91551           zSep = ", ";
91552           sqlite3StrAccumAppend(&errMsg, zCol, -1);
91553         }
91554         sqlite3StrAccumAppend(&errMsg,
91555             pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
91556         zErr = sqlite3StrAccumFinish(&errMsg);
91557         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_UNIQUE,
91558                               onError, zErr, 0);
91559         sqlite3DbFree(errMsg.db, zErr);
91560         break;
91561       }
91562       case OE_Ignore: {
91563         assert( seenReplace==0 );
91564         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
91565         break;
91566       }
91567       default: {
91568         Trigger *pTrigger = 0;
91569         assert( onError==OE_Replace );
91570         sqlite3MultiWrite(pParse);
91571         if( db->flags&SQLITE_RecTriggers ){
91572           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
91573         }
91574         sqlite3GenerateRowDelete(
91575             pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
91576         );
91577         seenReplace = 1;
91578         break;
91579       }
91580     }
91581     sqlite3VdbeJumpHere(v, j3);
91582     sqlite3ReleaseTempReg(pParse, regR);
91583   }
91584   
91585   if( pbMayReplace ){
91586     *pbMayReplace = seenReplace;
91587   }
91588 }
91589
91590 /*
91591 ** This routine generates code to finish the INSERT or UPDATE operation
91592 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
91593 ** A consecutive range of registers starting at regRowid contains the
91594 ** rowid and the content to be inserted.
91595 **
91596 ** The arguments to this routine should be the same as the first six
91597 ** arguments to sqlite3GenerateConstraintChecks.
91598 */
91599 SQLITE_PRIVATE void sqlite3CompleteInsertion(
91600   Parse *pParse,      /* The parser context */
91601   Table *pTab,        /* the table into which we are inserting */
91602   int baseCur,        /* Index of a read/write cursor pointing at pTab */
91603   int regRowid,       /* Range of content */
91604   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
91605   int isUpdate,       /* True for UPDATE, False for INSERT */
91606   int appendBias,     /* True if this is likely to be an append */
91607   int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
91608 ){
91609   int i;
91610   Vdbe *v;
91611   int nIdx;
91612   Index *pIdx;
91613   u8 pik_flags;
91614   int regData;
91615   int regRec;
91616
91617   v = sqlite3GetVdbe(pParse);
91618   assert( v!=0 );
91619   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
91620   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
91621   for(i=nIdx-1; i>=0; i--){
91622     if( aRegIdx[i]==0 ) continue;
91623     sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
91624     if( useSeekResult ){
91625       sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
91626     }
91627   }
91628   regData = regRowid + 1;
91629   regRec = sqlite3GetTempReg(pParse);
91630   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
91631   sqlite3TableAffinityStr(v, pTab);
91632   sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
91633   if( pParse->nested ){
91634     pik_flags = 0;
91635   }else{
91636     pik_flags = OPFLAG_NCHANGE;
91637     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
91638   }
91639   if( appendBias ){
91640     pik_flags |= OPFLAG_APPEND;
91641   }
91642   if( useSeekResult ){
91643     pik_flags |= OPFLAG_USESEEKRESULT;
91644   }
91645   sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
91646   if( !pParse->nested ){
91647     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
91648   }
91649   sqlite3VdbeChangeP5(v, pik_flags);
91650 }
91651
91652 /*
91653 ** Generate code that will open cursors for a table and for all
91654 ** indices of that table.  The "baseCur" parameter is the cursor number used
91655 ** for the table.  Indices are opened on subsequent cursors.
91656 **
91657 ** Return the number of indices on the table.
91658 */
91659 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
91660   Parse *pParse,   /* Parsing context */
91661   Table *pTab,     /* Table to be opened */
91662   int baseCur,     /* Cursor number assigned to the table */
91663   int op           /* OP_OpenRead or OP_OpenWrite */
91664 ){
91665   int i;
91666   int iDb;
91667   Index *pIdx;
91668   Vdbe *v;
91669
91670   if( IsVirtual(pTab) ) return 0;
91671   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
91672   v = sqlite3GetVdbe(pParse);
91673   assert( v!=0 );
91674   sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
91675   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
91676     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
91677     assert( pIdx->pSchema==pTab->pSchema );
91678     sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
91679                       (char*)pKey, P4_KEYINFO_HANDOFF);
91680     VdbeComment((v, "%s", pIdx->zName));
91681   }
91682   if( pParse->nTab<baseCur+i ){
91683     pParse->nTab = baseCur+i;
91684   }
91685   return i-1;
91686 }
91687
91688
91689 #ifdef SQLITE_TEST
91690 /*
91691 ** The following global variable is incremented whenever the
91692 ** transfer optimization is used.  This is used for testing
91693 ** purposes only - to make sure the transfer optimization really
91694 ** is happening when it is suppose to.
91695 */
91696 SQLITE_API int sqlite3_xferopt_count;
91697 #endif /* SQLITE_TEST */
91698
91699
91700 #ifndef SQLITE_OMIT_XFER_OPT
91701 /*
91702 ** Check to collation names to see if they are compatible.
91703 */
91704 static int xferCompatibleCollation(const char *z1, const char *z2){
91705   if( z1==0 ){
91706     return z2==0;
91707   }
91708   if( z2==0 ){
91709     return 0;
91710   }
91711   return sqlite3StrICmp(z1, z2)==0;
91712 }
91713
91714
91715 /*
91716 ** Check to see if index pSrc is compatible as a source of data
91717 ** for index pDest in an insert transfer optimization.  The rules
91718 ** for a compatible index:
91719 **
91720 **    *   The index is over the same set of columns
91721 **    *   The same DESC and ASC markings occurs on all columns
91722 **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
91723 **    *   The same collating sequence on each column
91724 */
91725 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
91726   int i;
91727   assert( pDest && pSrc );
91728   assert( pDest->pTable!=pSrc->pTable );
91729   if( pDest->nColumn!=pSrc->nColumn ){
91730     return 0;   /* Different number of columns */
91731   }
91732   if( pDest->onError!=pSrc->onError ){
91733     return 0;   /* Different conflict resolution strategies */
91734   }
91735   for(i=0; i<pSrc->nColumn; i++){
91736     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
91737       return 0;   /* Different columns indexed */
91738     }
91739     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
91740       return 0;   /* Different sort orders */
91741     }
91742     if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
91743       return 0;   /* Different collating sequences */
91744     }
91745   }
91746
91747   /* If no test above fails then the indices must be compatible */
91748   return 1;
91749 }
91750
91751 /*
91752 ** Attempt the transfer optimization on INSERTs of the form
91753 **
91754 **     INSERT INTO tab1 SELECT * FROM tab2;
91755 **
91756 ** The xfer optimization transfers raw records from tab2 over to tab1.  
91757 ** Columns are not decoded and reassemblied, which greatly improves
91758 ** performance.  Raw index records are transferred in the same way.
91759 **
91760 ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
91761 ** There are lots of rules for determining compatibility - see comments
91762 ** embedded in the code for details.
91763 **
91764 ** This routine returns TRUE if the optimization is guaranteed to be used.
91765 ** Sometimes the xfer optimization will only work if the destination table
91766 ** is empty - a factor that can only be determined at run-time.  In that
91767 ** case, this routine generates code for the xfer optimization but also
91768 ** does a test to see if the destination table is empty and jumps over the
91769 ** xfer optimization code if the test fails.  In that case, this routine
91770 ** returns FALSE so that the caller will know to go ahead and generate
91771 ** an unoptimized transfer.  This routine also returns FALSE if there
91772 ** is no chance that the xfer optimization can be applied.
91773 **
91774 ** This optimization is particularly useful at making VACUUM run faster.
91775 */
91776 static int xferOptimization(
91777   Parse *pParse,        /* Parser context */
91778   Table *pDest,         /* The table we are inserting into */
91779   Select *pSelect,      /* A SELECT statement to use as the data source */
91780   int onError,          /* How to handle constraint errors */
91781   int iDbDest           /* The database of pDest */
91782 ){
91783   ExprList *pEList;                /* The result set of the SELECT */
91784   Table *pSrc;                     /* The table in the FROM clause of SELECT */
91785   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
91786   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
91787   int i;                           /* Loop counter */
91788   int iDbSrc;                      /* The database of pSrc */
91789   int iSrc, iDest;                 /* Cursors from source and destination */
91790   int addr1, addr2;                /* Loop addresses */
91791   int emptyDestTest;               /* Address of test for empty pDest */
91792   int emptySrcTest;                /* Address of test for empty pSrc */
91793   Vdbe *v;                         /* The VDBE we are building */
91794   KeyInfo *pKey;                   /* Key information for an index */
91795   int regAutoinc;                  /* Memory register used by AUTOINC */
91796   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
91797   int regData, regRowid;           /* Registers holding data and rowid */
91798
91799   if( pSelect==0 ){
91800     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
91801   }
91802   if( sqlite3TriggerList(pParse, pDest) ){
91803     return 0;   /* tab1 must not have triggers */
91804   }
91805 #ifndef SQLITE_OMIT_VIRTUALTABLE
91806   if( pDest->tabFlags & TF_Virtual ){
91807     return 0;   /* tab1 must not be a virtual table */
91808   }
91809 #endif
91810   if( onError==OE_Default ){
91811     if( pDest->iPKey>=0 ) onError = pDest->keyConf;
91812     if( onError==OE_Default ) onError = OE_Abort;
91813   }
91814   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
91815   if( pSelect->pSrc->nSrc!=1 ){
91816     return 0;   /* FROM clause must have exactly one term */
91817   }
91818   if( pSelect->pSrc->a[0].pSelect ){
91819     return 0;   /* FROM clause cannot contain a subquery */
91820   }
91821   if( pSelect->pWhere ){
91822     return 0;   /* SELECT may not have a WHERE clause */
91823   }
91824   if( pSelect->pOrderBy ){
91825     return 0;   /* SELECT may not have an ORDER BY clause */
91826   }
91827   /* Do not need to test for a HAVING clause.  If HAVING is present but
91828   ** there is no ORDER BY, we will get an error. */
91829   if( pSelect->pGroupBy ){
91830     return 0;   /* SELECT may not have a GROUP BY clause */
91831   }
91832   if( pSelect->pLimit ){
91833     return 0;   /* SELECT may not have a LIMIT clause */
91834   }
91835   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
91836   if( pSelect->pPrior ){
91837     return 0;   /* SELECT may not be a compound query */
91838   }
91839   if( pSelect->selFlags & SF_Distinct ){
91840     return 0;   /* SELECT may not be DISTINCT */
91841   }
91842   pEList = pSelect->pEList;
91843   assert( pEList!=0 );
91844   if( pEList->nExpr!=1 ){
91845     return 0;   /* The result set must have exactly one column */
91846   }
91847   assert( pEList->a[0].pExpr );
91848   if( pEList->a[0].pExpr->op!=TK_ALL ){
91849     return 0;   /* The result set must be the special operator "*" */
91850   }
91851
91852   /* At this point we have established that the statement is of the
91853   ** correct syntactic form to participate in this optimization.  Now
91854   ** we have to check the semantics.
91855   */
91856   pItem = pSelect->pSrc->a;
91857   pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
91858   if( pSrc==0 ){
91859     return 0;   /* FROM clause does not contain a real table */
91860   }
91861   if( pSrc==pDest ){
91862     return 0;   /* tab1 and tab2 may not be the same table */
91863   }
91864 #ifndef SQLITE_OMIT_VIRTUALTABLE
91865   if( pSrc->tabFlags & TF_Virtual ){
91866     return 0;   /* tab2 must not be a virtual table */
91867   }
91868 #endif
91869   if( pSrc->pSelect ){
91870     return 0;   /* tab2 may not be a view */
91871   }
91872   if( pDest->nCol!=pSrc->nCol ){
91873     return 0;   /* Number of columns must be the same in tab1 and tab2 */
91874   }
91875   if( pDest->iPKey!=pSrc->iPKey ){
91876     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
91877   }
91878   for(i=0; i<pDest->nCol; i++){
91879     if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
91880       return 0;    /* Affinity must be the same on all columns */
91881     }
91882     if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
91883       return 0;    /* Collating sequence must be the same on all columns */
91884     }
91885     if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
91886       return 0;    /* tab2 must be NOT NULL if tab1 is */
91887     }
91888   }
91889   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
91890     if( pDestIdx->onError!=OE_None ){
91891       destHasUniqueIdx = 1;
91892     }
91893     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
91894       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
91895     }
91896     if( pSrcIdx==0 ){
91897       return 0;    /* pDestIdx has no corresponding index in pSrc */
91898     }
91899   }
91900 #ifndef SQLITE_OMIT_CHECK
91901   if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck, pDest->pCheck) ){
91902     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
91903   }
91904 #endif
91905 #ifndef SQLITE_OMIT_FOREIGN_KEY
91906   /* Disallow the transfer optimization if the destination table constains
91907   ** any foreign key constraints.  This is more restrictive than necessary.
91908   ** But the main beneficiary of the transfer optimization is the VACUUM 
91909   ** command, and the VACUUM command disables foreign key constraints.  So
91910   ** the extra complication to make this rule less restrictive is probably
91911   ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
91912   */
91913   if( (pParse->db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
91914     return 0;
91915   }
91916 #endif
91917   if( (pParse->db->flags & SQLITE_CountRows)!=0 ){
91918     return 0;  /* xfer opt does not play well with PRAGMA count_changes */
91919   }
91920
91921   /* If we get this far, it means that the xfer optimization is at
91922   ** least a possibility, though it might only work if the destination
91923   ** table (tab1) is initially empty.
91924   */
91925 #ifdef SQLITE_TEST
91926   sqlite3_xferopt_count++;
91927 #endif
91928   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
91929   v = sqlite3GetVdbe(pParse);
91930   sqlite3CodeVerifySchema(pParse, iDbSrc);
91931   iSrc = pParse->nTab++;
91932   iDest = pParse->nTab++;
91933   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
91934   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
91935   if( (pDest->iPKey<0 && pDest->pIndex!=0)          /* (1) */
91936    || destHasUniqueIdx                              /* (2) */
91937    || (onError!=OE_Abort && onError!=OE_Rollback)   /* (3) */
91938   ){
91939     /* In some circumstances, we are able to run the xfer optimization
91940     ** only if the destination table is initially empty.  This code makes
91941     ** that determination.  Conditions under which the destination must
91942     ** be empty:
91943     **
91944     ** (1) There is no INTEGER PRIMARY KEY but there are indices.
91945     **     (If the destination is not initially empty, the rowid fields
91946     **     of index entries might need to change.)
91947     **
91948     ** (2) The destination has a unique index.  (The xfer optimization 
91949     **     is unable to test uniqueness.)
91950     **
91951     ** (3) onError is something other than OE_Abort and OE_Rollback.
91952     */
91953     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
91954     emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
91955     sqlite3VdbeJumpHere(v, addr1);
91956   }else{
91957     emptyDestTest = 0;
91958   }
91959   sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
91960   emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
91961   regData = sqlite3GetTempReg(pParse);
91962   regRowid = sqlite3GetTempReg(pParse);
91963   if( pDest->iPKey>=0 ){
91964     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
91965     addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
91966     sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_PRIMARYKEY,
91967         onError, "PRIMARY KEY must be unique", P4_STATIC);
91968     sqlite3VdbeJumpHere(v, addr2);
91969     autoIncStep(pParse, regAutoinc, regRowid);
91970   }else if( pDest->pIndex==0 ){
91971     addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
91972   }else{
91973     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
91974     assert( (pDest->tabFlags & TF_Autoincrement)==0 );
91975   }
91976   sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
91977   sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
91978   sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
91979   sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
91980   sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
91981   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
91982     for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
91983       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
91984     }
91985     assert( pSrcIdx );
91986     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
91987     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
91988     pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
91989     sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
91990                       (char*)pKey, P4_KEYINFO_HANDOFF);
91991     VdbeComment((v, "%s", pSrcIdx->zName));
91992     pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
91993     sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
91994                       (char*)pKey, P4_KEYINFO_HANDOFF);
91995     VdbeComment((v, "%s", pDestIdx->zName));
91996     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
91997     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
91998     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
91999     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
92000     sqlite3VdbeJumpHere(v, addr1);
92001   }
92002   sqlite3VdbeJumpHere(v, emptySrcTest);
92003   sqlite3ReleaseTempReg(pParse, regRowid);
92004   sqlite3ReleaseTempReg(pParse, regData);
92005   sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
92006   sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
92007   if( emptyDestTest ){
92008     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
92009     sqlite3VdbeJumpHere(v, emptyDestTest);
92010     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
92011     return 0;
92012   }else{
92013     return 1;
92014   }
92015 }
92016 #endif /* SQLITE_OMIT_XFER_OPT */
92017
92018 /************** End of insert.c **********************************************/
92019 /************** Begin file legacy.c ******************************************/
92020 /*
92021 ** 2001 September 15
92022 **
92023 ** The author disclaims copyright to this source code.  In place of
92024 ** a legal notice, here is a blessing:
92025 **
92026 **    May you do good and not evil.
92027 **    May you find forgiveness for yourself and forgive others.
92028 **    May you share freely, never taking more than you give.
92029 **
92030 *************************************************************************
92031 ** Main file for the SQLite library.  The routines in this file
92032 ** implement the programmer interface to the library.  Routines in
92033 ** other files are for internal use by SQLite and should not be
92034 ** accessed by users of the library.
92035 */
92036
92037
92038 /*
92039 ** Execute SQL code.  Return one of the SQLITE_ success/failure
92040 ** codes.  Also write an error message into memory obtained from
92041 ** malloc() and make *pzErrMsg point to that message.
92042 **
92043 ** If the SQL is a query, then for each row in the query result
92044 ** the xCallback() function is called.  pArg becomes the first
92045 ** argument to xCallback().  If xCallback=NULL then no callback
92046 ** is invoked, even for queries.
92047 */
92048 SQLITE_API int sqlite3_exec(
92049   sqlite3 *db,                /* The database on which the SQL executes */
92050   const char *zSql,           /* The SQL to be executed */
92051   sqlite3_callback xCallback, /* Invoke this callback routine */
92052   void *pArg,                 /* First argument to xCallback() */
92053   char **pzErrMsg             /* Write error messages here */
92054 ){
92055   int rc = SQLITE_OK;         /* Return code */
92056   const char *zLeftover;      /* Tail of unprocessed SQL */
92057   sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
92058   char **azCols = 0;          /* Names of result columns */
92059   int callbackIsInit;         /* True if callback data is initialized */
92060
92061   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
92062   if( zSql==0 ) zSql = "";
92063
92064   sqlite3_mutex_enter(db->mutex);
92065   sqlite3Error(db, SQLITE_OK, 0);
92066   while( rc==SQLITE_OK && zSql[0] ){
92067     int nCol;
92068     char **azVals = 0;
92069
92070     pStmt = 0;
92071     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
92072     assert( rc==SQLITE_OK || pStmt==0 );
92073     if( rc!=SQLITE_OK ){
92074       continue;
92075     }
92076     if( !pStmt ){
92077       /* this happens for a comment or white-space */
92078       zSql = zLeftover;
92079       continue;
92080     }
92081
92082     callbackIsInit = 0;
92083     nCol = sqlite3_column_count(pStmt);
92084
92085     while( 1 ){
92086       int i;
92087       rc = sqlite3_step(pStmt);
92088
92089       /* Invoke the callback function if required */
92090       if( xCallback && (SQLITE_ROW==rc || 
92091           (SQLITE_DONE==rc && !callbackIsInit
92092                            && db->flags&SQLITE_NullCallback)) ){
92093         if( !callbackIsInit ){
92094           azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
92095           if( azCols==0 ){
92096             goto exec_out;
92097           }
92098           for(i=0; i<nCol; i++){
92099             azCols[i] = (char *)sqlite3_column_name(pStmt, i);
92100             /* sqlite3VdbeSetColName() installs column names as UTF8
92101             ** strings so there is no way for sqlite3_column_name() to fail. */
92102             assert( azCols[i]!=0 );
92103           }
92104           callbackIsInit = 1;
92105         }
92106         if( rc==SQLITE_ROW ){
92107           azVals = &azCols[nCol];
92108           for(i=0; i<nCol; i++){
92109             azVals[i] = (char *)sqlite3_column_text(pStmt, i);
92110             if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
92111               db->mallocFailed = 1;
92112               goto exec_out;
92113             }
92114           }
92115         }
92116         if( xCallback(pArg, nCol, azVals, azCols) ){
92117           rc = SQLITE_ABORT;
92118           sqlite3VdbeFinalize((Vdbe *)pStmt);
92119           pStmt = 0;
92120           sqlite3Error(db, SQLITE_ABORT, 0);
92121           goto exec_out;
92122         }
92123       }
92124
92125       if( rc!=SQLITE_ROW ){
92126         rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
92127         pStmt = 0;
92128         zSql = zLeftover;
92129         while( sqlite3Isspace(zSql[0]) ) zSql++;
92130         break;
92131       }
92132     }
92133
92134     sqlite3DbFree(db, azCols);
92135     azCols = 0;
92136   }
92137
92138 exec_out:
92139   if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
92140   sqlite3DbFree(db, azCols);
92141
92142   rc = sqlite3ApiExit(db, rc);
92143   if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){
92144     int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
92145     *pzErrMsg = sqlite3Malloc(nErrMsg);
92146     if( *pzErrMsg ){
92147       memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
92148     }else{
92149       rc = SQLITE_NOMEM;
92150       sqlite3Error(db, SQLITE_NOMEM, 0);
92151     }
92152   }else if( pzErrMsg ){
92153     *pzErrMsg = 0;
92154   }
92155
92156   assert( (rc&db->errMask)==rc );
92157   sqlite3_mutex_leave(db->mutex);
92158   return rc;
92159 }
92160
92161 /************** End of legacy.c **********************************************/
92162 /************** Begin file loadext.c *****************************************/
92163 /*
92164 ** 2006 June 7
92165 **
92166 ** The author disclaims copyright to this source code.  In place of
92167 ** a legal notice, here is a blessing:
92168 **
92169 **    May you do good and not evil.
92170 **    May you find forgiveness for yourself and forgive others.
92171 **    May you share freely, never taking more than you give.
92172 **
92173 *************************************************************************
92174 ** This file contains code used to dynamically load extensions into
92175 ** the SQLite library.
92176 */
92177
92178 #ifndef SQLITE_CORE
92179   #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
92180 #endif
92181 /************** Include sqlite3ext.h in the middle of loadext.c **************/
92182 /************** Begin file sqlite3ext.h **************************************/
92183 /*
92184 ** 2006 June 7
92185 **
92186 ** The author disclaims copyright to this source code.  In place of
92187 ** a legal notice, here is a blessing:
92188 **
92189 **    May you do good and not evil.
92190 **    May you find forgiveness for yourself and forgive others.
92191 **    May you share freely, never taking more than you give.
92192 **
92193 *************************************************************************
92194 ** This header file defines the SQLite interface for use by
92195 ** shared libraries that want to be imported as extensions into
92196 ** an SQLite instance.  Shared libraries that intend to be loaded
92197 ** as extensions by SQLite should #include this file instead of 
92198 ** sqlite3.h.
92199 */
92200 #ifndef _SQLITE3EXT_H_
92201 #define _SQLITE3EXT_H_
92202
92203 typedef struct sqlite3_api_routines sqlite3_api_routines;
92204
92205 /*
92206 ** The following structure holds pointers to all of the SQLite API
92207 ** routines.
92208 **
92209 ** WARNING:  In order to maintain backwards compatibility, add new
92210 ** interfaces to the end of this structure only.  If you insert new
92211 ** interfaces in the middle of this structure, then older different
92212 ** versions of SQLite will not be able to load each others' shared
92213 ** libraries!
92214 */
92215 struct sqlite3_api_routines {
92216   void * (*aggregate_context)(sqlite3_context*,int nBytes);
92217   int  (*aggregate_count)(sqlite3_context*);
92218   int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
92219   int  (*bind_double)(sqlite3_stmt*,int,double);
92220   int  (*bind_int)(sqlite3_stmt*,int,int);
92221   int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
92222   int  (*bind_null)(sqlite3_stmt*,int);
92223   int  (*bind_parameter_count)(sqlite3_stmt*);
92224   int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
92225   const char * (*bind_parameter_name)(sqlite3_stmt*,int);
92226   int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
92227   int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
92228   int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
92229   int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
92230   int  (*busy_timeout)(sqlite3*,int ms);
92231   int  (*changes)(sqlite3*);
92232   int  (*close)(sqlite3*);
92233   int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
92234                            int eTextRep,const char*));
92235   int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
92236                              int eTextRep,const void*));
92237   const void * (*column_blob)(sqlite3_stmt*,int iCol);
92238   int  (*column_bytes)(sqlite3_stmt*,int iCol);
92239   int  (*column_bytes16)(sqlite3_stmt*,int iCol);
92240   int  (*column_count)(sqlite3_stmt*pStmt);
92241   const char * (*column_database_name)(sqlite3_stmt*,int);
92242   const void * (*column_database_name16)(sqlite3_stmt*,int);
92243   const char * (*column_decltype)(sqlite3_stmt*,int i);
92244   const void * (*column_decltype16)(sqlite3_stmt*,int);
92245   double  (*column_double)(sqlite3_stmt*,int iCol);
92246   int  (*column_int)(sqlite3_stmt*,int iCol);
92247   sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
92248   const char * (*column_name)(sqlite3_stmt*,int);
92249   const void * (*column_name16)(sqlite3_stmt*,int);
92250   const char * (*column_origin_name)(sqlite3_stmt*,int);
92251   const void * (*column_origin_name16)(sqlite3_stmt*,int);
92252   const char * (*column_table_name)(sqlite3_stmt*,int);
92253   const void * (*column_table_name16)(sqlite3_stmt*,int);
92254   const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
92255   const void * (*column_text16)(sqlite3_stmt*,int iCol);
92256   int  (*column_type)(sqlite3_stmt*,int iCol);
92257   sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
92258   void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
92259   int  (*complete)(const char*sql);
92260   int  (*complete16)(const void*sql);
92261   int  (*create_collation)(sqlite3*,const char*,int,void*,
92262                            int(*)(void*,int,const void*,int,const void*));
92263   int  (*create_collation16)(sqlite3*,const void*,int,void*,
92264                              int(*)(void*,int,const void*,int,const void*));
92265   int  (*create_function)(sqlite3*,const char*,int,int,void*,
92266                           void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
92267                           void (*xStep)(sqlite3_context*,int,sqlite3_value**),
92268                           void (*xFinal)(sqlite3_context*));
92269   int  (*create_function16)(sqlite3*,const void*,int,int,void*,
92270                             void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
92271                             void (*xStep)(sqlite3_context*,int,sqlite3_value**),
92272                             void (*xFinal)(sqlite3_context*));
92273   int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
92274   int  (*data_count)(sqlite3_stmt*pStmt);
92275   sqlite3 * (*db_handle)(sqlite3_stmt*);
92276   int (*declare_vtab)(sqlite3*,const char*);
92277   int  (*enable_shared_cache)(int);
92278   int  (*errcode)(sqlite3*db);
92279   const char * (*errmsg)(sqlite3*);
92280   const void * (*errmsg16)(sqlite3*);
92281   int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
92282   int  (*expired)(sqlite3_stmt*);
92283   int  (*finalize)(sqlite3_stmt*pStmt);
92284   void  (*free)(void*);
92285   void  (*free_table)(char**result);
92286   int  (*get_autocommit)(sqlite3*);
92287   void * (*get_auxdata)(sqlite3_context*,int);
92288   int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
92289   int  (*global_recover)(void);
92290   void  (*interruptx)(sqlite3*);
92291   sqlite_int64  (*last_insert_rowid)(sqlite3*);
92292   const char * (*libversion)(void);
92293   int  (*libversion_number)(void);
92294   void *(*malloc)(int);
92295   char * (*mprintf)(const char*,...);
92296   int  (*open)(const char*,sqlite3**);
92297   int  (*open16)(const void*,sqlite3**);
92298   int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
92299   int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
92300   void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
92301   void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
92302   void *(*realloc)(void*,int);
92303   int  (*reset)(sqlite3_stmt*pStmt);
92304   void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
92305   void  (*result_double)(sqlite3_context*,double);
92306   void  (*result_error)(sqlite3_context*,const char*,int);
92307   void  (*result_error16)(sqlite3_context*,const void*,int);
92308   void  (*result_int)(sqlite3_context*,int);
92309   void  (*result_int64)(sqlite3_context*,sqlite_int64);
92310   void  (*result_null)(sqlite3_context*);
92311   void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
92312   void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
92313   void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
92314   void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
92315   void  (*result_value)(sqlite3_context*,sqlite3_value*);
92316   void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
92317   int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
92318                          const char*,const char*),void*);
92319   void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
92320   char * (*snprintf)(int,char*,const char*,...);
92321   int  (*step)(sqlite3_stmt*);
92322   int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
92323                                 char const**,char const**,int*,int*,int*);
92324   void  (*thread_cleanup)(void);
92325   int  (*total_changes)(sqlite3*);
92326   void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
92327   int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
92328   void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
92329                                          sqlite_int64),void*);
92330   void * (*user_data)(sqlite3_context*);
92331   const void * (*value_blob)(sqlite3_value*);
92332   int  (*value_bytes)(sqlite3_value*);
92333   int  (*value_bytes16)(sqlite3_value*);
92334   double  (*value_double)(sqlite3_value*);
92335   int  (*value_int)(sqlite3_value*);
92336   sqlite_int64  (*value_int64)(sqlite3_value*);
92337   int  (*value_numeric_type)(sqlite3_value*);
92338   const unsigned char * (*value_text)(sqlite3_value*);
92339   const void * (*value_text16)(sqlite3_value*);
92340   const void * (*value_text16be)(sqlite3_value*);
92341   const void * (*value_text16le)(sqlite3_value*);
92342   int  (*value_type)(sqlite3_value*);
92343   char *(*vmprintf)(const char*,va_list);
92344   /* Added ??? */
92345   int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
92346   /* Added by 3.3.13 */
92347   int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
92348   int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
92349   int (*clear_bindings)(sqlite3_stmt*);
92350   /* Added by 3.4.1 */
92351   int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
92352                           void (*xDestroy)(void *));
92353   /* Added by 3.5.0 */
92354   int (*bind_zeroblob)(sqlite3_stmt*,int,int);
92355   int (*blob_bytes)(sqlite3_blob*);
92356   int (*blob_close)(sqlite3_blob*);
92357   int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
92358                    int,sqlite3_blob**);
92359   int (*blob_read)(sqlite3_blob*,void*,int,int);
92360   int (*blob_write)(sqlite3_blob*,const void*,int,int);
92361   int (*create_collation_v2)(sqlite3*,const char*,int,void*,
92362                              int(*)(void*,int,const void*,int,const void*),
92363                              void(*)(void*));
92364   int (*file_control)(sqlite3*,const char*,int,void*);
92365   sqlite3_int64 (*memory_highwater)(int);
92366   sqlite3_int64 (*memory_used)(void);
92367   sqlite3_mutex *(*mutex_alloc)(int);
92368   void (*mutex_enter)(sqlite3_mutex*);
92369   void (*mutex_free)(sqlite3_mutex*);
92370   void (*mutex_leave)(sqlite3_mutex*);
92371   int (*mutex_try)(sqlite3_mutex*);
92372   int (*open_v2)(const char*,sqlite3**,int,const char*);
92373   int (*release_memory)(int);
92374   void (*result_error_nomem)(sqlite3_context*);
92375   void (*result_error_toobig)(sqlite3_context*);
92376   int (*sleep)(int);
92377   void (*soft_heap_limit)(int);
92378   sqlite3_vfs *(*vfs_find)(const char*);
92379   int (*vfs_register)(sqlite3_vfs*,int);
92380   int (*vfs_unregister)(sqlite3_vfs*);
92381   int (*xthreadsafe)(void);
92382   void (*result_zeroblob)(sqlite3_context*,int);
92383   void (*result_error_code)(sqlite3_context*,int);
92384   int (*test_control)(int, ...);
92385   void (*randomness)(int,void*);
92386   sqlite3 *(*context_db_handle)(sqlite3_context*);
92387   int (*extended_result_codes)(sqlite3*,int);
92388   int (*limit)(sqlite3*,int,int);
92389   sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
92390   const char *(*sql)(sqlite3_stmt*);
92391   int (*status)(int,int*,int*,int);
92392   int (*backup_finish)(sqlite3_backup*);
92393   sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
92394   int (*backup_pagecount)(sqlite3_backup*);
92395   int (*backup_remaining)(sqlite3_backup*);
92396   int (*backup_step)(sqlite3_backup*,int);
92397   const char *(*compileoption_get)(int);
92398   int (*compileoption_used)(const char*);
92399   int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
92400                             void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
92401                             void (*xStep)(sqlite3_context*,int,sqlite3_value**),
92402                             void (*xFinal)(sqlite3_context*),
92403                             void(*xDestroy)(void*));
92404   int (*db_config)(sqlite3*,int,...);
92405   sqlite3_mutex *(*db_mutex)(sqlite3*);
92406   int (*db_status)(sqlite3*,int,int*,int*,int);
92407   int (*extended_errcode)(sqlite3*);
92408   void (*log)(int,const char*,...);
92409   sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
92410   const char *(*sourceid)(void);
92411   int (*stmt_status)(sqlite3_stmt*,int,int);
92412   int (*strnicmp)(const char*,const char*,int);
92413   int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
92414   int (*wal_autocheckpoint)(sqlite3*,int);
92415   int (*wal_checkpoint)(sqlite3*,const char*);
92416   void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
92417   int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
92418   int (*vtab_config)(sqlite3*,int op,...);
92419   int (*vtab_on_conflict)(sqlite3*);
92420   /* Version 3.7.16 and later */
92421   int (*close_v2)(sqlite3*);
92422   const char *(*db_filename)(sqlite3*,const char*);
92423   int (*db_readonly)(sqlite3*,const char*);
92424   int (*db_release_memory)(sqlite3*);
92425   const char *(*errstr)(int);
92426   int (*stmt_busy)(sqlite3_stmt*);
92427   int (*stmt_readonly)(sqlite3_stmt*);
92428   int (*stricmp)(const char*,const char*);
92429   int (*uri_boolean)(const char*,const char*,int);
92430   sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
92431   const char *(*uri_parameter)(const char*,const char*);
92432   char *(*vsnprintf)(int,char*,const char*,va_list);
92433   int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
92434 };
92435
92436 /*
92437 ** The following macros redefine the API routines so that they are
92438 ** redirected throught the global sqlite3_api structure.
92439 **
92440 ** This header file is also used by the loadext.c source file
92441 ** (part of the main SQLite library - not an extension) so that
92442 ** it can get access to the sqlite3_api_routines structure
92443 ** definition.  But the main library does not want to redefine
92444 ** the API.  So the redefinition macros are only valid if the
92445 ** SQLITE_CORE macros is undefined.
92446 */
92447 #ifndef SQLITE_CORE
92448 #define sqlite3_aggregate_context      sqlite3_api->aggregate_context
92449 #ifndef SQLITE_OMIT_DEPRECATED
92450 #define sqlite3_aggregate_count        sqlite3_api->aggregate_count
92451 #endif
92452 #define sqlite3_bind_blob              sqlite3_api->bind_blob
92453 #define sqlite3_bind_double            sqlite3_api->bind_double
92454 #define sqlite3_bind_int               sqlite3_api->bind_int
92455 #define sqlite3_bind_int64             sqlite3_api->bind_int64
92456 #define sqlite3_bind_null              sqlite3_api->bind_null
92457 #define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
92458 #define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
92459 #define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
92460 #define sqlite3_bind_text              sqlite3_api->bind_text
92461 #define sqlite3_bind_text16            sqlite3_api->bind_text16
92462 #define sqlite3_bind_value             sqlite3_api->bind_value
92463 #define sqlite3_busy_handler           sqlite3_api->busy_handler
92464 #define sqlite3_busy_timeout           sqlite3_api->busy_timeout
92465 #define sqlite3_changes                sqlite3_api->changes
92466 #define sqlite3_close                  sqlite3_api->close
92467 #define sqlite3_collation_needed       sqlite3_api->collation_needed
92468 #define sqlite3_collation_needed16     sqlite3_api->collation_needed16
92469 #define sqlite3_column_blob            sqlite3_api->column_blob
92470 #define sqlite3_column_bytes           sqlite3_api->column_bytes
92471 #define sqlite3_column_bytes16         sqlite3_api->column_bytes16
92472 #define sqlite3_column_count           sqlite3_api->column_count
92473 #define sqlite3_column_database_name   sqlite3_api->column_database_name
92474 #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
92475 #define sqlite3_column_decltype        sqlite3_api->column_decltype
92476 #define sqlite3_column_decltype16      sqlite3_api->column_decltype16
92477 #define sqlite3_column_double          sqlite3_api->column_double
92478 #define sqlite3_column_int             sqlite3_api->column_int
92479 #define sqlite3_column_int64           sqlite3_api->column_int64
92480 #define sqlite3_column_name            sqlite3_api->column_name
92481 #define sqlite3_column_name16          sqlite3_api->column_name16
92482 #define sqlite3_column_origin_name     sqlite3_api->column_origin_name
92483 #define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
92484 #define sqlite3_column_table_name      sqlite3_api->column_table_name
92485 #define sqlite3_column_table_name16    sqlite3_api->column_table_name16
92486 #define sqlite3_column_text            sqlite3_api->column_text
92487 #define sqlite3_column_text16          sqlite3_api->column_text16
92488 #define sqlite3_column_type            sqlite3_api->column_type
92489 #define sqlite3_column_value           sqlite3_api->column_value
92490 #define sqlite3_commit_hook            sqlite3_api->commit_hook
92491 #define sqlite3_complete               sqlite3_api->complete
92492 #define sqlite3_complete16             sqlite3_api->complete16
92493 #define sqlite3_create_collation       sqlite3_api->create_collation
92494 #define sqlite3_create_collation16     sqlite3_api->create_collation16
92495 #define sqlite3_create_function        sqlite3_api->create_function
92496 #define sqlite3_create_function16      sqlite3_api->create_function16
92497 #define sqlite3_create_module          sqlite3_api->create_module
92498 #define sqlite3_create_module_v2       sqlite3_api->create_module_v2
92499 #define sqlite3_data_count             sqlite3_api->data_count
92500 #define sqlite3_db_handle              sqlite3_api->db_handle
92501 #define sqlite3_declare_vtab           sqlite3_api->declare_vtab
92502 #define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
92503 #define sqlite3_errcode                sqlite3_api->errcode
92504 #define sqlite3_errmsg                 sqlite3_api->errmsg
92505 #define sqlite3_errmsg16               sqlite3_api->errmsg16
92506 #define sqlite3_exec                   sqlite3_api->exec
92507 #ifndef SQLITE_OMIT_DEPRECATED
92508 #define sqlite3_expired                sqlite3_api->expired
92509 #endif
92510 #define sqlite3_finalize               sqlite3_api->finalize
92511 #define sqlite3_free                   sqlite3_api->free
92512 #define sqlite3_free_table             sqlite3_api->free_table
92513 #define sqlite3_get_autocommit         sqlite3_api->get_autocommit
92514 #define sqlite3_get_auxdata            sqlite3_api->get_auxdata
92515 #define sqlite3_get_table              sqlite3_api->get_table
92516 #ifndef SQLITE_OMIT_DEPRECATED
92517 #define sqlite3_global_recover         sqlite3_api->global_recover
92518 #endif
92519 #define sqlite3_interrupt              sqlite3_api->interruptx
92520 #define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
92521 #define sqlite3_libversion             sqlite3_api->libversion
92522 #define sqlite3_libversion_number      sqlite3_api->libversion_number
92523 #define sqlite3_malloc                 sqlite3_api->malloc
92524 #define sqlite3_mprintf                sqlite3_api->mprintf
92525 #define sqlite3_open                   sqlite3_api->open
92526 #define sqlite3_open16                 sqlite3_api->open16
92527 #define sqlite3_prepare                sqlite3_api->prepare
92528 #define sqlite3_prepare16              sqlite3_api->prepare16
92529 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
92530 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
92531 #define sqlite3_profile                sqlite3_api->profile
92532 #define sqlite3_progress_handler       sqlite3_api->progress_handler
92533 #define sqlite3_realloc                sqlite3_api->realloc
92534 #define sqlite3_reset                  sqlite3_api->reset
92535 #define sqlite3_result_blob            sqlite3_api->result_blob
92536 #define sqlite3_result_double          sqlite3_api->result_double
92537 #define sqlite3_result_error           sqlite3_api->result_error
92538 #define sqlite3_result_error16         sqlite3_api->result_error16
92539 #define sqlite3_result_int             sqlite3_api->result_int
92540 #define sqlite3_result_int64           sqlite3_api->result_int64
92541 #define sqlite3_result_null            sqlite3_api->result_null
92542 #define sqlite3_result_text            sqlite3_api->result_text
92543 #define sqlite3_result_text16          sqlite3_api->result_text16
92544 #define sqlite3_result_text16be        sqlite3_api->result_text16be
92545 #define sqlite3_result_text16le        sqlite3_api->result_text16le
92546 #define sqlite3_result_value           sqlite3_api->result_value
92547 #define sqlite3_rollback_hook          sqlite3_api->rollback_hook
92548 #define sqlite3_set_authorizer         sqlite3_api->set_authorizer
92549 #define sqlite3_set_auxdata            sqlite3_api->set_auxdata
92550 #define sqlite3_snprintf               sqlite3_api->snprintf
92551 #define sqlite3_step                   sqlite3_api->step
92552 #define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
92553 #define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
92554 #define sqlite3_total_changes          sqlite3_api->total_changes
92555 #define sqlite3_trace                  sqlite3_api->trace
92556 #ifndef SQLITE_OMIT_DEPRECATED
92557 #define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
92558 #endif
92559 #define sqlite3_update_hook            sqlite3_api->update_hook
92560 #define sqlite3_user_data              sqlite3_api->user_data
92561 #define sqlite3_value_blob             sqlite3_api->value_blob
92562 #define sqlite3_value_bytes            sqlite3_api->value_bytes
92563 #define sqlite3_value_bytes16          sqlite3_api->value_bytes16
92564 #define sqlite3_value_double           sqlite3_api->value_double
92565 #define sqlite3_value_int              sqlite3_api->value_int
92566 #define sqlite3_value_int64            sqlite3_api->value_int64
92567 #define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
92568 #define sqlite3_value_text             sqlite3_api->value_text
92569 #define sqlite3_value_text16           sqlite3_api->value_text16
92570 #define sqlite3_value_text16be         sqlite3_api->value_text16be
92571 #define sqlite3_value_text16le         sqlite3_api->value_text16le
92572 #define sqlite3_value_type             sqlite3_api->value_type
92573 #define sqlite3_vmprintf               sqlite3_api->vmprintf
92574 #define sqlite3_overload_function      sqlite3_api->overload_function
92575 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
92576 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
92577 #define sqlite3_clear_bindings         sqlite3_api->clear_bindings
92578 #define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
92579 #define sqlite3_blob_bytes             sqlite3_api->blob_bytes
92580 #define sqlite3_blob_close             sqlite3_api->blob_close
92581 #define sqlite3_blob_open              sqlite3_api->blob_open
92582 #define sqlite3_blob_read              sqlite3_api->blob_read
92583 #define sqlite3_blob_write             sqlite3_api->blob_write
92584 #define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
92585 #define sqlite3_file_control           sqlite3_api->file_control
92586 #define sqlite3_memory_highwater       sqlite3_api->memory_highwater
92587 #define sqlite3_memory_used            sqlite3_api->memory_used
92588 #define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
92589 #define sqlite3_mutex_enter            sqlite3_api->mutex_enter
92590 #define sqlite3_mutex_free             sqlite3_api->mutex_free
92591 #define sqlite3_mutex_leave            sqlite3_api->mutex_leave
92592 #define sqlite3_mutex_try              sqlite3_api->mutex_try
92593 #define sqlite3_open_v2                sqlite3_api->open_v2
92594 #define sqlite3_release_memory         sqlite3_api->release_memory
92595 #define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
92596 #define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
92597 #define sqlite3_sleep                  sqlite3_api->sleep
92598 #define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
92599 #define sqlite3_vfs_find               sqlite3_api->vfs_find
92600 #define sqlite3_vfs_register           sqlite3_api->vfs_register
92601 #define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
92602 #define sqlite3_threadsafe             sqlite3_api->xthreadsafe
92603 #define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
92604 #define sqlite3_result_error_code      sqlite3_api->result_error_code
92605 #define sqlite3_test_control           sqlite3_api->test_control
92606 #define sqlite3_randomness             sqlite3_api->randomness
92607 #define sqlite3_context_db_handle      sqlite3_api->context_db_handle
92608 #define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
92609 #define sqlite3_limit                  sqlite3_api->limit
92610 #define sqlite3_next_stmt              sqlite3_api->next_stmt
92611 #define sqlite3_sql                    sqlite3_api->sql
92612 #define sqlite3_status                 sqlite3_api->status
92613 #define sqlite3_backup_finish          sqlite3_api->backup_finish
92614 #define sqlite3_backup_init            sqlite3_api->backup_init
92615 #define sqlite3_backup_pagecount       sqlite3_api->backup_pagecount
92616 #define sqlite3_backup_remaining       sqlite3_api->backup_remaining
92617 #define sqlite3_backup_step            sqlite3_api->backup_step
92618 #define sqlite3_compileoption_get      sqlite3_api->compileoption_get
92619 #define sqlite3_compileoption_used     sqlite3_api->compileoption_used
92620 #define sqlite3_create_function_v2     sqlite3_api->create_function_v2
92621 #define sqlite3_db_config              sqlite3_api->db_config
92622 #define sqlite3_db_mutex               sqlite3_api->db_mutex
92623 #define sqlite3_db_status              sqlite3_api->db_status
92624 #define sqlite3_extended_errcode       sqlite3_api->extended_errcode
92625 #define sqlite3_log                    sqlite3_api->log
92626 #define sqlite3_soft_heap_limit64      sqlite3_api->soft_heap_limit64
92627 #define sqlite3_sourceid               sqlite3_api->sourceid
92628 #define sqlite3_stmt_status            sqlite3_api->stmt_status
92629 #define sqlite3_strnicmp               sqlite3_api->strnicmp
92630 #define sqlite3_unlock_notify          sqlite3_api->unlock_notify
92631 #define sqlite3_wal_autocheckpoint     sqlite3_api->wal_autocheckpoint
92632 #define sqlite3_wal_checkpoint         sqlite3_api->wal_checkpoint
92633 #define sqlite3_wal_hook               sqlite3_api->wal_hook
92634 #define sqlite3_blob_reopen            sqlite3_api->blob_reopen
92635 #define sqlite3_vtab_config            sqlite3_api->vtab_config
92636 #define sqlite3_vtab_on_conflict       sqlite3_api->vtab_on_conflict
92637 /* Version 3.7.16 and later */
92638 #define sqlite3_close_v2               sqlite3_api->close_v2
92639 #define sqlite3_db_filename            sqlite3_api->db_filename
92640 #define sqlite3_db_readonly            sqlite3_api->db_readonly
92641 #define sqlite3_db_release_memory      sqlite3_api->db_release_memory
92642 #define sqlite3_errstr                 sqlite3_api->errstr
92643 #define sqlite3_stmt_busy              sqlite3_api->stmt_busy
92644 #define sqlite3_stmt_readonly          sqlite3_api->stmt_readonly
92645 #define sqlite3_stricmp                sqlite3_api->stricmp
92646 #define sqlite3_uri_boolean            sqlite3_api->uri_boolean
92647 #define sqlite3_uri_int64              sqlite3_api->uri_int64
92648 #define sqlite3_uri_parameter          sqlite3_api->uri_parameter
92649 #define sqlite3_uri_vsnprintf          sqlite3_api->vsnprintf
92650 #define sqlite3_wal_checkpoint_v2      sqlite3_api->wal_checkpoint_v2
92651 #endif /* SQLITE_CORE */
92652
92653 #ifndef SQLITE_CORE
92654   /* This case when the file really is being compiled as a loadable 
92655   ** extension */
92656 # define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api=0;
92657 # define SQLITE_EXTENSION_INIT2(v)  sqlite3_api=v;
92658 #else
92659   /* This case when the file is being statically linked into the 
92660   ** application */
92661 # define SQLITE_EXTENSION_INIT1     /*no-op*/
92662 # define SQLITE_EXTENSION_INIT2(v)  (void)v; /* unused parameter */
92663 #endif
92664
92665 #endif /* _SQLITE3EXT_H_ */
92666
92667 /************** End of sqlite3ext.h ******************************************/
92668 /************** Continuing where we left off in loadext.c ********************/
92669 /* #include <string.h> */
92670
92671 #ifndef SQLITE_OMIT_LOAD_EXTENSION
92672
92673 /*
92674 ** Some API routines are omitted when various features are
92675 ** excluded from a build of SQLite.  Substitute a NULL pointer
92676 ** for any missing APIs.
92677 */
92678 #ifndef SQLITE_ENABLE_COLUMN_METADATA
92679 # define sqlite3_column_database_name   0
92680 # define sqlite3_column_database_name16 0
92681 # define sqlite3_column_table_name      0
92682 # define sqlite3_column_table_name16    0
92683 # define sqlite3_column_origin_name     0
92684 # define sqlite3_column_origin_name16   0
92685 # define sqlite3_table_column_metadata  0
92686 #endif
92687
92688 #ifdef SQLITE_OMIT_AUTHORIZATION
92689 # define sqlite3_set_authorizer         0
92690 #endif
92691
92692 #ifdef SQLITE_OMIT_UTF16
92693 # define sqlite3_bind_text16            0
92694 # define sqlite3_collation_needed16     0
92695 # define sqlite3_column_decltype16      0
92696 # define sqlite3_column_name16          0
92697 # define sqlite3_column_text16          0
92698 # define sqlite3_complete16             0
92699 # define sqlite3_create_collation16     0
92700 # define sqlite3_create_function16      0
92701 # define sqlite3_errmsg16               0
92702 # define sqlite3_open16                 0
92703 # define sqlite3_prepare16              0
92704 # define sqlite3_prepare16_v2           0
92705 # define sqlite3_result_error16         0
92706 # define sqlite3_result_text16          0
92707 # define sqlite3_result_text16be        0
92708 # define sqlite3_result_text16le        0
92709 # define sqlite3_value_text16           0
92710 # define sqlite3_value_text16be         0
92711 # define sqlite3_value_text16le         0
92712 # define sqlite3_column_database_name16 0
92713 # define sqlite3_column_table_name16    0
92714 # define sqlite3_column_origin_name16   0
92715 #endif
92716
92717 #ifdef SQLITE_OMIT_COMPLETE
92718 # define sqlite3_complete 0
92719 # define sqlite3_complete16 0
92720 #endif
92721
92722 #ifdef SQLITE_OMIT_DECLTYPE
92723 # define sqlite3_column_decltype16      0
92724 # define sqlite3_column_decltype        0
92725 #endif
92726
92727 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
92728 # define sqlite3_progress_handler 0
92729 #endif
92730
92731 #ifdef SQLITE_OMIT_VIRTUALTABLE
92732 # define sqlite3_create_module 0
92733 # define sqlite3_create_module_v2 0
92734 # define sqlite3_declare_vtab 0
92735 # define sqlite3_vtab_config 0
92736 # define sqlite3_vtab_on_conflict 0
92737 #endif
92738
92739 #ifdef SQLITE_OMIT_SHARED_CACHE
92740 # define sqlite3_enable_shared_cache 0
92741 #endif
92742
92743 #ifdef SQLITE_OMIT_TRACE
92744 # define sqlite3_profile       0
92745 # define sqlite3_trace         0
92746 #endif
92747
92748 #ifdef SQLITE_OMIT_GET_TABLE
92749 # define sqlite3_free_table    0
92750 # define sqlite3_get_table     0
92751 #endif
92752
92753 #ifdef SQLITE_OMIT_INCRBLOB
92754 #define sqlite3_bind_zeroblob  0
92755 #define sqlite3_blob_bytes     0
92756 #define sqlite3_blob_close     0
92757 #define sqlite3_blob_open      0
92758 #define sqlite3_blob_read      0
92759 #define sqlite3_blob_write     0
92760 #define sqlite3_blob_reopen    0
92761 #endif
92762
92763 /*
92764 ** The following structure contains pointers to all SQLite API routines.
92765 ** A pointer to this structure is passed into extensions when they are
92766 ** loaded so that the extension can make calls back into the SQLite
92767 ** library.
92768 **
92769 ** When adding new APIs, add them to the bottom of this structure
92770 ** in order to preserve backwards compatibility.
92771 **
92772 ** Extensions that use newer APIs should first call the
92773 ** sqlite3_libversion_number() to make sure that the API they
92774 ** intend to use is supported by the library.  Extensions should
92775 ** also check to make sure that the pointer to the function is
92776 ** not NULL before calling it.
92777 */
92778 static const sqlite3_api_routines sqlite3Apis = {
92779   sqlite3_aggregate_context,
92780 #ifndef SQLITE_OMIT_DEPRECATED
92781   sqlite3_aggregate_count,
92782 #else
92783   0,
92784 #endif
92785   sqlite3_bind_blob,
92786   sqlite3_bind_double,
92787   sqlite3_bind_int,
92788   sqlite3_bind_int64,
92789   sqlite3_bind_null,
92790   sqlite3_bind_parameter_count,
92791   sqlite3_bind_parameter_index,
92792   sqlite3_bind_parameter_name,
92793   sqlite3_bind_text,
92794   sqlite3_bind_text16,
92795   sqlite3_bind_value,
92796   sqlite3_busy_handler,
92797   sqlite3_busy_timeout,
92798   sqlite3_changes,
92799   sqlite3_close,
92800   sqlite3_collation_needed,
92801   sqlite3_collation_needed16,
92802   sqlite3_column_blob,
92803   sqlite3_column_bytes,
92804   sqlite3_column_bytes16,
92805   sqlite3_column_count,
92806   sqlite3_column_database_name,
92807   sqlite3_column_database_name16,
92808   sqlite3_column_decltype,
92809   sqlite3_column_decltype16,
92810   sqlite3_column_double,
92811   sqlite3_column_int,
92812   sqlite3_column_int64,
92813   sqlite3_column_name,
92814   sqlite3_column_name16,
92815   sqlite3_column_origin_name,
92816   sqlite3_column_origin_name16,
92817   sqlite3_column_table_name,
92818   sqlite3_column_table_name16,
92819   sqlite3_column_text,
92820   sqlite3_column_text16,
92821   sqlite3_column_type,
92822   sqlite3_column_value,
92823   sqlite3_commit_hook,
92824   sqlite3_complete,
92825   sqlite3_complete16,
92826   sqlite3_create_collation,
92827   sqlite3_create_collation16,
92828   sqlite3_create_function,
92829   sqlite3_create_function16,
92830   sqlite3_create_module,
92831   sqlite3_data_count,
92832   sqlite3_db_handle,
92833   sqlite3_declare_vtab,
92834   sqlite3_enable_shared_cache,
92835   sqlite3_errcode,
92836   sqlite3_errmsg,
92837   sqlite3_errmsg16,
92838   sqlite3_exec,
92839 #ifndef SQLITE_OMIT_DEPRECATED
92840   sqlite3_expired,
92841 #else
92842   0,
92843 #endif
92844   sqlite3_finalize,
92845   sqlite3_free,
92846   sqlite3_free_table,
92847   sqlite3_get_autocommit,
92848   sqlite3_get_auxdata,
92849   sqlite3_get_table,
92850   0,     /* Was sqlite3_global_recover(), but that function is deprecated */
92851   sqlite3_interrupt,
92852   sqlite3_last_insert_rowid,
92853   sqlite3_libversion,
92854   sqlite3_libversion_number,
92855   sqlite3_malloc,
92856   sqlite3_mprintf,
92857   sqlite3_open,
92858   sqlite3_open16,
92859   sqlite3_prepare,
92860   sqlite3_prepare16,
92861   sqlite3_profile,
92862   sqlite3_progress_handler,
92863   sqlite3_realloc,
92864   sqlite3_reset,
92865   sqlite3_result_blob,
92866   sqlite3_result_double,
92867   sqlite3_result_error,
92868   sqlite3_result_error16,
92869   sqlite3_result_int,
92870   sqlite3_result_int64,
92871   sqlite3_result_null,
92872   sqlite3_result_text,
92873   sqlite3_result_text16,
92874   sqlite3_result_text16be,
92875   sqlite3_result_text16le,
92876   sqlite3_result_value,
92877   sqlite3_rollback_hook,
92878   sqlite3_set_authorizer,
92879   sqlite3_set_auxdata,
92880   sqlite3_snprintf,
92881   sqlite3_step,
92882   sqlite3_table_column_metadata,
92883 #ifndef SQLITE_OMIT_DEPRECATED
92884   sqlite3_thread_cleanup,
92885 #else
92886   0,
92887 #endif
92888   sqlite3_total_changes,
92889   sqlite3_trace,
92890 #ifndef SQLITE_OMIT_DEPRECATED
92891   sqlite3_transfer_bindings,
92892 #else
92893   0,
92894 #endif
92895   sqlite3_update_hook,
92896   sqlite3_user_data,
92897   sqlite3_value_blob,
92898   sqlite3_value_bytes,
92899   sqlite3_value_bytes16,
92900   sqlite3_value_double,
92901   sqlite3_value_int,
92902   sqlite3_value_int64,
92903   sqlite3_value_numeric_type,
92904   sqlite3_value_text,
92905   sqlite3_value_text16,
92906   sqlite3_value_text16be,
92907   sqlite3_value_text16le,
92908   sqlite3_value_type,
92909   sqlite3_vmprintf,
92910   /*
92911   ** The original API set ends here.  All extensions can call any
92912   ** of the APIs above provided that the pointer is not NULL.  But
92913   ** before calling APIs that follow, extension should check the
92914   ** sqlite3_libversion_number() to make sure they are dealing with
92915   ** a library that is new enough to support that API.
92916   *************************************************************************
92917   */
92918   sqlite3_overload_function,
92919
92920   /*
92921   ** Added after 3.3.13
92922   */
92923   sqlite3_prepare_v2,
92924   sqlite3_prepare16_v2,
92925   sqlite3_clear_bindings,
92926
92927   /*
92928   ** Added for 3.4.1
92929   */
92930   sqlite3_create_module_v2,
92931
92932   /*
92933   ** Added for 3.5.0
92934   */
92935   sqlite3_bind_zeroblob,
92936   sqlite3_blob_bytes,
92937   sqlite3_blob_close,
92938   sqlite3_blob_open,
92939   sqlite3_blob_read,
92940   sqlite3_blob_write,
92941   sqlite3_create_collation_v2,
92942   sqlite3_file_control,
92943   sqlite3_memory_highwater,
92944   sqlite3_memory_used,
92945 #ifdef SQLITE_MUTEX_OMIT
92946   0, 
92947   0, 
92948   0,
92949   0,
92950   0,
92951 #else
92952   sqlite3_mutex_alloc,
92953   sqlite3_mutex_enter,
92954   sqlite3_mutex_free,
92955   sqlite3_mutex_leave,
92956   sqlite3_mutex_try,
92957 #endif
92958   sqlite3_open_v2,
92959   sqlite3_release_memory,
92960   sqlite3_result_error_nomem,
92961   sqlite3_result_error_toobig,
92962   sqlite3_sleep,
92963   sqlite3_soft_heap_limit,
92964   sqlite3_vfs_find,
92965   sqlite3_vfs_register,
92966   sqlite3_vfs_unregister,
92967
92968   /*
92969   ** Added for 3.5.8
92970   */
92971   sqlite3_threadsafe,
92972   sqlite3_result_zeroblob,
92973   sqlite3_result_error_code,
92974   sqlite3_test_control,
92975   sqlite3_randomness,
92976   sqlite3_context_db_handle,
92977
92978   /*
92979   ** Added for 3.6.0
92980   */
92981   sqlite3_extended_result_codes,
92982   sqlite3_limit,
92983   sqlite3_next_stmt,
92984   sqlite3_sql,
92985   sqlite3_status,
92986
92987   /*
92988   ** Added for 3.7.4
92989   */
92990   sqlite3_backup_finish,
92991   sqlite3_backup_init,
92992   sqlite3_backup_pagecount,
92993   sqlite3_backup_remaining,
92994   sqlite3_backup_step,
92995 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
92996   sqlite3_compileoption_get,
92997   sqlite3_compileoption_used,
92998 #else
92999   0,
93000   0,
93001 #endif
93002   sqlite3_create_function_v2,
93003   sqlite3_db_config,
93004   sqlite3_db_mutex,
93005   sqlite3_db_status,
93006   sqlite3_extended_errcode,
93007   sqlite3_log,
93008   sqlite3_soft_heap_limit64,
93009   sqlite3_sourceid,
93010   sqlite3_stmt_status,
93011   sqlite3_strnicmp,
93012 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
93013   sqlite3_unlock_notify,
93014 #else
93015   0,
93016 #endif
93017 #ifndef SQLITE_OMIT_WAL
93018   sqlite3_wal_autocheckpoint,
93019   sqlite3_wal_checkpoint,
93020   sqlite3_wal_hook,
93021 #else
93022   0,
93023   0,
93024   0,
93025 #endif
93026   sqlite3_blob_reopen,
93027   sqlite3_vtab_config,
93028   sqlite3_vtab_on_conflict,
93029   sqlite3_close_v2,
93030   sqlite3_db_filename,
93031   sqlite3_db_readonly,
93032   sqlite3_db_release_memory,
93033   sqlite3_errstr,
93034   sqlite3_stmt_busy,
93035   sqlite3_stmt_readonly,
93036   sqlite3_stricmp,
93037   sqlite3_uri_boolean,
93038   sqlite3_uri_int64,
93039   sqlite3_uri_parameter,
93040   sqlite3_vsnprintf,
93041   sqlite3_wal_checkpoint_v2
93042 };
93043
93044 /*
93045 ** Attempt to load an SQLite extension library contained in the file
93046 ** zFile.  The entry point is zProc.  zProc may be 0 in which case a
93047 ** default entry point name (sqlite3_extension_init) is used.  Use
93048 ** of the default name is recommended.
93049 **
93050 ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
93051 **
93052 ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with 
93053 ** error message text.  The calling function should free this memory
93054 ** by calling sqlite3DbFree(db, ).
93055 */
93056 static int sqlite3LoadExtension(
93057   sqlite3 *db,          /* Load the extension into this database connection */
93058   const char *zFile,    /* Name of the shared library containing extension */
93059   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
93060   char **pzErrMsg       /* Put error message here if not 0 */
93061 ){
93062   sqlite3_vfs *pVfs = db->pVfs;
93063   void *handle;
93064   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
93065   char *zErrmsg = 0;
93066   const char *zEntry;
93067   char *zAltEntry = 0;
93068   void **aHandle;
93069   int nMsg = 300 + sqlite3Strlen30(zFile);
93070   int ii;
93071
93072   /* Shared library endings to try if zFile cannot be loaded as written */
93073   static const char *azEndings[] = {
93074 #if SQLITE_OS_WIN
93075      "dll"   
93076 #elif defined(__APPLE__)
93077      "dylib"
93078 #else
93079      "so"
93080 #endif
93081   };
93082
93083
93084   if( pzErrMsg ) *pzErrMsg = 0;
93085
93086   /* Ticket #1863.  To avoid a creating security problems for older
93087   ** applications that relink against newer versions of SQLite, the
93088   ** ability to run load_extension is turned off by default.  One
93089   ** must call sqlite3_enable_load_extension() to turn on extension
93090   ** loading.  Otherwise you get the following error.
93091   */
93092   if( (db->flags & SQLITE_LoadExtension)==0 ){
93093     if( pzErrMsg ){
93094       *pzErrMsg = sqlite3_mprintf("not authorized");
93095     }
93096     return SQLITE_ERROR;
93097   }
93098
93099   zEntry = zProc ? zProc : "sqlite3_extension_init";
93100
93101   handle = sqlite3OsDlOpen(pVfs, zFile);
93102 #if SQLITE_OS_UNIX || SQLITE_OS_WIN
93103   for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
93104     char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
93105     if( zAltFile==0 ) return SQLITE_NOMEM;
93106     handle = sqlite3OsDlOpen(pVfs, zAltFile);
93107     sqlite3_free(zAltFile);
93108   }
93109 #endif
93110   if( handle==0 ){
93111     if( pzErrMsg ){
93112       *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
93113       if( zErrmsg ){
93114         sqlite3_snprintf(nMsg, zErrmsg, 
93115             "unable to open shared library [%s]", zFile);
93116         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
93117       }
93118     }
93119     return SQLITE_ERROR;
93120   }
93121   xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
93122                    sqlite3OsDlSym(pVfs, handle, zEntry);
93123
93124   /* If no entry point was specified and the default legacy
93125   ** entry point name "sqlite3_extension_init" was not found, then
93126   ** construct an entry point name "sqlite3_X_init" where the X is
93127   ** replaced by the lowercase value of every ASCII alphabetic 
93128   ** character in the filename after the last "/" upto the first ".",
93129   ** and eliding the first three characters if they are "lib".  
93130   ** Examples:
93131   **
93132   **    /usr/local/lib/libExample5.4.3.so ==>  sqlite3_example_init
93133   **    C:/lib/mathfuncs.dll              ==>  sqlite3_mathfuncs_init
93134   */
93135   if( xInit==0 && zProc==0 ){
93136     int iFile, iEntry, c;
93137     int ncFile = sqlite3Strlen30(zFile);
93138     zAltEntry = sqlite3_malloc(ncFile+30);
93139     if( zAltEntry==0 ){
93140       sqlite3OsDlClose(pVfs, handle);
93141       return SQLITE_NOMEM;
93142     }
93143     memcpy(zAltEntry, "sqlite3_", 8);
93144     for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){}
93145     iFile++;
93146     if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
93147     for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
93148       if( sqlite3Isalpha(c) ){
93149         zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
93150       }
93151     }
93152     memcpy(zAltEntry+iEntry, "_init", 6);
93153     zEntry = zAltEntry;
93154     xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
93155                      sqlite3OsDlSym(pVfs, handle, zEntry);
93156   }
93157   if( xInit==0 ){
93158     if( pzErrMsg ){
93159       nMsg += sqlite3Strlen30(zEntry);
93160       *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
93161       if( zErrmsg ){
93162         sqlite3_snprintf(nMsg, zErrmsg,
93163             "no entry point [%s] in shared library [%s]", zEntry, zFile);
93164         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
93165       }
93166     }
93167     sqlite3OsDlClose(pVfs, handle);
93168     sqlite3_free(zAltEntry);
93169     return SQLITE_ERROR;
93170   }
93171   sqlite3_free(zAltEntry);
93172   if( xInit(db, &zErrmsg, &sqlite3Apis) ){
93173     if( pzErrMsg ){
93174       *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
93175     }
93176     sqlite3_free(zErrmsg);
93177     sqlite3OsDlClose(pVfs, handle);
93178     return SQLITE_ERROR;
93179   }
93180
93181   /* Append the new shared library handle to the db->aExtension array. */
93182   aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
93183   if( aHandle==0 ){
93184     return SQLITE_NOMEM;
93185   }
93186   if( db->nExtension>0 ){
93187     memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
93188   }
93189   sqlite3DbFree(db, db->aExtension);
93190   db->aExtension = aHandle;
93191
93192   db->aExtension[db->nExtension++] = handle;
93193   return SQLITE_OK;
93194 }
93195 SQLITE_API int sqlite3_load_extension(
93196   sqlite3 *db,          /* Load the extension into this database connection */
93197   const char *zFile,    /* Name of the shared library containing extension */
93198   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
93199   char **pzErrMsg       /* Put error message here if not 0 */
93200 ){
93201   int rc;
93202   sqlite3_mutex_enter(db->mutex);
93203   rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
93204   rc = sqlite3ApiExit(db, rc);
93205   sqlite3_mutex_leave(db->mutex);
93206   return rc;
93207 }
93208
93209 /*
93210 ** Call this routine when the database connection is closing in order
93211 ** to clean up loaded extensions
93212 */
93213 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
93214   int i;
93215   assert( sqlite3_mutex_held(db->mutex) );
93216   for(i=0; i<db->nExtension; i++){
93217     sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
93218   }
93219   sqlite3DbFree(db, db->aExtension);
93220 }
93221
93222 /*
93223 ** Enable or disable extension loading.  Extension loading is disabled by
93224 ** default so as not to open security holes in older applications.
93225 */
93226 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
93227   sqlite3_mutex_enter(db->mutex);
93228   if( onoff ){
93229     db->flags |= SQLITE_LoadExtension;
93230   }else{
93231     db->flags &= ~SQLITE_LoadExtension;
93232   }
93233   sqlite3_mutex_leave(db->mutex);
93234   return SQLITE_OK;
93235 }
93236
93237 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
93238
93239 /*
93240 ** The auto-extension code added regardless of whether or not extension
93241 ** loading is supported.  We need a dummy sqlite3Apis pointer for that
93242 ** code if regular extension loading is not available.  This is that
93243 ** dummy pointer.
93244 */
93245 #ifdef SQLITE_OMIT_LOAD_EXTENSION
93246 static const sqlite3_api_routines sqlite3Apis = { 0 };
93247 #endif
93248
93249
93250 /*
93251 ** The following object holds the list of automatically loaded
93252 ** extensions.
93253 **
93254 ** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
93255 ** mutex must be held while accessing this list.
93256 */
93257 typedef struct sqlite3AutoExtList sqlite3AutoExtList;
93258 static SQLITE_WSD struct sqlite3AutoExtList {
93259   int nExt;              /* Number of entries in aExt[] */          
93260   void (**aExt)(void);   /* Pointers to the extension init functions */
93261 } sqlite3Autoext = { 0, 0 };
93262
93263 /* The "wsdAutoext" macro will resolve to the autoextension
93264 ** state vector.  If writable static data is unsupported on the target,
93265 ** we have to locate the state vector at run-time.  In the more common
93266 ** case where writable static data is supported, wsdStat can refer directly
93267 ** to the "sqlite3Autoext" state vector declared above.
93268 */
93269 #ifdef SQLITE_OMIT_WSD
93270 # define wsdAutoextInit \
93271   sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
93272 # define wsdAutoext x[0]
93273 #else
93274 # define wsdAutoextInit
93275 # define wsdAutoext sqlite3Autoext
93276 #endif
93277
93278
93279 /*
93280 ** Register a statically linked extension that is automatically
93281 ** loaded by every new database connection.
93282 */
93283 SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
93284   int rc = SQLITE_OK;
93285 #ifndef SQLITE_OMIT_AUTOINIT
93286   rc = sqlite3_initialize();
93287   if( rc ){
93288     return rc;
93289   }else
93290 #endif
93291   {
93292     int i;
93293 #if SQLITE_THREADSAFE
93294     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
93295 #endif
93296     wsdAutoextInit;
93297     sqlite3_mutex_enter(mutex);
93298     for(i=0; i<wsdAutoext.nExt; i++){
93299       if( wsdAutoext.aExt[i]==xInit ) break;
93300     }
93301     if( i==wsdAutoext.nExt ){
93302       int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
93303       void (**aNew)(void);
93304       aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
93305       if( aNew==0 ){
93306         rc = SQLITE_NOMEM;
93307       }else{
93308         wsdAutoext.aExt = aNew;
93309         wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
93310         wsdAutoext.nExt++;
93311       }
93312     }
93313     sqlite3_mutex_leave(mutex);
93314     assert( (rc&0xff)==rc );
93315     return rc;
93316   }
93317 }
93318
93319 /*
93320 ** Reset the automatic extension loading mechanism.
93321 */
93322 SQLITE_API void sqlite3_reset_auto_extension(void){
93323 #ifndef SQLITE_OMIT_AUTOINIT
93324   if( sqlite3_initialize()==SQLITE_OK )
93325 #endif
93326   {
93327 #if SQLITE_THREADSAFE
93328     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
93329 #endif
93330     wsdAutoextInit;
93331     sqlite3_mutex_enter(mutex);
93332     sqlite3_free(wsdAutoext.aExt);
93333     wsdAutoext.aExt = 0;
93334     wsdAutoext.nExt = 0;
93335     sqlite3_mutex_leave(mutex);
93336   }
93337 }
93338
93339 /*
93340 ** Load all automatic extensions.
93341 **
93342 ** If anything goes wrong, set an error in the database connection.
93343 */
93344 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
93345   int i;
93346   int go = 1;
93347   int rc;
93348   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
93349
93350   wsdAutoextInit;
93351   if( wsdAutoext.nExt==0 ){
93352     /* Common case: early out without every having to acquire a mutex */
93353     return;
93354   }
93355   for(i=0; go; i++){
93356     char *zErrmsg;
93357 #if SQLITE_THREADSAFE
93358     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
93359 #endif
93360     sqlite3_mutex_enter(mutex);
93361     if( i>=wsdAutoext.nExt ){
93362       xInit = 0;
93363       go = 0;
93364     }else{
93365       xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
93366               wsdAutoext.aExt[i];
93367     }
93368     sqlite3_mutex_leave(mutex);
93369     zErrmsg = 0;
93370     if( xInit && (rc = xInit(db, &zErrmsg, &sqlite3Apis))!=0 ){
93371       sqlite3Error(db, rc,
93372             "automatic extension loading failed: %s", zErrmsg);
93373       go = 0;
93374     }
93375     sqlite3_free(zErrmsg);
93376   }
93377 }
93378
93379 /************** End of loadext.c *********************************************/
93380 /************** Begin file pragma.c ******************************************/
93381 /*
93382 ** 2003 April 6
93383 **
93384 ** The author disclaims copyright to this source code.  In place of
93385 ** a legal notice, here is a blessing:
93386 **
93387 **    May you do good and not evil.
93388 **    May you find forgiveness for yourself and forgive others.
93389 **    May you share freely, never taking more than you give.
93390 **
93391 *************************************************************************
93392 ** This file contains code used to implement the PRAGMA command.
93393 */
93394
93395 /*
93396 ** Interpret the given string as a safety level.  Return 0 for OFF,
93397 ** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or 
93398 ** unrecognized string argument.  The FULL option is disallowed
93399 ** if the omitFull parameter it 1.
93400 **
93401 ** Note that the values returned are one less that the values that
93402 ** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
93403 ** to support legacy SQL code.  The safety level used to be boolean
93404 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
93405 */
93406 static u8 getSafetyLevel(const char *z, int omitFull, int dflt){
93407                              /* 123456789 123456789 */
93408   static const char zText[] = "onoffalseyestruefull";
93409   static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
93410   static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
93411   static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
93412   int i, n;
93413   if( sqlite3Isdigit(*z) ){
93414     return (u8)sqlite3Atoi(z);
93415   }
93416   n = sqlite3Strlen30(z);
93417   for(i=0; i<ArraySize(iLength)-omitFull; i++){
93418     if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
93419       return iValue[i];
93420     }
93421   }
93422   return dflt;
93423 }
93424
93425 /*
93426 ** Interpret the given string as a boolean value.
93427 */
93428 SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, int dflt){
93429   return getSafetyLevel(z,1,dflt)!=0;
93430 }
93431
93432 /* The sqlite3GetBoolean() function is used by other modules but the
93433 ** remainder of this file is specific to PRAGMA processing.  So omit
93434 ** the rest of the file if PRAGMAs are omitted from the build.
93435 */
93436 #if !defined(SQLITE_OMIT_PRAGMA)
93437
93438 /*
93439 ** Interpret the given string as a locking mode value.
93440 */
93441 static int getLockingMode(const char *z){
93442   if( z ){
93443     if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
93444     if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
93445   }
93446   return PAGER_LOCKINGMODE_QUERY;
93447 }
93448
93449 #ifndef SQLITE_OMIT_AUTOVACUUM
93450 /*
93451 ** Interpret the given string as an auto-vacuum mode value.
93452 **
93453 ** The following strings, "none", "full" and "incremental" are 
93454 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
93455 */
93456 static int getAutoVacuum(const char *z){
93457   int i;
93458   if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
93459   if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
93460   if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
93461   i = sqlite3Atoi(z);
93462   return (u8)((i>=0&&i<=2)?i:0);
93463 }
93464 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
93465
93466 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
93467 /*
93468 ** Interpret the given string as a temp db location. Return 1 for file
93469 ** backed temporary databases, 2 for the Red-Black tree in memory database
93470 ** and 0 to use the compile-time default.
93471 */
93472 static int getTempStore(const char *z){
93473   if( z[0]>='0' && z[0]<='2' ){
93474     return z[0] - '0';
93475   }else if( sqlite3StrICmp(z, "file")==0 ){
93476     return 1;
93477   }else if( sqlite3StrICmp(z, "memory")==0 ){
93478     return 2;
93479   }else{
93480     return 0;
93481   }
93482 }
93483 #endif /* SQLITE_PAGER_PRAGMAS */
93484
93485 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
93486 /*
93487 ** Invalidate temp storage, either when the temp storage is changed
93488 ** from default, or when 'file' and the temp_store_directory has changed
93489 */
93490 static int invalidateTempStorage(Parse *pParse){
93491   sqlite3 *db = pParse->db;
93492   if( db->aDb[1].pBt!=0 ){
93493     if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
93494       sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
93495         "from within a transaction");
93496       return SQLITE_ERROR;
93497     }
93498     sqlite3BtreeClose(db->aDb[1].pBt);
93499     db->aDb[1].pBt = 0;
93500     sqlite3ResetAllSchemasOfConnection(db);
93501   }
93502   return SQLITE_OK;
93503 }
93504 #endif /* SQLITE_PAGER_PRAGMAS */
93505
93506 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
93507 /*
93508 ** If the TEMP database is open, close it and mark the database schema
93509 ** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
93510 ** or DEFAULT_TEMP_STORE pragmas.
93511 */
93512 static int changeTempStorage(Parse *pParse, const char *zStorageType){
93513   int ts = getTempStore(zStorageType);
93514   sqlite3 *db = pParse->db;
93515   if( db->temp_store==ts ) return SQLITE_OK;
93516   if( invalidateTempStorage( pParse ) != SQLITE_OK ){
93517     return SQLITE_ERROR;
93518   }
93519   db->temp_store = (u8)ts;
93520   return SQLITE_OK;
93521 }
93522 #endif /* SQLITE_PAGER_PRAGMAS */
93523
93524 /*
93525 ** Generate code to return a single integer value.
93526 */
93527 static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
93528   Vdbe *v = sqlite3GetVdbe(pParse);
93529   int mem = ++pParse->nMem;
93530   i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
93531   if( pI64 ){
93532     memcpy(pI64, &value, sizeof(value));
93533   }
93534   sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
93535   sqlite3VdbeSetNumCols(v, 1);
93536   sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
93537   sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
93538 }
93539
93540 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
93541 /*
93542 ** Check to see if zRight and zLeft refer to a pragma that queries
93543 ** or changes one of the flags in db->flags.  Return 1 if so and 0 if not.
93544 ** Also, implement the pragma.
93545 */
93546 static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
93547   static const struct sPragmaType {
93548     const char *zName;  /* Name of the pragma */
93549     int mask;           /* Mask for the db->flags value */
93550   } aPragma[] = {
93551     { "full_column_names",        SQLITE_FullColNames  },
93552     { "short_column_names",       SQLITE_ShortColNames },
93553     { "count_changes",            SQLITE_CountRows     },
93554     { "empty_result_callbacks",   SQLITE_NullCallback  },
93555     { "legacy_file_format",       SQLITE_LegacyFileFmt },
93556     { "fullfsync",                SQLITE_FullFSync     },
93557     { "checkpoint_fullfsync",     SQLITE_CkptFullFSync },
93558     { "reverse_unordered_selects", SQLITE_ReverseOrder  },
93559 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
93560     { "automatic_index",          SQLITE_AutoIndex     },
93561 #endif
93562 #ifdef SQLITE_DEBUG
93563     { "sql_trace",                SQLITE_SqlTrace      },
93564     { "vdbe_listing",             SQLITE_VdbeListing   },
93565     { "vdbe_trace",               SQLITE_VdbeTrace     },
93566     { "vdbe_addoptrace",          SQLITE_VdbeAddopTrace},
93567     { "vdbe_debug",    SQLITE_SqlTrace | SQLITE_VdbeListing
93568                                | SQLITE_VdbeTrace      },
93569 #endif
93570 #ifndef SQLITE_OMIT_CHECK
93571     { "ignore_check_constraints", SQLITE_IgnoreChecks  },
93572 #endif
93573     /* The following is VERY experimental */
93574     { "writable_schema",          SQLITE_WriteSchema|SQLITE_RecoveryMode },
93575
93576     /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
93577     ** flag if there are any active statements. */
93578     { "read_uncommitted",         SQLITE_ReadUncommitted },
93579     { "recursive_triggers",       SQLITE_RecTriggers },
93580
93581     /* This flag may only be set if both foreign-key and trigger support
93582     ** are present in the build.  */
93583 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
93584     { "foreign_keys",             SQLITE_ForeignKeys },
93585 #endif
93586   };
93587   int i;
93588   const struct sPragmaType *p;
93589   for(i=0, p=aPragma; i<ArraySize(aPragma); i++, p++){
93590     if( sqlite3StrICmp(zLeft, p->zName)==0 ){
93591       sqlite3 *db = pParse->db;
93592       Vdbe *v;
93593       v = sqlite3GetVdbe(pParse);
93594       assert( v!=0 );  /* Already allocated by sqlite3Pragma() */
93595       if( ALWAYS(v) ){
93596         if( zRight==0 ){
93597           returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
93598         }else{
93599           int mask = p->mask;          /* Mask of bits to set or clear. */
93600           if( db->autoCommit==0 ){
93601             /* Foreign key support may not be enabled or disabled while not
93602             ** in auto-commit mode.  */
93603             mask &= ~(SQLITE_ForeignKeys);
93604           }
93605
93606           if( sqlite3GetBoolean(zRight, 0) ){
93607             db->flags |= mask;
93608           }else{
93609             db->flags &= ~mask;
93610           }
93611
93612           /* Many of the flag-pragmas modify the code generated by the SQL 
93613           ** compiler (eg. count_changes). So add an opcode to expire all
93614           ** compiled SQL statements after modifying a pragma value.
93615           */
93616           sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
93617         }
93618       }
93619
93620       return 1;
93621     }
93622   }
93623   return 0;
93624 }
93625 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
93626
93627 /*
93628 ** Return a human-readable name for a constraint resolution action.
93629 */
93630 #ifndef SQLITE_OMIT_FOREIGN_KEY
93631 static const char *actionName(u8 action){
93632   const char *zName;
93633   switch( action ){
93634     case OE_SetNull:  zName = "SET NULL";        break;
93635     case OE_SetDflt:  zName = "SET DEFAULT";     break;
93636     case OE_Cascade:  zName = "CASCADE";         break;
93637     case OE_Restrict: zName = "RESTRICT";        break;
93638     default:          zName = "NO ACTION";  
93639                       assert( action==OE_None ); break;
93640   }
93641   return zName;
93642 }
93643 #endif
93644
93645
93646 /*
93647 ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
93648 ** defined in pager.h. This function returns the associated lowercase
93649 ** journal-mode name.
93650 */
93651 SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
93652   static char * const azModeName[] = {
93653     "delete", "persist", "off", "truncate", "memory"
93654 #ifndef SQLITE_OMIT_WAL
93655      , "wal"
93656 #endif
93657   };
93658   assert( PAGER_JOURNALMODE_DELETE==0 );
93659   assert( PAGER_JOURNALMODE_PERSIST==1 );
93660   assert( PAGER_JOURNALMODE_OFF==2 );
93661   assert( PAGER_JOURNALMODE_TRUNCATE==3 );
93662   assert( PAGER_JOURNALMODE_MEMORY==4 );
93663   assert( PAGER_JOURNALMODE_WAL==5 );
93664   assert( eMode>=0 && eMode<=ArraySize(azModeName) );
93665
93666   if( eMode==ArraySize(azModeName) ) return 0;
93667   return azModeName[eMode];
93668 }
93669
93670 /*
93671 ** Process a pragma statement.  
93672 **
93673 ** Pragmas are of this form:
93674 **
93675 **      PRAGMA [database.]id [= value]
93676 **
93677 ** The identifier might also be a string.  The value is a string, and
93678 ** identifier, or a number.  If minusFlag is true, then the value is
93679 ** a number that was preceded by a minus sign.
93680 **
93681 ** If the left side is "database.id" then pId1 is the database name
93682 ** and pId2 is the id.  If the left side is just "id" then pId1 is the
93683 ** id and pId2 is any empty string.
93684 */
93685 SQLITE_PRIVATE void sqlite3Pragma(
93686   Parse *pParse, 
93687   Token *pId1,        /* First part of [database.]id field */
93688   Token *pId2,        /* Second part of [database.]id field, or NULL */
93689   Token *pValue,      /* Token for <value>, or NULL */
93690   int minusFlag       /* True if a '-' sign preceded <value> */
93691 ){
93692   char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
93693   char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
93694   const char *zDb = 0;   /* The database name */
93695   Token *pId;            /* Pointer to <id> token */
93696   int iDb;               /* Database index for <database> */
93697   char *aFcntl[4];       /* Argument to SQLITE_FCNTL_PRAGMA */
93698   int rc;                      /* return value form SQLITE_FCNTL_PRAGMA */
93699   sqlite3 *db = pParse->db;    /* The database connection */
93700   Db *pDb;                     /* The specific database being pragmaed */
93701   Vdbe *v = sqlite3GetVdbe(pParse);  /* Prepared statement */
93702
93703   if( v==0 ) return;
93704   sqlite3VdbeRunOnlyOnce(v);
93705   pParse->nMem = 2;
93706
93707   /* Interpret the [database.] part of the pragma statement. iDb is the
93708   ** index of the database this pragma is being applied to in db.aDb[]. */
93709   iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
93710   if( iDb<0 ) return;
93711   pDb = &db->aDb[iDb];
93712
93713   /* If the temp database has been explicitly named as part of the 
93714   ** pragma, make sure it is open. 
93715   */
93716   if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
93717     return;
93718   }
93719
93720   zLeft = sqlite3NameFromToken(db, pId);
93721   if( !zLeft ) return;
93722   if( minusFlag ){
93723     zRight = sqlite3MPrintf(db, "-%T", pValue);
93724   }else{
93725     zRight = sqlite3NameFromToken(db, pValue);
93726   }
93727
93728   assert( pId2 );
93729   zDb = pId2->n>0 ? pDb->zName : 0;
93730   if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
93731     goto pragma_out;
93732   }
93733
93734   /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
93735   ** connection.  If it returns SQLITE_OK, then assume that the VFS
93736   ** handled the pragma and generate a no-op prepared statement.
93737   */
93738   aFcntl[0] = 0;
93739   aFcntl[1] = zLeft;
93740   aFcntl[2] = zRight;
93741   aFcntl[3] = 0;
93742   db->busyHandler.nBusy = 0;
93743   rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
93744   if( rc==SQLITE_OK ){
93745     if( aFcntl[0] ){
93746       int mem = ++pParse->nMem;
93747       sqlite3VdbeAddOp4(v, OP_String8, 0, mem, 0, aFcntl[0], 0);
93748       sqlite3VdbeSetNumCols(v, 1);
93749       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "result", SQLITE_STATIC);
93750       sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
93751       sqlite3_free(aFcntl[0]);
93752     }
93753   }else if( rc!=SQLITE_NOTFOUND ){
93754     if( aFcntl[0] ){
93755       sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
93756       sqlite3_free(aFcntl[0]);
93757     }
93758     pParse->nErr++;
93759     pParse->rc = rc;
93760   }else
93761                             
93762  
93763 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
93764   /*
93765   **  PRAGMA [database.]default_cache_size
93766   **  PRAGMA [database.]default_cache_size=N
93767   **
93768   ** The first form reports the current persistent setting for the
93769   ** page cache size.  The value returned is the maximum number of
93770   ** pages in the page cache.  The second form sets both the current
93771   ** page cache size value and the persistent page cache size value
93772   ** stored in the database file.
93773   **
93774   ** Older versions of SQLite would set the default cache size to a
93775   ** negative number to indicate synchronous=OFF.  These days, synchronous
93776   ** is always on by default regardless of the sign of the default cache
93777   ** size.  But continue to take the absolute value of the default cache
93778   ** size of historical compatibility.
93779   */
93780   if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
93781     static const VdbeOpList getCacheSize[] = {
93782       { OP_Transaction, 0, 0,        0},                         /* 0 */
93783       { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
93784       { OP_IfPos,       1, 8,        0},
93785       { OP_Integer,     0, 2,        0},
93786       { OP_Subtract,    1, 2,        1},
93787       { OP_IfPos,       1, 8,        0},
93788       { OP_Integer,     0, 1,        0},                         /* 6 */
93789       { OP_Noop,        0, 0,        0},
93790       { OP_ResultRow,   1, 1,        0},
93791     };
93792     int addr;
93793     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
93794     sqlite3VdbeUsesBtree(v, iDb);
93795     if( !zRight ){
93796       sqlite3VdbeSetNumCols(v, 1);
93797       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
93798       pParse->nMem += 2;
93799       addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
93800       sqlite3VdbeChangeP1(v, addr, iDb);
93801       sqlite3VdbeChangeP1(v, addr+1, iDb);
93802       sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
93803     }else{
93804       int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
93805       sqlite3BeginWriteOperation(pParse, 0, iDb);
93806       sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
93807       sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
93808       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
93809       pDb->pSchema->cache_size = size;
93810       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
93811     }
93812   }else
93813 #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
93814
93815 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
93816   /*
93817   **  PRAGMA [database.]page_size
93818   **  PRAGMA [database.]page_size=N
93819   **
93820   ** The first form reports the current setting for the
93821   ** database page size in bytes.  The second form sets the
93822   ** database page size value.  The value can only be set if
93823   ** the database has not yet been created.
93824   */
93825   if( sqlite3StrICmp(zLeft,"page_size")==0 ){
93826     Btree *pBt = pDb->pBt;
93827     assert( pBt!=0 );
93828     if( !zRight ){
93829       int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
93830       returnSingleInt(pParse, "page_size", size);
93831     }else{
93832       /* Malloc may fail when setting the page-size, as there is an internal
93833       ** buffer that the pager module resizes using sqlite3_realloc().
93834       */
93835       db->nextPagesize = sqlite3Atoi(zRight);
93836       if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
93837         db->mallocFailed = 1;
93838       }
93839     }
93840   }else
93841
93842   /*
93843   **  PRAGMA [database.]secure_delete
93844   **  PRAGMA [database.]secure_delete=ON/OFF
93845   **
93846   ** The first form reports the current setting for the
93847   ** secure_delete flag.  The second form changes the secure_delete
93848   ** flag setting and reports thenew value.
93849   */
93850   if( sqlite3StrICmp(zLeft,"secure_delete")==0 ){
93851     Btree *pBt = pDb->pBt;
93852     int b = -1;
93853     assert( pBt!=0 );
93854     if( zRight ){
93855       b = sqlite3GetBoolean(zRight, 0);
93856     }
93857     if( pId2->n==0 && b>=0 ){
93858       int ii;
93859       for(ii=0; ii<db->nDb; ii++){
93860         sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
93861       }
93862     }
93863     b = sqlite3BtreeSecureDelete(pBt, b);
93864     returnSingleInt(pParse, "secure_delete", b);
93865   }else
93866
93867   /*
93868   **  PRAGMA [database.]max_page_count
93869   **  PRAGMA [database.]max_page_count=N
93870   **
93871   ** The first form reports the current setting for the
93872   ** maximum number of pages in the database file.  The 
93873   ** second form attempts to change this setting.  Both
93874   ** forms return the current setting.
93875   **
93876   ** The absolute value of N is used.  This is undocumented and might
93877   ** change.  The only purpose is to provide an easy way to test
93878   ** the sqlite3AbsInt32() function.
93879   **
93880   **  PRAGMA [database.]page_count
93881   **
93882   ** Return the number of pages in the specified database.
93883   */
93884   if( sqlite3StrICmp(zLeft,"page_count")==0
93885    || sqlite3StrICmp(zLeft,"max_page_count")==0
93886   ){
93887     int iReg;
93888     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
93889     sqlite3CodeVerifySchema(pParse, iDb);
93890     iReg = ++pParse->nMem;
93891     if( sqlite3Tolower(zLeft[0])=='p' ){
93892       sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
93893     }else{
93894       sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg, 
93895                         sqlite3AbsInt32(sqlite3Atoi(zRight)));
93896     }
93897     sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
93898     sqlite3VdbeSetNumCols(v, 1);
93899     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
93900   }else
93901
93902   /*
93903   **  PRAGMA [database.]locking_mode
93904   **  PRAGMA [database.]locking_mode = (normal|exclusive)
93905   */
93906   if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
93907     const char *zRet = "normal";
93908     int eMode = getLockingMode(zRight);
93909
93910     if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
93911       /* Simple "PRAGMA locking_mode;" statement. This is a query for
93912       ** the current default locking mode (which may be different to
93913       ** the locking-mode of the main database).
93914       */
93915       eMode = db->dfltLockMode;
93916     }else{
93917       Pager *pPager;
93918       if( pId2->n==0 ){
93919         /* This indicates that no database name was specified as part
93920         ** of the PRAGMA command. In this case the locking-mode must be
93921         ** set on all attached databases, as well as the main db file.
93922         **
93923         ** Also, the sqlite3.dfltLockMode variable is set so that
93924         ** any subsequently attached databases also use the specified
93925         ** locking mode.
93926         */
93927         int ii;
93928         assert(pDb==&db->aDb[0]);
93929         for(ii=2; ii<db->nDb; ii++){
93930           pPager = sqlite3BtreePager(db->aDb[ii].pBt);
93931           sqlite3PagerLockingMode(pPager, eMode);
93932         }
93933         db->dfltLockMode = (u8)eMode;
93934       }
93935       pPager = sqlite3BtreePager(pDb->pBt);
93936       eMode = sqlite3PagerLockingMode(pPager, eMode);
93937     }
93938
93939     assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
93940     if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
93941       zRet = "exclusive";
93942     }
93943     sqlite3VdbeSetNumCols(v, 1);
93944     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
93945     sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
93946     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
93947   }else
93948
93949   /*
93950   **  PRAGMA [database.]journal_mode
93951   **  PRAGMA [database.]journal_mode =
93952   **                      (delete|persist|off|truncate|memory|wal|off)
93953   */
93954   if( sqlite3StrICmp(zLeft,"journal_mode")==0 ){
93955     int eMode;        /* One of the PAGER_JOURNALMODE_XXX symbols */
93956     int ii;           /* Loop counter */
93957
93958     /* Force the schema to be loaded on all databases.  This causes all
93959     ** database files to be opened and the journal_modes set.  This is
93960     ** necessary because subsequent processing must know if the databases
93961     ** are in WAL mode. */
93962     if( sqlite3ReadSchema(pParse) ){
93963       goto pragma_out;
93964     }
93965
93966     sqlite3VdbeSetNumCols(v, 1);
93967     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
93968
93969     if( zRight==0 ){
93970       /* If there is no "=MODE" part of the pragma, do a query for the
93971       ** current mode */
93972       eMode = PAGER_JOURNALMODE_QUERY;
93973     }else{
93974       const char *zMode;
93975       int n = sqlite3Strlen30(zRight);
93976       for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
93977         if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
93978       }
93979       if( !zMode ){
93980         /* If the "=MODE" part does not match any known journal mode,
93981         ** then do a query */
93982         eMode = PAGER_JOURNALMODE_QUERY;
93983       }
93984     }
93985     if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
93986       /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
93987       iDb = 0;
93988       pId2->n = 1;
93989     }
93990     for(ii=db->nDb-1; ii>=0; ii--){
93991       if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
93992         sqlite3VdbeUsesBtree(v, ii);
93993         sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
93994       }
93995     }
93996     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
93997   }else
93998
93999   /*
94000   **  PRAGMA [database.]journal_size_limit
94001   **  PRAGMA [database.]journal_size_limit=N
94002   **
94003   ** Get or set the size limit on rollback journal files.
94004   */
94005   if( sqlite3StrICmp(zLeft,"journal_size_limit")==0 ){
94006     Pager *pPager = sqlite3BtreePager(pDb->pBt);
94007     i64 iLimit = -2;
94008     if( zRight ){
94009       sqlite3Atoi64(zRight, &iLimit, 1000000, SQLITE_UTF8);
94010       if( iLimit<-1 ) iLimit = -1;
94011     }
94012     iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
94013     returnSingleInt(pParse, "journal_size_limit", iLimit);
94014   }else
94015
94016 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
94017
94018   /*
94019   **  PRAGMA [database.]auto_vacuum
94020   **  PRAGMA [database.]auto_vacuum=N
94021   **
94022   ** Get or set the value of the database 'auto-vacuum' parameter.
94023   ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
94024   */
94025 #ifndef SQLITE_OMIT_AUTOVACUUM
94026   if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
94027     Btree *pBt = pDb->pBt;
94028     assert( pBt!=0 );
94029     if( sqlite3ReadSchema(pParse) ){
94030       goto pragma_out;
94031     }
94032     if( !zRight ){
94033       int auto_vacuum;
94034       if( ALWAYS(pBt) ){
94035          auto_vacuum = sqlite3BtreeGetAutoVacuum(pBt);
94036       }else{
94037          auto_vacuum = SQLITE_DEFAULT_AUTOVACUUM;
94038       }
94039       returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
94040     }else{
94041       int eAuto = getAutoVacuum(zRight);
94042       assert( eAuto>=0 && eAuto<=2 );
94043       db->nextAutovac = (u8)eAuto;
94044       if( ALWAYS(eAuto>=0) ){
94045         /* Call SetAutoVacuum() to set initialize the internal auto and
94046         ** incr-vacuum flags. This is required in case this connection
94047         ** creates the database file. It is important that it is created
94048         ** as an auto-vacuum capable db.
94049         */
94050         rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
94051         if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
94052           /* When setting the auto_vacuum mode to either "full" or 
94053           ** "incremental", write the value of meta[6] in the database
94054           ** file. Before writing to meta[6], check that meta[3] indicates
94055           ** that this really is an auto-vacuum capable database.
94056           */
94057           static const VdbeOpList setMeta6[] = {
94058             { OP_Transaction,    0,         1,                 0},    /* 0 */
94059             { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
94060             { OP_If,             1,         0,                 0},    /* 2 */
94061             { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
94062             { OP_Integer,        0,         1,                 0},    /* 4 */
94063             { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 1},    /* 5 */
94064           };
94065           int iAddr;
94066           iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
94067           sqlite3VdbeChangeP1(v, iAddr, iDb);
94068           sqlite3VdbeChangeP1(v, iAddr+1, iDb);
94069           sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
94070           sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
94071           sqlite3VdbeChangeP1(v, iAddr+5, iDb);
94072           sqlite3VdbeUsesBtree(v, iDb);
94073         }
94074       }
94075     }
94076   }else
94077 #endif
94078
94079   /*
94080   **  PRAGMA [database.]incremental_vacuum(N)
94081   **
94082   ** Do N steps of incremental vacuuming on a database.
94083   */
94084 #ifndef SQLITE_OMIT_AUTOVACUUM
94085   if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
94086     int iLimit, addr;
94087     if( sqlite3ReadSchema(pParse) ){
94088       goto pragma_out;
94089     }
94090     if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
94091       iLimit = 0x7fffffff;
94092     }
94093     sqlite3BeginWriteOperation(pParse, 0, iDb);
94094     sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
94095     addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
94096     sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
94097     sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
94098     sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
94099     sqlite3VdbeJumpHere(v, addr);
94100   }else
94101 #endif
94102
94103 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
94104   /*
94105   **  PRAGMA [database.]cache_size
94106   **  PRAGMA [database.]cache_size=N
94107   **
94108   ** The first form reports the current local setting for the
94109   ** page cache size. The second form sets the local
94110   ** page cache size value.  If N is positive then that is the
94111   ** number of pages in the cache.  If N is negative, then the
94112   ** number of pages is adjusted so that the cache uses -N kibibytes
94113   ** of memory.
94114   */
94115   if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
94116     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
94117     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
94118     if( !zRight ){
94119       returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
94120     }else{
94121       int size = sqlite3Atoi(zRight);
94122       pDb->pSchema->cache_size = size;
94123       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
94124     }
94125   }else
94126
94127   /*
94128   **  PRAGMA [database.]mmap_size(N)
94129   **
94130   ** Used to set mapping size limit. The mapping size limit is
94131   ** used to limit the aggregate size of all memory mapped regions of the
94132   ** database file. If this parameter is set to zero, then memory mapping
94133   ** is not used at all.  If N is negative, then the default memory map
94134   ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
94135   ** The parameter N is measured in bytes.
94136   **
94137   ** This value is advisory.  The underlying VFS is free to memory map
94138   ** as little or as much as it wants.  Except, if N is set to 0 then the
94139   ** upper layers will never invoke the xFetch interfaces to the VFS.
94140   */
94141   if( sqlite3StrICmp(zLeft,"mmap_size")==0 ){
94142     sqlite3_int64 sz;
94143     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
94144     if( zRight ){
94145       int ii;
94146       sqlite3Atoi64(zRight, &sz, 1000, SQLITE_UTF8);
94147       if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
94148       if( pId2->n==0 ) db->szMmap = sz;
94149       for(ii=db->nDb-1; ii>=0; ii--){
94150         if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
94151           sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
94152         }
94153       }
94154     }
94155     sz = -1;
94156     if( sqlite3_file_control(db,zDb,SQLITE_FCNTL_MMAP_SIZE,&sz)==SQLITE_OK ){
94157 #if SQLITE_MAX_MMAP_SIZE==0
94158       sz = 0;
94159 #endif
94160       returnSingleInt(pParse, "mmap_size", sz);
94161     }
94162   }else
94163
94164   /*
94165   **   PRAGMA temp_store
94166   **   PRAGMA temp_store = "default"|"memory"|"file"
94167   **
94168   ** Return or set the local value of the temp_store flag.  Changing
94169   ** the local value does not make changes to the disk file and the default
94170   ** value will be restored the next time the database is opened.
94171   **
94172   ** Note that it is possible for the library compile-time options to
94173   ** override this setting
94174   */
94175   if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
94176     if( !zRight ){
94177       returnSingleInt(pParse, "temp_store", db->temp_store);
94178     }else{
94179       changeTempStorage(pParse, zRight);
94180     }
94181   }else
94182
94183   /*
94184   **   PRAGMA temp_store_directory
94185   **   PRAGMA temp_store_directory = ""|"directory_name"
94186   **
94187   ** Return or set the local value of the temp_store_directory flag.  Changing
94188   ** the value sets a specific directory to be used for temporary files.
94189   ** Setting to a null string reverts to the default temporary directory search.
94190   ** If temporary directory is changed, then invalidateTempStorage.
94191   **
94192   */
94193   if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
94194     if( !zRight ){
94195       if( sqlite3_temp_directory ){
94196         sqlite3VdbeSetNumCols(v, 1);
94197         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
94198             "temp_store_directory", SQLITE_STATIC);
94199         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
94200         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
94201       }
94202     }else{
94203 #ifndef SQLITE_OMIT_WSD
94204       if( zRight[0] ){
94205         int res;
94206         rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
94207         if( rc!=SQLITE_OK || res==0 ){
94208           sqlite3ErrorMsg(pParse, "not a writable directory");
94209           goto pragma_out;
94210         }
94211       }
94212       if( SQLITE_TEMP_STORE==0
94213        || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
94214        || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
94215       ){
94216         invalidateTempStorage(pParse);
94217       }
94218       sqlite3_free(sqlite3_temp_directory);
94219       if( zRight[0] ){
94220         sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
94221       }else{
94222         sqlite3_temp_directory = 0;
94223       }
94224 #endif /* SQLITE_OMIT_WSD */
94225     }
94226   }else
94227
94228 #if SQLITE_OS_WIN
94229   /*
94230   **   PRAGMA data_store_directory
94231   **   PRAGMA data_store_directory = ""|"directory_name"
94232   **
94233   ** Return or set the local value of the data_store_directory flag.  Changing
94234   ** the value sets a specific directory to be used for database files that
94235   ** were specified with a relative pathname.  Setting to a null string reverts
94236   ** to the default database directory, which for database files specified with
94237   ** a relative path will probably be based on the current directory for the
94238   ** process.  Database file specified with an absolute path are not impacted
94239   ** by this setting, regardless of its value.
94240   **
94241   */
94242   if( sqlite3StrICmp(zLeft, "data_store_directory")==0 ){
94243     if( !zRight ){
94244       if( sqlite3_data_directory ){
94245         sqlite3VdbeSetNumCols(v, 1);
94246         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
94247             "data_store_directory", SQLITE_STATIC);
94248         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_data_directory, 0);
94249         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
94250       }
94251     }else{
94252 #ifndef SQLITE_OMIT_WSD
94253       if( zRight[0] ){
94254         int res;
94255         rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
94256         if( rc!=SQLITE_OK || res==0 ){
94257           sqlite3ErrorMsg(pParse, "not a writable directory");
94258           goto pragma_out;
94259         }
94260       }
94261       sqlite3_free(sqlite3_data_directory);
94262       if( zRight[0] ){
94263         sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
94264       }else{
94265         sqlite3_data_directory = 0;
94266       }
94267 #endif /* SQLITE_OMIT_WSD */
94268     }
94269   }else
94270 #endif
94271
94272 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
94273 #  if defined(__APPLE__)
94274 #    define SQLITE_ENABLE_LOCKING_STYLE 1
94275 #  else
94276 #    define SQLITE_ENABLE_LOCKING_STYLE 0
94277 #  endif
94278 #endif
94279 #if SQLITE_ENABLE_LOCKING_STYLE
94280   /*
94281    **   PRAGMA [database.]lock_proxy_file
94282    **   PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
94283    **
94284    ** Return or set the value of the lock_proxy_file flag.  Changing
94285    ** the value sets a specific file to be used for database access locks.
94286    **
94287    */
94288   if( sqlite3StrICmp(zLeft, "lock_proxy_file")==0 ){
94289     if( !zRight ){
94290       Pager *pPager = sqlite3BtreePager(pDb->pBt);
94291       char *proxy_file_path = NULL;
94292       sqlite3_file *pFile = sqlite3PagerFile(pPager);
94293       sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE, 
94294                            &proxy_file_path);
94295       
94296       if( proxy_file_path ){
94297         sqlite3VdbeSetNumCols(v, 1);
94298         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
94299                               "lock_proxy_file", SQLITE_STATIC);
94300         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
94301         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
94302       }
94303     }else{
94304       Pager *pPager = sqlite3BtreePager(pDb->pBt);
94305       sqlite3_file *pFile = sqlite3PagerFile(pPager);
94306       int res;
94307       if( zRight[0] ){
94308         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 
94309                                      zRight);
94310       } else {
94311         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 
94312                                      NULL);
94313       }
94314       if( res!=SQLITE_OK ){
94315         sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
94316         goto pragma_out;
94317       }
94318     }
94319   }else
94320 #endif /* SQLITE_ENABLE_LOCKING_STYLE */      
94321     
94322   /*
94323   **   PRAGMA [database.]synchronous
94324   **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
94325   **
94326   ** Return or set the local value of the synchronous flag.  Changing
94327   ** the local value does not make changes to the disk file and the
94328   ** default value will be restored the next time the database is
94329   ** opened.
94330   */
94331   if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
94332     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
94333     if( !zRight ){
94334       returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
94335     }else{
94336       if( !db->autoCommit ){
94337         sqlite3ErrorMsg(pParse, 
94338             "Safety level may not be changed inside a transaction");
94339       }else{
94340         pDb->safety_level = getSafetyLevel(zRight,0,1)+1;
94341       }
94342     }
94343   }else
94344 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
94345
94346 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
94347   if( flagPragma(pParse, zLeft, zRight) ){
94348     /* The flagPragma() subroutine also generates any necessary code
94349     ** there is nothing more to do here */
94350   }else
94351 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
94352
94353 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
94354   /*
94355   **   PRAGMA table_info(<table>)
94356   **
94357   ** Return a single row for each column of the named table. The columns of
94358   ** the returned data set are:
94359   **
94360   ** cid:        Column id (numbered from left to right, starting at 0)
94361   ** name:       Column name
94362   ** type:       Column declaration type.
94363   ** notnull:    True if 'NOT NULL' is part of column declaration
94364   ** dflt_value: The default value for the column, if any.
94365   */
94366   if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
94367     Table *pTab;
94368     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
94369     pTab = sqlite3FindTable(db, zRight, zDb);
94370     if( pTab ){
94371       int i, k;
94372       int nHidden = 0;
94373       Column *pCol;
94374       Index *pPk;
94375       for(pPk=pTab->pIndex; pPk && pPk->autoIndex!=2; pPk=pPk->pNext){}
94376       sqlite3VdbeSetNumCols(v, 6);
94377       pParse->nMem = 6;
94378       sqlite3CodeVerifySchema(pParse, iDb);
94379       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
94380       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
94381       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
94382       sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
94383       sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
94384       sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
94385       sqlite3ViewGetColumnNames(pParse, pTab);
94386       for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
94387         if( IsHiddenColumn(pCol) ){
94388           nHidden++;
94389           continue;
94390         }
94391         sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
94392         sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
94393         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
94394            pCol->zType ? pCol->zType : "", 0);
94395         sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
94396         if( pCol->zDflt ){
94397           sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
94398         }else{
94399           sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
94400         }
94401         if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
94402           k = 0;
94403         }else if( pPk==0 ){
94404           k = 1;
94405         }else{
94406           for(k=1; ALWAYS(k<=pTab->nCol) && pPk->aiColumn[k-1]!=i; k++){}
94407         }
94408         sqlite3VdbeAddOp2(v, OP_Integer, k, 6);
94409         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
94410       }
94411     }
94412   }else
94413
94414   if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
94415     Index *pIdx;
94416     Table *pTab;
94417     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
94418     pIdx = sqlite3FindIndex(db, zRight, zDb);
94419     if( pIdx ){
94420       int i;
94421       pTab = pIdx->pTable;
94422       sqlite3VdbeSetNumCols(v, 3);
94423       pParse->nMem = 3;
94424       sqlite3CodeVerifySchema(pParse, iDb);
94425       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
94426       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
94427       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
94428       for(i=0; i<pIdx->nColumn; i++){
94429         int cnum = pIdx->aiColumn[i];
94430         sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
94431         sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
94432         assert( pTab->nCol>cnum );
94433         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
94434         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
94435       }
94436     }
94437   }else
94438
94439   if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
94440     Index *pIdx;
94441     Table *pTab;
94442     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
94443     pTab = sqlite3FindTable(db, zRight, zDb);
94444     if( pTab ){
94445       v = sqlite3GetVdbe(pParse);
94446       pIdx = pTab->pIndex;
94447       if( pIdx ){
94448         int i = 0; 
94449         sqlite3VdbeSetNumCols(v, 3);
94450         pParse->nMem = 3;
94451         sqlite3CodeVerifySchema(pParse, iDb);
94452         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
94453         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
94454         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
94455         while(pIdx){
94456           sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
94457           sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
94458           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
94459           sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
94460           ++i;
94461           pIdx = pIdx->pNext;
94462         }
94463       }
94464     }
94465   }else
94466
94467   if( sqlite3StrICmp(zLeft, "database_list")==0 ){
94468     int i;
94469     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
94470     sqlite3VdbeSetNumCols(v, 3);
94471     pParse->nMem = 3;
94472     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
94473     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
94474     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
94475     for(i=0; i<db->nDb; i++){
94476       if( db->aDb[i].pBt==0 ) continue;
94477       assert( db->aDb[i].zName!=0 );
94478       sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
94479       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
94480       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
94481            sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
94482       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
94483     }
94484   }else
94485
94486   if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
94487     int i = 0;
94488     HashElem *p;
94489     sqlite3VdbeSetNumCols(v, 2);
94490     pParse->nMem = 2;
94491     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
94492     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
94493     for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
94494       CollSeq *pColl = (CollSeq *)sqliteHashData(p);
94495       sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
94496       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
94497       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
94498     }
94499   }else
94500 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
94501
94502 #ifndef SQLITE_OMIT_FOREIGN_KEY
94503   if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
94504     FKey *pFK;
94505     Table *pTab;
94506     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
94507     pTab = sqlite3FindTable(db, zRight, zDb);
94508     if( pTab ){
94509       v = sqlite3GetVdbe(pParse);
94510       pFK = pTab->pFKey;
94511       if( pFK ){
94512         int i = 0; 
94513         sqlite3VdbeSetNumCols(v, 8);
94514         pParse->nMem = 8;
94515         sqlite3CodeVerifySchema(pParse, iDb);
94516         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
94517         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
94518         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
94519         sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
94520         sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
94521         sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
94522         sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
94523         sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
94524         while(pFK){
94525           int j;
94526           for(j=0; j<pFK->nCol; j++){
94527             char *zCol = pFK->aCol[j].zCol;
94528             char *zOnDelete = (char *)actionName(pFK->aAction[0]);
94529             char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
94530             sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
94531             sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
94532             sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
94533             sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
94534                               pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
94535             sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
94536             sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
94537             sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
94538             sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
94539             sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
94540           }
94541           ++i;
94542           pFK = pFK->pNextFrom;
94543         }
94544       }
94545     }
94546   }else
94547 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
94548
94549 #ifndef SQLITE_OMIT_FOREIGN_KEY
94550 #ifndef SQLITE_OMIT_TRIGGER
94551   if( sqlite3StrICmp(zLeft, "foreign_key_check")==0 ){
94552     FKey *pFK;             /* A foreign key constraint */
94553     Table *pTab;           /* Child table contain "REFERENCES" keyword */
94554     Table *pParent;        /* Parent table that child points to */
94555     Index *pIdx;           /* Index in the parent table */
94556     int i;                 /* Loop counter:  Foreign key number for pTab */
94557     int j;                 /* Loop counter:  Field of the foreign key */
94558     HashElem *k;           /* Loop counter:  Next table in schema */
94559     int x;                 /* result variable */
94560     int regResult;         /* 3 registers to hold a result row */
94561     int regKey;            /* Register to hold key for checking the FK */
94562     int regRow;            /* Registers to hold a row from pTab */
94563     int addrTop;           /* Top of a loop checking foreign keys */
94564     int addrOk;            /* Jump here if the key is OK */
94565     int *aiCols;           /* child to parent column mapping */
94566
94567     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
94568     regResult = pParse->nMem+1;
94569     pParse->nMem += 4;
94570     regKey = ++pParse->nMem;
94571     regRow = ++pParse->nMem;
94572     v = sqlite3GetVdbe(pParse);
94573     sqlite3VdbeSetNumCols(v, 4);
94574     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "table", SQLITE_STATIC);
94575     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "rowid", SQLITE_STATIC);
94576     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "parent", SQLITE_STATIC);
94577     sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "fkid", SQLITE_STATIC);
94578     sqlite3CodeVerifySchema(pParse, iDb);
94579     k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
94580     while( k ){
94581       if( zRight ){
94582         pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
94583         k = 0;
94584       }else{
94585         pTab = (Table*)sqliteHashData(k);
94586         k = sqliteHashNext(k);
94587       }
94588       if( pTab==0 || pTab->pFKey==0 ) continue;
94589       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
94590       if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
94591       sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
94592       sqlite3VdbeAddOp4(v, OP_String8, 0, regResult, 0, pTab->zName,
94593                         P4_TRANSIENT);
94594       for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
94595         pParent = sqlite3LocateTable(pParse, 0, pFK->zTo, zDb);
94596         if( pParent==0 ) break;
94597         pIdx = 0;
94598         sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
94599         x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
94600         if( x==0 ){
94601           if( pIdx==0 ){
94602             sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
94603           }else{
94604             KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
94605             sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
94606             sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
94607           }
94608         }else{
94609           k = 0;
94610           break;
94611         }
94612       }
94613       if( pFK ) break;
94614       if( pParse->nTab<i ) pParse->nTab = i;
94615       addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0);
94616       for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
94617         pParent = sqlite3LocateTable(pParse, 0, pFK->zTo, zDb);
94618         assert( pParent!=0 );
94619         pIdx = 0;
94620         aiCols = 0;
94621         x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
94622         assert( x==0 );
94623         addrOk = sqlite3VdbeMakeLabel(v);
94624         if( pIdx==0 ){
94625           int iKey = pFK->aCol[0].iFrom;
94626           assert( iKey>=0 && iKey<pTab->nCol );
94627           if( iKey!=pTab->iPKey ){
94628             sqlite3VdbeAddOp3(v, OP_Column, 0, iKey, regRow);
94629             sqlite3ColumnDefault(v, pTab, iKey, regRow);
94630             sqlite3VdbeAddOp2(v, OP_IsNull, regRow, addrOk);
94631             sqlite3VdbeAddOp2(v, OP_MustBeInt, regRow,
94632                sqlite3VdbeCurrentAddr(v)+3);
94633           }else{
94634             sqlite3VdbeAddOp2(v, OP_Rowid, 0, regRow);
94635           }
94636           sqlite3VdbeAddOp3(v, OP_NotExists, i, 0, regRow);
94637           sqlite3VdbeAddOp2(v, OP_Goto, 0, addrOk);
94638           sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
94639         }else{
94640           for(j=0; j<pFK->nCol; j++){
94641             sqlite3ExprCodeGetColumnOfTable(v, pTab, 0,
94642                             aiCols ? aiCols[j] : pFK->aCol[0].iFrom, regRow+j);
94643             sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk);
94644           }
94645           sqlite3VdbeAddOp3(v, OP_MakeRecord, regRow, pFK->nCol, regKey);
94646           sqlite3VdbeChangeP4(v, -1,
94647                    sqlite3IndexAffinityStr(v,pIdx), P4_TRANSIENT);
94648           sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
94649         }
94650         sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
94651         sqlite3VdbeAddOp4(v, OP_String8, 0, regResult+2, 0, 
94652                           pFK->zTo, P4_TRANSIENT);
94653         sqlite3VdbeAddOp2(v, OP_Integer, i-1, regResult+3);
94654         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
94655         sqlite3VdbeResolveLabel(v, addrOk);
94656         sqlite3DbFree(db, aiCols);
94657       }
94658       sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1);
94659       sqlite3VdbeJumpHere(v, addrTop);
94660     }
94661   }else
94662 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
94663 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
94664
94665 #ifndef NDEBUG
94666   if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
94667     if( zRight ){
94668       if( sqlite3GetBoolean(zRight, 0) ){
94669         sqlite3ParserTrace(stderr, "parser: ");
94670       }else{
94671         sqlite3ParserTrace(0, 0);
94672       }
94673     }
94674   }else
94675 #endif
94676
94677   /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
94678   ** used will be case sensitive or not depending on the RHS.
94679   */
94680   if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
94681     if( zRight ){
94682       sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
94683     }
94684   }else
94685
94686 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
94687 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
94688 #endif
94689
94690 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
94691   /* Pragma "quick_check" is an experimental reduced version of 
94692   ** integrity_check designed to detect most database corruption
94693   ** without most of the overhead of a full integrity-check.
94694   */
94695   if( sqlite3StrICmp(zLeft, "integrity_check")==0
94696    || sqlite3StrICmp(zLeft, "quick_check")==0 
94697   ){
94698     int i, j, addr, mxErr;
94699
94700     /* Code that appears at the end of the integrity check.  If no error
94701     ** messages have been generated, output OK.  Otherwise output the
94702     ** error message
94703     */
94704     static const VdbeOpList endCode[] = {
94705       { OP_AddImm,      1, 0,        0},    /* 0 */
94706       { OP_IfNeg,       1, 0,        0},    /* 1 */
94707       { OP_String8,     0, 3,        0},    /* 2 */
94708       { OP_ResultRow,   3, 1,        0},
94709     };
94710
94711     int isQuick = (sqlite3Tolower(zLeft[0])=='q');
94712
94713     /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
94714     ** then iDb is set to the index of the database identified by <db>.
94715     ** In this case, the integrity of database iDb only is verified by
94716     ** the VDBE created below.
94717     **
94718     ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
94719     ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
94720     ** to -1 here, to indicate that the VDBE should verify the integrity
94721     ** of all attached databases.  */
94722     assert( iDb>=0 );
94723     assert( iDb==0 || pId2->z );
94724     if( pId2->z==0 ) iDb = -1;
94725
94726     /* Initialize the VDBE program */
94727     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
94728     pParse->nMem = 6;
94729     sqlite3VdbeSetNumCols(v, 1);
94730     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
94731
94732     /* Set the maximum error count */
94733     mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
94734     if( zRight ){
94735       sqlite3GetInt32(zRight, &mxErr);
94736       if( mxErr<=0 ){
94737         mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
94738       }
94739     }
94740     sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
94741
94742     /* Do an integrity check on each database file */
94743     for(i=0; i<db->nDb; i++){
94744       HashElem *x;
94745       Hash *pTbls;
94746       int cnt = 0;
94747
94748       if( OMIT_TEMPDB && i==1 ) continue;
94749       if( iDb>=0 && i!=iDb ) continue;
94750
94751       sqlite3CodeVerifySchema(pParse, i);
94752       addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
94753       sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
94754       sqlite3VdbeJumpHere(v, addr);
94755
94756       /* Do an integrity check of the B-Tree
94757       **
94758       ** Begin by filling registers 2, 3, ... with the root pages numbers
94759       ** for all tables and indices in the database.
94760       */
94761       assert( sqlite3SchemaMutexHeld(db, i, 0) );
94762       pTbls = &db->aDb[i].pSchema->tblHash;
94763       for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
94764         Table *pTab = sqliteHashData(x);
94765         Index *pIdx;
94766         sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
94767         cnt++;
94768         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
94769           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
94770           cnt++;
94771         }
94772       }
94773
94774       /* Make sure sufficient number of registers have been allocated */
94775       if( pParse->nMem < cnt+4 ){
94776         pParse->nMem = cnt+4;
94777       }
94778
94779       /* Do the b-tree integrity checks */
94780       sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
94781       sqlite3VdbeChangeP5(v, (u8)i);
94782       addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
94783       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
94784          sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
94785          P4_DYNAMIC);
94786       sqlite3VdbeAddOp2(v, OP_Move, 2, 4);
94787       sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
94788       sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
94789       sqlite3VdbeJumpHere(v, addr);
94790
94791       /* Make sure all the indices are constructed correctly.
94792       */
94793       for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
94794         Table *pTab = sqliteHashData(x);
94795         Index *pIdx;
94796         int loopTop;
94797
94798         if( pTab->pIndex==0 ) continue;
94799         addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
94800         sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
94801         sqlite3VdbeJumpHere(v, addr);
94802         sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
94803         sqlite3VdbeAddOp2(v, OP_Integer, 0, 2);  /* reg(2) will count entries */
94804         loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0);
94805         sqlite3VdbeAddOp2(v, OP_AddImm, 2, 1);   /* increment entry count */
94806         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
94807           int jmp2;
94808           int r1;
94809           static const VdbeOpList idxErr[] = {
94810             { OP_AddImm,      1, -1,  0},
94811             { OP_String8,     0,  3,  0},    /* 1 */
94812             { OP_Rowid,       1,  4,  0},
94813             { OP_String8,     0,  5,  0},    /* 3 */
94814             { OP_String8,     0,  6,  0},    /* 4 */
94815             { OP_Concat,      4,  3,  3},
94816             { OP_Concat,      5,  3,  3},
94817             { OP_Concat,      6,  3,  3},
94818             { OP_ResultRow,   3,  1,  0},
94819             { OP_IfPos,       1,  0,  0},    /* 9 */
94820             { OP_Halt,        0,  0,  0},
94821           };
94822           r1 = sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 0);
94823           jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, j+2, 0, r1, pIdx->nColumn+1);
94824           addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
94825           sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
94826           sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
94827           sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_TRANSIENT);
94828           sqlite3VdbeJumpHere(v, addr+9);
94829           sqlite3VdbeJumpHere(v, jmp2);
94830         }
94831         sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop+1);
94832         sqlite3VdbeJumpHere(v, loopTop);
94833         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
94834           static const VdbeOpList cntIdx[] = {
94835              { OP_Integer,      0,  3,  0},
94836              { OP_Rewind,       0,  0,  0},  /* 1 */
94837              { OP_AddImm,       3,  1,  0},
94838              { OP_Next,         0,  0,  0},  /* 3 */
94839              { OP_Eq,           2,  0,  3},  /* 4 */
94840              { OP_AddImm,       1, -1,  0},
94841              { OP_String8,      0,  2,  0},  /* 6 */
94842              { OP_String8,      0,  3,  0},  /* 7 */
94843              { OP_Concat,       3,  2,  2},
94844              { OP_ResultRow,    2,  1,  0},
94845           };
94846           addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);
94847           sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
94848           sqlite3VdbeJumpHere(v, addr);
94849           addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
94850           sqlite3VdbeChangeP1(v, addr+1, j+2);
94851           sqlite3VdbeChangeP2(v, addr+1, addr+4);
94852           sqlite3VdbeChangeP1(v, addr+3, j+2);
94853           sqlite3VdbeChangeP2(v, addr+3, addr+2);
94854           sqlite3VdbeJumpHere(v, addr+4);
94855           sqlite3VdbeChangeP4(v, addr+6, 
94856                      "wrong # of entries in index ", P4_STATIC);
94857           sqlite3VdbeChangeP4(v, addr+7, pIdx->zName, P4_TRANSIENT);
94858         }
94859       } 
94860     }
94861     addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
94862     sqlite3VdbeChangeP2(v, addr, -mxErr);
94863     sqlite3VdbeJumpHere(v, addr+1);
94864     sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
94865   }else
94866 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
94867
94868 #ifndef SQLITE_OMIT_UTF16
94869   /*
94870   **   PRAGMA encoding
94871   **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
94872   **
94873   ** In its first form, this pragma returns the encoding of the main
94874   ** database. If the database is not initialized, it is initialized now.
94875   **
94876   ** The second form of this pragma is a no-op if the main database file
94877   ** has not already been initialized. In this case it sets the default
94878   ** encoding that will be used for the main database file if a new file
94879   ** is created. If an existing main database file is opened, then the
94880   ** default text encoding for the existing database is used.
94881   ** 
94882   ** In all cases new databases created using the ATTACH command are
94883   ** created to use the same default text encoding as the main database. If
94884   ** the main database has not been initialized and/or created when ATTACH
94885   ** is executed, this is done before the ATTACH operation.
94886   **
94887   ** In the second form this pragma sets the text encoding to be used in
94888   ** new database files created using this database handle. It is only
94889   ** useful if invoked immediately after the main database i
94890   */
94891   if( sqlite3StrICmp(zLeft, "encoding")==0 ){
94892     static const struct EncName {
94893       char *zName;
94894       u8 enc;
94895     } encnames[] = {
94896       { "UTF8",     SQLITE_UTF8        },
94897       { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
94898       { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
94899       { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
94900       { "UTF16le",  SQLITE_UTF16LE     },
94901       { "UTF16be",  SQLITE_UTF16BE     },
94902       { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
94903       { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
94904       { 0, 0 }
94905     };
94906     const struct EncName *pEnc;
94907     if( !zRight ){    /* "PRAGMA encoding" */
94908       if( sqlite3ReadSchema(pParse) ) goto pragma_out;
94909       sqlite3VdbeSetNumCols(v, 1);
94910       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
94911       sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
94912       assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
94913       assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
94914       assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
94915       sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
94916       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
94917     }else{                        /* "PRAGMA encoding = XXX" */
94918       /* Only change the value of sqlite.enc if the database handle is not
94919       ** initialized. If the main database exists, the new sqlite.enc value
94920       ** will be overwritten when the schema is next loaded. If it does not
94921       ** already exists, it will be created to use the new encoding value.
94922       */
94923       if( 
94924         !(DbHasProperty(db, 0, DB_SchemaLoaded)) || 
94925         DbHasProperty(db, 0, DB_Empty) 
94926       ){
94927         for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
94928           if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
94929             ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
94930             break;
94931           }
94932         }
94933         if( !pEnc->zName ){
94934           sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
94935         }
94936       }
94937     }
94938   }else
94939 #endif /* SQLITE_OMIT_UTF16 */
94940
94941 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
94942   /*
94943   **   PRAGMA [database.]schema_version
94944   **   PRAGMA [database.]schema_version = <integer>
94945   **
94946   **   PRAGMA [database.]user_version
94947   **   PRAGMA [database.]user_version = <integer>
94948   **
94949   **   PRAGMA [database.]freelist_count = <integer>
94950   **
94951   **   PRAGMA [database.]application_id
94952   **   PRAGMA [database.]application_id = <integer>
94953   **
94954   ** The pragma's schema_version and user_version are used to set or get
94955   ** the value of the schema-version and user-version, respectively. Both
94956   ** the schema-version and the user-version are 32-bit signed integers
94957   ** stored in the database header.
94958   **
94959   ** The schema-cookie is usually only manipulated internally by SQLite. It
94960   ** is incremented by SQLite whenever the database schema is modified (by
94961   ** creating or dropping a table or index). The schema version is used by
94962   ** SQLite each time a query is executed to ensure that the internal cache
94963   ** of the schema used when compiling the SQL query matches the schema of
94964   ** the database against which the compiled query is actually executed.
94965   ** Subverting this mechanism by using "PRAGMA schema_version" to modify
94966   ** the schema-version is potentially dangerous and may lead to program
94967   ** crashes or database corruption. Use with caution!
94968   **
94969   ** The user-version is not used internally by SQLite. It may be used by
94970   ** applications for any purpose.
94971   */
94972   if( sqlite3StrICmp(zLeft, "schema_version")==0 
94973    || sqlite3StrICmp(zLeft, "user_version")==0 
94974    || sqlite3StrICmp(zLeft, "freelist_count")==0 
94975    || sqlite3StrICmp(zLeft, "application_id")==0 
94976   ){
94977     int iCookie;   /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
94978     sqlite3VdbeUsesBtree(v, iDb);
94979     switch( zLeft[0] ){
94980       case 'a': case 'A':
94981         iCookie = BTREE_APPLICATION_ID;
94982         break;
94983       case 'f': case 'F':
94984         iCookie = BTREE_FREE_PAGE_COUNT;
94985         break;
94986       case 's': case 'S':
94987         iCookie = BTREE_SCHEMA_VERSION;
94988         break;
94989       default:
94990         iCookie = BTREE_USER_VERSION;
94991         break;
94992     }
94993
94994     if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
94995       /* Write the specified cookie value */
94996       static const VdbeOpList setCookie[] = {
94997         { OP_Transaction,    0,  1,  0},    /* 0 */
94998         { OP_Integer,        0,  1,  0},    /* 1 */
94999         { OP_SetCookie,      0,  0,  1},    /* 2 */
95000       };
95001       int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
95002       sqlite3VdbeChangeP1(v, addr, iDb);
95003       sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight));
95004       sqlite3VdbeChangeP1(v, addr+2, iDb);
95005       sqlite3VdbeChangeP2(v, addr+2, iCookie);
95006     }else{
95007       /* Read the specified cookie value */
95008       static const VdbeOpList readCookie[] = {
95009         { OP_Transaction,     0,  0,  0},    /* 0 */
95010         { OP_ReadCookie,      0,  1,  0},    /* 1 */
95011         { OP_ResultRow,       1,  1,  0}
95012       };
95013       int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
95014       sqlite3VdbeChangeP1(v, addr, iDb);
95015       sqlite3VdbeChangeP1(v, addr+1, iDb);
95016       sqlite3VdbeChangeP3(v, addr+1, iCookie);
95017       sqlite3VdbeSetNumCols(v, 1);
95018       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
95019     }
95020   }else
95021 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
95022
95023 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
95024   /*
95025   **   PRAGMA compile_options
95026   **
95027   ** Return the names of all compile-time options used in this build,
95028   ** one option per row.
95029   */
95030   if( sqlite3StrICmp(zLeft, "compile_options")==0 ){
95031     int i = 0;
95032     const char *zOpt;
95033     sqlite3VdbeSetNumCols(v, 1);
95034     pParse->nMem = 1;
95035     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
95036     while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
95037       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
95038       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
95039     }
95040   }else
95041 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
95042
95043 #ifndef SQLITE_OMIT_WAL
95044   /*
95045   **   PRAGMA [database.]wal_checkpoint = passive|full|restart
95046   **
95047   ** Checkpoint the database.
95048   */
95049   if( sqlite3StrICmp(zLeft, "wal_checkpoint")==0 ){
95050     int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
95051     int eMode = SQLITE_CHECKPOINT_PASSIVE;
95052     if( zRight ){
95053       if( sqlite3StrICmp(zRight, "full")==0 ){
95054         eMode = SQLITE_CHECKPOINT_FULL;
95055       }else if( sqlite3StrICmp(zRight, "restart")==0 ){
95056         eMode = SQLITE_CHECKPOINT_RESTART;
95057       }
95058     }
95059     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
95060     sqlite3VdbeSetNumCols(v, 3);
95061     pParse->nMem = 3;
95062     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "busy", SQLITE_STATIC);
95063     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "log", SQLITE_STATIC);
95064     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "checkpointed", SQLITE_STATIC);
95065
95066     sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
95067     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
95068   }else
95069
95070   /*
95071   **   PRAGMA wal_autocheckpoint
95072   **   PRAGMA wal_autocheckpoint = N
95073   **
95074   ** Configure a database connection to automatically checkpoint a database
95075   ** after accumulating N frames in the log. Or query for the current value
95076   ** of N.
95077   */
95078   if( sqlite3StrICmp(zLeft, "wal_autocheckpoint")==0 ){
95079     if( zRight ){
95080       sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
95081     }
95082     returnSingleInt(pParse, "wal_autocheckpoint", 
95083        db->xWalCallback==sqlite3WalDefaultHook ? 
95084            SQLITE_PTR_TO_INT(db->pWalArg) : 0);
95085   }else
95086 #endif
95087
95088   /*
95089   **  PRAGMA shrink_memory
95090   **
95091   ** This pragma attempts to free as much memory as possible from the
95092   ** current database connection.
95093   */
95094   if( sqlite3StrICmp(zLeft, "shrink_memory")==0 ){
95095     sqlite3_db_release_memory(db);
95096   }else
95097
95098   /*
95099   **   PRAGMA busy_timeout
95100   **   PRAGMA busy_timeout = N
95101   **
95102   ** Call sqlite3_busy_timeout(db, N).  Return the current timeout value
95103   ** if one is set.  If no busy handler or a different busy handler is set
95104   ** then 0 is returned.  Setting the busy_timeout to 0 or negative
95105   ** disables the timeout.
95106   */
95107   if( sqlite3StrICmp(zLeft, "busy_timeout")==0 ){
95108     if( zRight ){
95109       sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
95110     }
95111     returnSingleInt(pParse, "timeout",  db->busyTimeout);
95112   }else
95113
95114 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
95115   /*
95116   ** Report the current state of file logs for all databases
95117   */
95118   if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
95119     static const char *const azLockName[] = {
95120       "unlocked", "shared", "reserved", "pending", "exclusive"
95121     };
95122     int i;
95123     sqlite3VdbeSetNumCols(v, 2);
95124     pParse->nMem = 2;
95125     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
95126     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
95127     for(i=0; i<db->nDb; i++){
95128       Btree *pBt;
95129       const char *zState = "unknown";
95130       int j;
95131       if( db->aDb[i].zName==0 ) continue;
95132       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
95133       pBt = db->aDb[i].pBt;
95134       if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
95135         zState = "closed";
95136       }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0, 
95137                                      SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
95138          zState = azLockName[j];
95139       }
95140       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
95141       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
95142     }
95143
95144   }else
95145 #endif
95146
95147 #ifdef SQLITE_HAS_CODEC
95148   if( sqlite3StrICmp(zLeft, "key")==0 && zRight ){
95149     sqlite3_key(db, zRight, sqlite3Strlen30(zRight));
95150   }else
95151   if( sqlite3StrICmp(zLeft, "rekey")==0 && zRight ){
95152     sqlite3_rekey(db, zRight, sqlite3Strlen30(zRight));
95153   }else
95154   if( zRight && (sqlite3StrICmp(zLeft, "hexkey")==0 ||
95155                  sqlite3StrICmp(zLeft, "hexrekey")==0) ){
95156     int i, h1, h2;
95157     char zKey[40];
95158     for(i=0; (h1 = zRight[i])!=0 && (h2 = zRight[i+1])!=0; i+=2){
95159       h1 += 9*(1&(h1>>6));
95160       h2 += 9*(1&(h2>>6));
95161       zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4);
95162     }
95163     if( (zLeft[3] & 0xf)==0xb ){
95164       sqlite3_key(db, zKey, i/2);
95165     }else{
95166       sqlite3_rekey(db, zKey, i/2);
95167     }
95168   }else
95169 #endif
95170 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
95171   if( sqlite3StrICmp(zLeft, "activate_extensions")==0 && zRight ){
95172 #ifdef SQLITE_HAS_CODEC
95173     if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
95174       sqlite3_activate_see(&zRight[4]);
95175     }
95176 #endif
95177 #ifdef SQLITE_ENABLE_CEROD
95178     if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
95179       sqlite3_activate_cerod(&zRight[6]);
95180     }
95181 #endif
95182   }else
95183 #endif
95184
95185  
95186   {/* Empty ELSE clause */}
95187
95188   /*
95189   ** Reset the safety level, in case the fullfsync flag or synchronous
95190   ** setting changed.
95191   */
95192 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
95193   if( db->autoCommit ){
95194     sqlite3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
95195                (db->flags&SQLITE_FullFSync)!=0,
95196                (db->flags&SQLITE_CkptFullFSync)!=0);
95197   }
95198 #endif
95199 pragma_out:
95200   sqlite3DbFree(db, zLeft);
95201   sqlite3DbFree(db, zRight);
95202 }
95203
95204 #endif /* SQLITE_OMIT_PRAGMA */
95205
95206 /************** End of pragma.c **********************************************/
95207 /************** Begin file prepare.c *****************************************/
95208 /*
95209 ** 2005 May 25
95210 **
95211 ** The author disclaims copyright to this source code.  In place of
95212 ** a legal notice, here is a blessing:
95213 **
95214 **    May you do good and not evil.
95215 **    May you find forgiveness for yourself and forgive others.
95216 **    May you share freely, never taking more than you give.
95217 **
95218 *************************************************************************
95219 ** This file contains the implementation of the sqlite3_prepare()
95220 ** interface, and routines that contribute to loading the database schema
95221 ** from disk.
95222 */
95223
95224 /*
95225 ** Fill the InitData structure with an error message that indicates
95226 ** that the database is corrupt.
95227 */
95228 static void corruptSchema(
95229   InitData *pData,     /* Initialization context */
95230   const char *zObj,    /* Object being parsed at the point of error */
95231   const char *zExtra   /* Error information */
95232 ){
95233   sqlite3 *db = pData->db;
95234   if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
95235     if( zObj==0 ) zObj = "?";
95236     sqlite3SetString(pData->pzErrMsg, db,
95237       "malformed database schema (%s)", zObj);
95238     if( zExtra ){
95239       *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg, 
95240                                  "%s - %s", *pData->pzErrMsg, zExtra);
95241     }
95242   }
95243   pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT;
95244 }
95245
95246 /*
95247 ** This is the callback routine for the code that initializes the
95248 ** database.  See sqlite3Init() below for additional information.
95249 ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
95250 **
95251 ** Each callback contains the following information:
95252 **
95253 **     argv[0] = name of thing being created
95254 **     argv[1] = root page number for table or index. 0 for trigger or view.
95255 **     argv[2] = SQL text for the CREATE statement.
95256 **
95257 */
95258 SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
95259   InitData *pData = (InitData*)pInit;
95260   sqlite3 *db = pData->db;
95261   int iDb = pData->iDb;
95262
95263   assert( argc==3 );
95264   UNUSED_PARAMETER2(NotUsed, argc);
95265   assert( sqlite3_mutex_held(db->mutex) );
95266   DbClearProperty(db, iDb, DB_Empty);
95267   if( db->mallocFailed ){
95268     corruptSchema(pData, argv[0], 0);
95269     return 1;
95270   }
95271
95272   assert( iDb>=0 && iDb<db->nDb );
95273   if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
95274   if( argv[1]==0 ){
95275     corruptSchema(pData, argv[0], 0);
95276   }else if( argv[2] && argv[2][0] ){
95277     /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
95278     ** But because db->init.busy is set to 1, no VDBE code is generated
95279     ** or executed.  All the parser does is build the internal data
95280     ** structures that describe the table, index, or view.
95281     */
95282     int rc;
95283     sqlite3_stmt *pStmt;
95284     TESTONLY(int rcp);            /* Return code from sqlite3_prepare() */
95285
95286     assert( db->init.busy );
95287     db->init.iDb = iDb;
95288     db->init.newTnum = sqlite3Atoi(argv[1]);
95289     db->init.orphanTrigger = 0;
95290     TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
95291     rc = db->errCode;
95292     assert( (rc&0xFF)==(rcp&0xFF) );
95293     db->init.iDb = 0;
95294     if( SQLITE_OK!=rc ){
95295       if( db->init.orphanTrigger ){
95296         assert( iDb==1 );
95297       }else{
95298         pData->rc = rc;
95299         if( rc==SQLITE_NOMEM ){
95300           db->mallocFailed = 1;
95301         }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
95302           corruptSchema(pData, argv[0], sqlite3_errmsg(db));
95303         }
95304       }
95305     }
95306     sqlite3_finalize(pStmt);
95307   }else if( argv[0]==0 ){
95308     corruptSchema(pData, 0, 0);
95309   }else{
95310     /* If the SQL column is blank it means this is an index that
95311     ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
95312     ** constraint for a CREATE TABLE.  The index should have already
95313     ** been created when we processed the CREATE TABLE.  All we have
95314     ** to do here is record the root page number for that index.
95315     */
95316     Index *pIndex;
95317     pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
95318     if( pIndex==0 ){
95319       /* This can occur if there exists an index on a TEMP table which
95320       ** has the same name as another index on a permanent index.  Since
95321       ** the permanent table is hidden by the TEMP table, we can also
95322       ** safely ignore the index on the permanent table.
95323       */
95324       /* Do Nothing */;
95325     }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
95326       corruptSchema(pData, argv[0], "invalid rootpage");
95327     }
95328   }
95329   return 0;
95330 }
95331
95332 /*
95333 ** Attempt to read the database schema and initialize internal
95334 ** data structures for a single database file.  The index of the
95335 ** database file is given by iDb.  iDb==0 is used for the main
95336 ** database.  iDb==1 should never be used.  iDb>=2 is used for
95337 ** auxiliary databases.  Return one of the SQLITE_ error codes to
95338 ** indicate success or failure.
95339 */
95340 static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
95341   int rc;
95342   int i;
95343 #ifndef SQLITE_OMIT_DEPRECATED
95344   int size;
95345 #endif
95346   Table *pTab;
95347   Db *pDb;
95348   char const *azArg[4];
95349   int meta[5];
95350   InitData initData;
95351   char const *zMasterSchema;
95352   char const *zMasterName;
95353   int openedTransaction = 0;
95354
95355   /*
95356   ** The master database table has a structure like this
95357   */
95358   static const char master_schema[] = 
95359      "CREATE TABLE sqlite_master(\n"
95360      "  type text,\n"
95361      "  name text,\n"
95362      "  tbl_name text,\n"
95363      "  rootpage integer,\n"
95364      "  sql text\n"
95365      ")"
95366   ;
95367 #ifndef SQLITE_OMIT_TEMPDB
95368   static const char temp_master_schema[] = 
95369      "CREATE TEMP TABLE sqlite_temp_master(\n"
95370      "  type text,\n"
95371      "  name text,\n"
95372      "  tbl_name text,\n"
95373      "  rootpage integer,\n"
95374      "  sql text\n"
95375      ")"
95376   ;
95377 #else
95378   #define temp_master_schema 0
95379 #endif
95380
95381   assert( iDb>=0 && iDb<db->nDb );
95382   assert( db->aDb[iDb].pSchema );
95383   assert( sqlite3_mutex_held(db->mutex) );
95384   assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
95385
95386   /* zMasterSchema and zInitScript are set to point at the master schema
95387   ** and initialisation script appropriate for the database being
95388   ** initialized. zMasterName is the name of the master table.
95389   */
95390   if( !OMIT_TEMPDB && iDb==1 ){
95391     zMasterSchema = temp_master_schema;
95392   }else{
95393     zMasterSchema = master_schema;
95394   }
95395   zMasterName = SCHEMA_TABLE(iDb);
95396
95397   /* Construct the schema tables.  */
95398   azArg[0] = zMasterName;
95399   azArg[1] = "1";
95400   azArg[2] = zMasterSchema;
95401   azArg[3] = 0;
95402   initData.db = db;
95403   initData.iDb = iDb;
95404   initData.rc = SQLITE_OK;
95405   initData.pzErrMsg = pzErrMsg;
95406   sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
95407   if( initData.rc ){
95408     rc = initData.rc;
95409     goto error_out;
95410   }
95411   pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
95412   if( ALWAYS(pTab) ){
95413     pTab->tabFlags |= TF_Readonly;
95414   }
95415
95416   /* Create a cursor to hold the database open
95417   */
95418   pDb = &db->aDb[iDb];
95419   if( pDb->pBt==0 ){
95420     if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
95421       DbSetProperty(db, 1, DB_SchemaLoaded);
95422     }
95423     return SQLITE_OK;
95424   }
95425
95426   /* If there is not already a read-only (or read-write) transaction opened
95427   ** on the b-tree database, open one now. If a transaction is opened, it 
95428   ** will be closed before this function returns.  */
95429   sqlite3BtreeEnter(pDb->pBt);
95430   if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
95431     rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
95432     if( rc!=SQLITE_OK ){
95433       sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
95434       goto initone_error_out;
95435     }
95436     openedTransaction = 1;
95437   }
95438
95439   /* Get the database meta information.
95440   **
95441   ** Meta values are as follows:
95442   **    meta[0]   Schema cookie.  Changes with each schema change.
95443   **    meta[1]   File format of schema layer.
95444   **    meta[2]   Size of the page cache.
95445   **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
95446   **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
95447   **    meta[5]   User version
95448   **    meta[6]   Incremental vacuum mode
95449   **    meta[7]   unused
95450   **    meta[8]   unused
95451   **    meta[9]   unused
95452   **
95453   ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
95454   ** the possible values of meta[4].
95455   */
95456   for(i=0; i<ArraySize(meta); i++){
95457     sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
95458   }
95459   pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
95460
95461   /* If opening a non-empty database, check the text encoding. For the
95462   ** main database, set sqlite3.enc to the encoding of the main database.
95463   ** For an attached db, it is an error if the encoding is not the same
95464   ** as sqlite3.enc.
95465   */
95466   if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
95467     if( iDb==0 ){
95468 #ifndef SQLITE_OMIT_UTF16
95469       u8 encoding;
95470       /* If opening the main database, set ENC(db). */
95471       encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
95472       if( encoding==0 ) encoding = SQLITE_UTF8;
95473       ENC(db) = encoding;
95474 #else
95475       ENC(db) = SQLITE_UTF8;
95476 #endif
95477     }else{
95478       /* If opening an attached database, the encoding much match ENC(db) */
95479       if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
95480         sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
95481             " text encoding as main database");
95482         rc = SQLITE_ERROR;
95483         goto initone_error_out;
95484       }
95485     }
95486   }else{
95487     DbSetProperty(db, iDb, DB_Empty);
95488   }
95489   pDb->pSchema->enc = ENC(db);
95490
95491   if( pDb->pSchema->cache_size==0 ){
95492 #ifndef SQLITE_OMIT_DEPRECATED
95493     size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
95494     if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
95495     pDb->pSchema->cache_size = size;
95496 #else
95497     pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
95498 #endif
95499     sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
95500   }
95501
95502   /*
95503   ** file_format==1    Version 3.0.0.
95504   ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
95505   ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
95506   ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
95507   */
95508   pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
95509   if( pDb->pSchema->file_format==0 ){
95510     pDb->pSchema->file_format = 1;
95511   }
95512   if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
95513     sqlite3SetString(pzErrMsg, db, "unsupported file format");
95514     rc = SQLITE_ERROR;
95515     goto initone_error_out;
95516   }
95517
95518   /* Ticket #2804:  When we open a database in the newer file format,
95519   ** clear the legacy_file_format pragma flag so that a VACUUM will
95520   ** not downgrade the database and thus invalidate any descending
95521   ** indices that the user might have created.
95522   */
95523   if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
95524     db->flags &= ~SQLITE_LegacyFileFmt;
95525   }
95526
95527   /* Read the schema information out of the schema tables
95528   */
95529   assert( db->init.busy );
95530   {
95531     char *zSql;
95532     zSql = sqlite3MPrintf(db, 
95533         "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
95534         db->aDb[iDb].zName, zMasterName);
95535 #ifndef SQLITE_OMIT_AUTHORIZATION
95536     {
95537       int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
95538       xAuth = db->xAuth;
95539       db->xAuth = 0;
95540 #endif
95541       rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
95542 #ifndef SQLITE_OMIT_AUTHORIZATION
95543       db->xAuth = xAuth;
95544     }
95545 #endif
95546     if( rc==SQLITE_OK ) rc = initData.rc;
95547     sqlite3DbFree(db, zSql);
95548 #ifndef SQLITE_OMIT_ANALYZE
95549     if( rc==SQLITE_OK ){
95550       sqlite3AnalysisLoad(db, iDb);
95551     }
95552 #endif
95553   }
95554   if( db->mallocFailed ){
95555     rc = SQLITE_NOMEM;
95556     sqlite3ResetAllSchemasOfConnection(db);
95557   }
95558   if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
95559     /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
95560     ** the schema loaded, even if errors occurred. In this situation the 
95561     ** current sqlite3_prepare() operation will fail, but the following one
95562     ** will attempt to compile the supplied statement against whatever subset
95563     ** of the schema was loaded before the error occurred. The primary
95564     ** purpose of this is to allow access to the sqlite_master table
95565     ** even when its contents have been corrupted.
95566     */
95567     DbSetProperty(db, iDb, DB_SchemaLoaded);
95568     rc = SQLITE_OK;
95569   }
95570
95571   /* Jump here for an error that occurs after successfully allocating
95572   ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
95573   ** before that point, jump to error_out.
95574   */
95575 initone_error_out:
95576   if( openedTransaction ){
95577     sqlite3BtreeCommit(pDb->pBt);
95578   }
95579   sqlite3BtreeLeave(pDb->pBt);
95580
95581 error_out:
95582   if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
95583     db->mallocFailed = 1;
95584   }
95585   return rc;
95586 }
95587
95588 /*
95589 ** Initialize all database files - the main database file, the file
95590 ** used to store temporary tables, and any additional database files
95591 ** created using ATTACH statements.  Return a success code.  If an
95592 ** error occurs, write an error message into *pzErrMsg.
95593 **
95594 ** After a database is initialized, the DB_SchemaLoaded bit is set
95595 ** bit is set in the flags field of the Db structure. If the database
95596 ** file was of zero-length, then the DB_Empty flag is also set.
95597 */
95598 SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
95599   int i, rc;
95600   int commit_internal = !(db->flags&SQLITE_InternChanges);
95601   
95602   assert( sqlite3_mutex_held(db->mutex) );
95603   rc = SQLITE_OK;
95604   db->init.busy = 1;
95605   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
95606     if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
95607     rc = sqlite3InitOne(db, i, pzErrMsg);
95608     if( rc ){
95609       sqlite3ResetOneSchema(db, i);
95610     }
95611   }
95612
95613   /* Once all the other databases have been initialized, load the schema
95614   ** for the TEMP database. This is loaded last, as the TEMP database
95615   ** schema may contain references to objects in other databases.
95616   */
95617 #ifndef SQLITE_OMIT_TEMPDB
95618   if( rc==SQLITE_OK && ALWAYS(db->nDb>1)
95619                     && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
95620     rc = sqlite3InitOne(db, 1, pzErrMsg);
95621     if( rc ){
95622       sqlite3ResetOneSchema(db, 1);
95623     }
95624   }
95625 #endif
95626
95627   db->init.busy = 0;
95628   if( rc==SQLITE_OK && commit_internal ){
95629     sqlite3CommitInternalChanges(db);
95630   }
95631
95632   return rc; 
95633 }
95634
95635 /*
95636 ** This routine is a no-op if the database schema is already initialized.
95637 ** Otherwise, the schema is loaded. An error code is returned.
95638 */
95639 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
95640   int rc = SQLITE_OK;
95641   sqlite3 *db = pParse->db;
95642   assert( sqlite3_mutex_held(db->mutex) );
95643   if( !db->init.busy ){
95644     rc = sqlite3Init(db, &pParse->zErrMsg);
95645   }
95646   if( rc!=SQLITE_OK ){
95647     pParse->rc = rc;
95648     pParse->nErr++;
95649   }
95650   return rc;
95651 }
95652
95653
95654 /*
95655 ** Check schema cookies in all databases.  If any cookie is out
95656 ** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
95657 ** make no changes to pParse->rc.
95658 */
95659 static void schemaIsValid(Parse *pParse){
95660   sqlite3 *db = pParse->db;
95661   int iDb;
95662   int rc;
95663   int cookie;
95664
95665   assert( pParse->checkSchema );
95666   assert( sqlite3_mutex_held(db->mutex) );
95667   for(iDb=0; iDb<db->nDb; iDb++){
95668     int openedTransaction = 0;         /* True if a transaction is opened */
95669     Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
95670     if( pBt==0 ) continue;
95671
95672     /* If there is not already a read-only (or read-write) transaction opened
95673     ** on the b-tree database, open one now. If a transaction is opened, it 
95674     ** will be closed immediately after reading the meta-value. */
95675     if( !sqlite3BtreeIsInReadTrans(pBt) ){
95676       rc = sqlite3BtreeBeginTrans(pBt, 0);
95677       if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
95678         db->mallocFailed = 1;
95679       }
95680       if( rc!=SQLITE_OK ) return;
95681       openedTransaction = 1;
95682     }
95683
95684     /* Read the schema cookie from the database. If it does not match the 
95685     ** value stored as part of the in-memory schema representation,
95686     ** set Parse.rc to SQLITE_SCHEMA. */
95687     sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
95688     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
95689     if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
95690       sqlite3ResetOneSchema(db, iDb);
95691       pParse->rc = SQLITE_SCHEMA;
95692     }
95693
95694     /* Close the transaction, if one was opened. */
95695     if( openedTransaction ){
95696       sqlite3BtreeCommit(pBt);
95697     }
95698   }
95699 }
95700
95701 /*
95702 ** Convert a schema pointer into the iDb index that indicates
95703 ** which database file in db->aDb[] the schema refers to.
95704 **
95705 ** If the same database is attached more than once, the first
95706 ** attached database is returned.
95707 */
95708 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
95709   int i = -1000000;
95710
95711   /* If pSchema is NULL, then return -1000000. This happens when code in 
95712   ** expr.c is trying to resolve a reference to a transient table (i.e. one
95713   ** created by a sub-select). In this case the return value of this 
95714   ** function should never be used.
95715   **
95716   ** We return -1000000 instead of the more usual -1 simply because using
95717   ** -1000000 as the incorrect index into db->aDb[] is much 
95718   ** more likely to cause a segfault than -1 (of course there are assert()
95719   ** statements too, but it never hurts to play the odds).
95720   */
95721   assert( sqlite3_mutex_held(db->mutex) );
95722   if( pSchema ){
95723     for(i=0; ALWAYS(i<db->nDb); i++){
95724       if( db->aDb[i].pSchema==pSchema ){
95725         break;
95726       }
95727     }
95728     assert( i>=0 && i<db->nDb );
95729   }
95730   return i;
95731 }
95732
95733 /*
95734 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
95735 */
95736 static int sqlite3Prepare(
95737   sqlite3 *db,              /* Database handle. */
95738   const char *zSql,         /* UTF-8 encoded SQL statement. */
95739   int nBytes,               /* Length of zSql in bytes. */
95740   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
95741   Vdbe *pReprepare,         /* VM being reprepared */
95742   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
95743   const char **pzTail       /* OUT: End of parsed string */
95744 ){
95745   Parse *pParse;            /* Parsing context */
95746   char *zErrMsg = 0;        /* Error message */
95747   int rc = SQLITE_OK;       /* Result code */
95748   int i;                    /* Loop counter */
95749
95750   /* Allocate the parsing context */
95751   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
95752   if( pParse==0 ){
95753     rc = SQLITE_NOMEM;
95754     goto end_prepare;
95755   }
95756   pParse->pReprepare = pReprepare;
95757   assert( ppStmt && *ppStmt==0 );
95758   assert( !db->mallocFailed );
95759   assert( sqlite3_mutex_held(db->mutex) );
95760
95761   /* Check to verify that it is possible to get a read lock on all
95762   ** database schemas.  The inability to get a read lock indicates that
95763   ** some other database connection is holding a write-lock, which in
95764   ** turn means that the other connection has made uncommitted changes
95765   ** to the schema.
95766   **
95767   ** Were we to proceed and prepare the statement against the uncommitted
95768   ** schema changes and if those schema changes are subsequently rolled
95769   ** back and different changes are made in their place, then when this
95770   ** prepared statement goes to run the schema cookie would fail to detect
95771   ** the schema change.  Disaster would follow.
95772   **
95773   ** This thread is currently holding mutexes on all Btrees (because
95774   ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
95775   ** is not possible for another thread to start a new schema change
95776   ** while this routine is running.  Hence, we do not need to hold 
95777   ** locks on the schema, we just need to make sure nobody else is 
95778   ** holding them.
95779   **
95780   ** Note that setting READ_UNCOMMITTED overrides most lock detection,
95781   ** but it does *not* override schema lock detection, so this all still
95782   ** works even if READ_UNCOMMITTED is set.
95783   */
95784   for(i=0; i<db->nDb; i++) {
95785     Btree *pBt = db->aDb[i].pBt;
95786     if( pBt ){
95787       assert( sqlite3BtreeHoldsMutex(pBt) );
95788       rc = sqlite3BtreeSchemaLocked(pBt);
95789       if( rc ){
95790         const char *zDb = db->aDb[i].zName;
95791         sqlite3Error(db, rc, "database schema is locked: %s", zDb);
95792         testcase( db->flags & SQLITE_ReadUncommitted );
95793         goto end_prepare;
95794       }
95795     }
95796   }
95797
95798   sqlite3VtabUnlockList(db);
95799
95800   pParse->db = db;
95801   pParse->nQueryLoop = (double)1;
95802   if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
95803     char *zSqlCopy;
95804     int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
95805     testcase( nBytes==mxLen );
95806     testcase( nBytes==mxLen+1 );
95807     if( nBytes>mxLen ){
95808       sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
95809       rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
95810       goto end_prepare;
95811     }
95812     zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
95813     if( zSqlCopy ){
95814       sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
95815       sqlite3DbFree(db, zSqlCopy);
95816       pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
95817     }else{
95818       pParse->zTail = &zSql[nBytes];
95819     }
95820   }else{
95821     sqlite3RunParser(pParse, zSql, &zErrMsg);
95822   }
95823   assert( 1==(int)pParse->nQueryLoop );
95824
95825   if( db->mallocFailed ){
95826     pParse->rc = SQLITE_NOMEM;
95827   }
95828   if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
95829   if( pParse->checkSchema ){
95830     schemaIsValid(pParse);
95831   }
95832   if( db->mallocFailed ){
95833     pParse->rc = SQLITE_NOMEM;
95834   }
95835   if( pzTail ){
95836     *pzTail = pParse->zTail;
95837   }
95838   rc = pParse->rc;
95839
95840 #ifndef SQLITE_OMIT_EXPLAIN
95841   if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
95842     static const char * const azColName[] = {
95843        "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
95844        "selectid", "order", "from", "detail"
95845     };
95846     int iFirst, mx;
95847     if( pParse->explain==2 ){
95848       sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
95849       iFirst = 8;
95850       mx = 12;
95851     }else{
95852       sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
95853       iFirst = 0;
95854       mx = 8;
95855     }
95856     for(i=iFirst; i<mx; i++){
95857       sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
95858                             azColName[i], SQLITE_STATIC);
95859     }
95860   }
95861 #endif
95862
95863   if( db->init.busy==0 ){
95864     Vdbe *pVdbe = pParse->pVdbe;
95865     sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
95866   }
95867   if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
95868     sqlite3VdbeFinalize(pParse->pVdbe);
95869     assert(!(*ppStmt));
95870   }else{
95871     *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
95872   }
95873
95874   if( zErrMsg ){
95875     sqlite3Error(db, rc, "%s", zErrMsg);
95876     sqlite3DbFree(db, zErrMsg);
95877   }else{
95878     sqlite3Error(db, rc, 0);
95879   }
95880
95881   /* Delete any TriggerPrg structures allocated while parsing this statement. */
95882   while( pParse->pTriggerPrg ){
95883     TriggerPrg *pT = pParse->pTriggerPrg;
95884     pParse->pTriggerPrg = pT->pNext;
95885     sqlite3DbFree(db, pT);
95886   }
95887
95888 end_prepare:
95889
95890   sqlite3StackFree(db, pParse);
95891   rc = sqlite3ApiExit(db, rc);
95892   assert( (rc&db->errMask)==rc );
95893   return rc;
95894 }
95895 static int sqlite3LockAndPrepare(
95896   sqlite3 *db,              /* Database handle. */
95897   const char *zSql,         /* UTF-8 encoded SQL statement. */
95898   int nBytes,               /* Length of zSql in bytes. */
95899   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
95900   Vdbe *pOld,               /* VM being reprepared */
95901   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
95902   const char **pzTail       /* OUT: End of parsed string */
95903 ){
95904   int rc;
95905   assert( ppStmt!=0 );
95906   *ppStmt = 0;
95907   if( !sqlite3SafetyCheckOk(db) ){
95908     return SQLITE_MISUSE_BKPT;
95909   }
95910   sqlite3_mutex_enter(db->mutex);
95911   sqlite3BtreeEnterAll(db);
95912   rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
95913   if( rc==SQLITE_SCHEMA ){
95914     sqlite3_finalize(*ppStmt);
95915     rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
95916   }
95917   sqlite3BtreeLeaveAll(db);
95918   sqlite3_mutex_leave(db->mutex);
95919   assert( rc==SQLITE_OK || *ppStmt==0 );
95920   return rc;
95921 }
95922
95923 /*
95924 ** Rerun the compilation of a statement after a schema change.
95925 **
95926 ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
95927 ** if the statement cannot be recompiled because another connection has
95928 ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
95929 ** occurs, return SQLITE_SCHEMA.
95930 */
95931 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
95932   int rc;
95933   sqlite3_stmt *pNew;
95934   const char *zSql;
95935   sqlite3 *db;
95936
95937   assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
95938   zSql = sqlite3_sql((sqlite3_stmt *)p);
95939   assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
95940   db = sqlite3VdbeDb(p);
95941   assert( sqlite3_mutex_held(db->mutex) );
95942   rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
95943   if( rc ){
95944     if( rc==SQLITE_NOMEM ){
95945       db->mallocFailed = 1;
95946     }
95947     assert( pNew==0 );
95948     return rc;
95949   }else{
95950     assert( pNew!=0 );
95951   }
95952   sqlite3VdbeSwap((Vdbe*)pNew, p);
95953   sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
95954   sqlite3VdbeResetStepResult((Vdbe*)pNew);
95955   sqlite3VdbeFinalize((Vdbe*)pNew);
95956   return SQLITE_OK;
95957 }
95958
95959
95960 /*
95961 ** Two versions of the official API.  Legacy and new use.  In the legacy
95962 ** version, the original SQL text is not saved in the prepared statement
95963 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
95964 ** sqlite3_step().  In the new version, the original SQL text is retained
95965 ** and the statement is automatically recompiled if an schema change
95966 ** occurs.
95967 */
95968 SQLITE_API int sqlite3_prepare(
95969   sqlite3 *db,              /* Database handle. */
95970   const char *zSql,         /* UTF-8 encoded SQL statement. */
95971   int nBytes,               /* Length of zSql in bytes. */
95972   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
95973   const char **pzTail       /* OUT: End of parsed string */
95974 ){
95975   int rc;
95976   rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
95977   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
95978   return rc;
95979 }
95980 SQLITE_API int sqlite3_prepare_v2(
95981   sqlite3 *db,              /* Database handle. */
95982   const char *zSql,         /* UTF-8 encoded SQL statement. */
95983   int nBytes,               /* Length of zSql in bytes. */
95984   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
95985   const char **pzTail       /* OUT: End of parsed string */
95986 ){
95987   int rc;
95988   rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
95989   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
95990   return rc;
95991 }
95992
95993
95994 #ifndef SQLITE_OMIT_UTF16
95995 /*
95996 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
95997 */
95998 static int sqlite3Prepare16(
95999   sqlite3 *db,              /* Database handle. */ 
96000   const void *zSql,         /* UTF-16 encoded SQL statement. */
96001   int nBytes,               /* Length of zSql in bytes. */
96002   int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
96003   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
96004   const void **pzTail       /* OUT: End of parsed string */
96005 ){
96006   /* This function currently works by first transforming the UTF-16
96007   ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
96008   ** tricky bit is figuring out the pointer to return in *pzTail.
96009   */
96010   char *zSql8;
96011   const char *zTail8 = 0;
96012   int rc = SQLITE_OK;
96013
96014   assert( ppStmt );
96015   *ppStmt = 0;
96016   if( !sqlite3SafetyCheckOk(db) ){
96017     return SQLITE_MISUSE_BKPT;
96018   }
96019   sqlite3_mutex_enter(db->mutex);
96020   zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
96021   if( zSql8 ){
96022     rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
96023   }
96024
96025   if( zTail8 && pzTail ){
96026     /* If sqlite3_prepare returns a tail pointer, we calculate the
96027     ** equivalent pointer into the UTF-16 string by counting the unicode
96028     ** characters between zSql8 and zTail8, and then returning a pointer
96029     ** the same number of characters into the UTF-16 string.
96030     */
96031     int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
96032     *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
96033   }
96034   sqlite3DbFree(db, zSql8); 
96035   rc = sqlite3ApiExit(db, rc);
96036   sqlite3_mutex_leave(db->mutex);
96037   return rc;
96038 }
96039
96040 /*
96041 ** Two versions of the official API.  Legacy and new use.  In the legacy
96042 ** version, the original SQL text is not saved in the prepared statement
96043 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
96044 ** sqlite3_step().  In the new version, the original SQL text is retained
96045 ** and the statement is automatically recompiled if an schema change
96046 ** occurs.
96047 */
96048 SQLITE_API int sqlite3_prepare16(
96049   sqlite3 *db,              /* Database handle. */ 
96050   const void *zSql,         /* UTF-16 encoded SQL statement. */
96051   int nBytes,               /* Length of zSql in bytes. */
96052   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
96053   const void **pzTail       /* OUT: End of parsed string */
96054 ){
96055   int rc;
96056   rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
96057   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
96058   return rc;
96059 }
96060 SQLITE_API int sqlite3_prepare16_v2(
96061   sqlite3 *db,              /* Database handle. */ 
96062   const void *zSql,         /* UTF-16 encoded SQL statement. */
96063   int nBytes,               /* Length of zSql in bytes. */
96064   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
96065   const void **pzTail       /* OUT: End of parsed string */
96066 ){
96067   int rc;
96068   rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
96069   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
96070   return rc;
96071 }
96072
96073 #endif /* SQLITE_OMIT_UTF16 */
96074
96075 /************** End of prepare.c *********************************************/
96076 /************** Begin file select.c ******************************************/
96077 /*
96078 ** 2001 September 15
96079 **
96080 ** The author disclaims copyright to this source code.  In place of
96081 ** a legal notice, here is a blessing:
96082 **
96083 **    May you do good and not evil.
96084 **    May you find forgiveness for yourself and forgive others.
96085 **    May you share freely, never taking more than you give.
96086 **
96087 *************************************************************************
96088 ** This file contains C code routines that are called by the parser
96089 ** to handle SELECT statements in SQLite.
96090 */
96091
96092
96093 /*
96094 ** Delete all the content of a Select structure but do not deallocate
96095 ** the select structure itself.
96096 */
96097 static void clearSelect(sqlite3 *db, Select *p){
96098   sqlite3ExprListDelete(db, p->pEList);
96099   sqlite3SrcListDelete(db, p->pSrc);
96100   sqlite3ExprDelete(db, p->pWhere);
96101   sqlite3ExprListDelete(db, p->pGroupBy);
96102   sqlite3ExprDelete(db, p->pHaving);
96103   sqlite3ExprListDelete(db, p->pOrderBy);
96104   sqlite3SelectDelete(db, p->pPrior);
96105   sqlite3ExprDelete(db, p->pLimit);
96106   sqlite3ExprDelete(db, p->pOffset);
96107 }
96108
96109 /*
96110 ** Initialize a SelectDest structure.
96111 */
96112 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
96113   pDest->eDest = (u8)eDest;
96114   pDest->iSDParm = iParm;
96115   pDest->affSdst = 0;
96116   pDest->iSdst = 0;
96117   pDest->nSdst = 0;
96118 }
96119
96120
96121 /*
96122 ** Allocate a new Select structure and return a pointer to that
96123 ** structure.
96124 */
96125 SQLITE_PRIVATE Select *sqlite3SelectNew(
96126   Parse *pParse,        /* Parsing context */
96127   ExprList *pEList,     /* which columns to include in the result */
96128   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
96129   Expr *pWhere,         /* the WHERE clause */
96130   ExprList *pGroupBy,   /* the GROUP BY clause */
96131   Expr *pHaving,        /* the HAVING clause */
96132   ExprList *pOrderBy,   /* the ORDER BY clause */
96133   u16 selFlags,         /* Flag parameters, such as SF_Distinct */
96134   Expr *pLimit,         /* LIMIT value.  NULL means not used */
96135   Expr *pOffset         /* OFFSET value.  NULL means no offset */
96136 ){
96137   Select *pNew;
96138   Select standin;
96139   sqlite3 *db = pParse->db;
96140   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
96141   assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
96142   if( pNew==0 ){
96143     assert( db->mallocFailed );
96144     pNew = &standin;
96145     memset(pNew, 0, sizeof(*pNew));
96146   }
96147   if( pEList==0 ){
96148     pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
96149   }
96150   pNew->pEList = pEList;
96151   if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
96152   pNew->pSrc = pSrc;
96153   pNew->pWhere = pWhere;
96154   pNew->pGroupBy = pGroupBy;
96155   pNew->pHaving = pHaving;
96156   pNew->pOrderBy = pOrderBy;
96157   pNew->selFlags = selFlags;
96158   pNew->op = TK_SELECT;
96159   pNew->pLimit = pLimit;
96160   pNew->pOffset = pOffset;
96161   assert( pOffset==0 || pLimit!=0 );
96162   pNew->addrOpenEphm[0] = -1;
96163   pNew->addrOpenEphm[1] = -1;
96164   pNew->addrOpenEphm[2] = -1;
96165   if( db->mallocFailed ) {
96166     clearSelect(db, pNew);
96167     if( pNew!=&standin ) sqlite3DbFree(db, pNew);
96168     pNew = 0;
96169   }else{
96170     assert( pNew->pSrc!=0 || pParse->nErr>0 );
96171   }
96172   assert( pNew!=&standin );
96173   return pNew;
96174 }
96175
96176 /*
96177 ** Delete the given Select structure and all of its substructures.
96178 */
96179 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
96180   if( p ){
96181     clearSelect(db, p);
96182     sqlite3DbFree(db, p);
96183   }
96184 }
96185
96186 /*
96187 ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
96188 ** type of join.  Return an integer constant that expresses that type
96189 ** in terms of the following bit values:
96190 **
96191 **     JT_INNER
96192 **     JT_CROSS
96193 **     JT_OUTER
96194 **     JT_NATURAL
96195 **     JT_LEFT
96196 **     JT_RIGHT
96197 **
96198 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
96199 **
96200 ** If an illegal or unsupported join type is seen, then still return
96201 ** a join type, but put an error in the pParse structure.
96202 */
96203 SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
96204   int jointype = 0;
96205   Token *apAll[3];
96206   Token *p;
96207                              /*   0123456789 123456789 123456789 123 */
96208   static const char zKeyText[] = "naturaleftouterightfullinnercross";
96209   static const struct {
96210     u8 i;        /* Beginning of keyword text in zKeyText[] */
96211     u8 nChar;    /* Length of the keyword in characters */
96212     u8 code;     /* Join type mask */
96213   } aKeyword[] = {
96214     /* natural */ { 0,  7, JT_NATURAL                },
96215     /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
96216     /* outer   */ { 10, 5, JT_OUTER                  },
96217     /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
96218     /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
96219     /* inner   */ { 23, 5, JT_INNER                  },
96220     /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
96221   };
96222   int i, j;
96223   apAll[0] = pA;
96224   apAll[1] = pB;
96225   apAll[2] = pC;
96226   for(i=0; i<3 && apAll[i]; i++){
96227     p = apAll[i];
96228     for(j=0; j<ArraySize(aKeyword); j++){
96229       if( p->n==aKeyword[j].nChar 
96230           && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
96231         jointype |= aKeyword[j].code;
96232         break;
96233       }
96234     }
96235     testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
96236     if( j>=ArraySize(aKeyword) ){
96237       jointype |= JT_ERROR;
96238       break;
96239     }
96240   }
96241   if(
96242      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
96243      (jointype & JT_ERROR)!=0
96244   ){
96245     const char *zSp = " ";
96246     assert( pB!=0 );
96247     if( pC==0 ){ zSp++; }
96248     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
96249        "%T %T%s%T", pA, pB, zSp, pC);
96250     jointype = JT_INNER;
96251   }else if( (jointype & JT_OUTER)!=0 
96252          && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
96253     sqlite3ErrorMsg(pParse, 
96254       "RIGHT and FULL OUTER JOINs are not currently supported");
96255     jointype = JT_INNER;
96256   }
96257   return jointype;
96258 }
96259
96260 /*
96261 ** Return the index of a column in a table.  Return -1 if the column
96262 ** is not contained in the table.
96263 */
96264 static int columnIndex(Table *pTab, const char *zCol){
96265   int i;
96266   for(i=0; i<pTab->nCol; i++){
96267     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
96268   }
96269   return -1;
96270 }
96271
96272 /*
96273 ** Search the first N tables in pSrc, from left to right, looking for a
96274 ** table that has a column named zCol.  
96275 **
96276 ** When found, set *piTab and *piCol to the table index and column index
96277 ** of the matching column and return TRUE.
96278 **
96279 ** If not found, return FALSE.
96280 */
96281 static int tableAndColumnIndex(
96282   SrcList *pSrc,       /* Array of tables to search */
96283   int N,               /* Number of tables in pSrc->a[] to search */
96284   const char *zCol,    /* Name of the column we are looking for */
96285   int *piTab,          /* Write index of pSrc->a[] here */
96286   int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
96287 ){
96288   int i;               /* For looping over tables in pSrc */
96289   int iCol;            /* Index of column matching zCol */
96290
96291   assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
96292   for(i=0; i<N; i++){
96293     iCol = columnIndex(pSrc->a[i].pTab, zCol);
96294     if( iCol>=0 ){
96295       if( piTab ){
96296         *piTab = i;
96297         *piCol = iCol;
96298       }
96299       return 1;
96300     }
96301   }
96302   return 0;
96303 }
96304
96305 /*
96306 ** This function is used to add terms implied by JOIN syntax to the
96307 ** WHERE clause expression of a SELECT statement. The new term, which
96308 ** is ANDed with the existing WHERE clause, is of the form:
96309 **
96310 **    (tab1.col1 = tab2.col2)
96311 **
96312 ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the 
96313 ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
96314 ** column iColRight of tab2.
96315 */
96316 static void addWhereTerm(
96317   Parse *pParse,                  /* Parsing context */
96318   SrcList *pSrc,                  /* List of tables in FROM clause */
96319   int iLeft,                      /* Index of first table to join in pSrc */
96320   int iColLeft,                   /* Index of column in first table */
96321   int iRight,                     /* Index of second table in pSrc */
96322   int iColRight,                  /* Index of column in second table */
96323   int isOuterJoin,                /* True if this is an OUTER join */
96324   Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
96325 ){
96326   sqlite3 *db = pParse->db;
96327   Expr *pE1;
96328   Expr *pE2;
96329   Expr *pEq;
96330
96331   assert( iLeft<iRight );
96332   assert( pSrc->nSrc>iRight );
96333   assert( pSrc->a[iLeft].pTab );
96334   assert( pSrc->a[iRight].pTab );
96335
96336   pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
96337   pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
96338
96339   pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
96340   if( pEq && isOuterJoin ){
96341     ExprSetProperty(pEq, EP_FromJoin);
96342     assert( !ExprHasAnyProperty(pEq, EP_TokenOnly|EP_Reduced) );
96343     ExprSetIrreducible(pEq);
96344     pEq->iRightJoinTable = (i16)pE2->iTable;
96345   }
96346   *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
96347 }
96348
96349 /*
96350 ** Set the EP_FromJoin property on all terms of the given expression.
96351 ** And set the Expr.iRightJoinTable to iTable for every term in the
96352 ** expression.
96353 **
96354 ** The EP_FromJoin property is used on terms of an expression to tell
96355 ** the LEFT OUTER JOIN processing logic that this term is part of the
96356 ** join restriction specified in the ON or USING clause and not a part
96357 ** of the more general WHERE clause.  These terms are moved over to the
96358 ** WHERE clause during join processing but we need to remember that they
96359 ** originated in the ON or USING clause.
96360 **
96361 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
96362 ** expression depends on table iRightJoinTable even if that table is not
96363 ** explicitly mentioned in the expression.  That information is needed
96364 ** for cases like this:
96365 **
96366 **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
96367 **
96368 ** The where clause needs to defer the handling of the t1.x=5
96369 ** term until after the t2 loop of the join.  In that way, a
96370 ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
96371 ** defer the handling of t1.x=5, it will be processed immediately
96372 ** after the t1 loop and rows with t1.x!=5 will never appear in
96373 ** the output, which is incorrect.
96374 */
96375 static void setJoinExpr(Expr *p, int iTable){
96376   while( p ){
96377     ExprSetProperty(p, EP_FromJoin);
96378     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
96379     ExprSetIrreducible(p);
96380     p->iRightJoinTable = (i16)iTable;
96381     setJoinExpr(p->pLeft, iTable);
96382     p = p->pRight;
96383   } 
96384 }
96385
96386 /*
96387 ** This routine processes the join information for a SELECT statement.
96388 ** ON and USING clauses are converted into extra terms of the WHERE clause.
96389 ** NATURAL joins also create extra WHERE clause terms.
96390 **
96391 ** The terms of a FROM clause are contained in the Select.pSrc structure.
96392 ** The left most table is the first entry in Select.pSrc.  The right-most
96393 ** table is the last entry.  The join operator is held in the entry to
96394 ** the left.  Thus entry 0 contains the join operator for the join between
96395 ** entries 0 and 1.  Any ON or USING clauses associated with the join are
96396 ** also attached to the left entry.
96397 **
96398 ** This routine returns the number of errors encountered.
96399 */
96400 static int sqliteProcessJoin(Parse *pParse, Select *p){
96401   SrcList *pSrc;                  /* All tables in the FROM clause */
96402   int i, j;                       /* Loop counters */
96403   struct SrcList_item *pLeft;     /* Left table being joined */
96404   struct SrcList_item *pRight;    /* Right table being joined */
96405
96406   pSrc = p->pSrc;
96407   pLeft = &pSrc->a[0];
96408   pRight = &pLeft[1];
96409   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
96410     Table *pLeftTab = pLeft->pTab;
96411     Table *pRightTab = pRight->pTab;
96412     int isOuter;
96413
96414     if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
96415     isOuter = (pRight->jointype & JT_OUTER)!=0;
96416
96417     /* When the NATURAL keyword is present, add WHERE clause terms for
96418     ** every column that the two tables have in common.
96419     */
96420     if( pRight->jointype & JT_NATURAL ){
96421       if( pRight->pOn || pRight->pUsing ){
96422         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
96423            "an ON or USING clause", 0);
96424         return 1;
96425       }
96426       for(j=0; j<pRightTab->nCol; j++){
96427         char *zName;   /* Name of column in the right table */
96428         int iLeft;     /* Matching left table */
96429         int iLeftCol;  /* Matching column in the left table */
96430
96431         zName = pRightTab->aCol[j].zName;
96432         if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
96433           addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
96434                        isOuter, &p->pWhere);
96435         }
96436       }
96437     }
96438
96439     /* Disallow both ON and USING clauses in the same join
96440     */
96441     if( pRight->pOn && pRight->pUsing ){
96442       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
96443         "clauses in the same join");
96444       return 1;
96445     }
96446
96447     /* Add the ON clause to the end of the WHERE clause, connected by
96448     ** an AND operator.
96449     */
96450     if( pRight->pOn ){
96451       if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
96452       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
96453       pRight->pOn = 0;
96454     }
96455
96456     /* Create extra terms on the WHERE clause for each column named
96457     ** in the USING clause.  Example: If the two tables to be joined are 
96458     ** A and B and the USING clause names X, Y, and Z, then add this
96459     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
96460     ** Report an error if any column mentioned in the USING clause is
96461     ** not contained in both tables to be joined.
96462     */
96463     if( pRight->pUsing ){
96464       IdList *pList = pRight->pUsing;
96465       for(j=0; j<pList->nId; j++){
96466         char *zName;     /* Name of the term in the USING clause */
96467         int iLeft;       /* Table on the left with matching column name */
96468         int iLeftCol;    /* Column number of matching column on the left */
96469         int iRightCol;   /* Column number of matching column on the right */
96470
96471         zName = pList->a[j].zName;
96472         iRightCol = columnIndex(pRightTab, zName);
96473         if( iRightCol<0
96474          || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
96475         ){
96476           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
96477             "not present in both tables", zName);
96478           return 1;
96479         }
96480         addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
96481                      isOuter, &p->pWhere);
96482       }
96483     }
96484   }
96485   return 0;
96486 }
96487
96488 /*
96489 ** Insert code into "v" that will push the record on the top of the
96490 ** stack into the sorter.
96491 */
96492 static void pushOntoSorter(
96493   Parse *pParse,         /* Parser context */
96494   ExprList *pOrderBy,    /* The ORDER BY clause */
96495   Select *pSelect,       /* The whole SELECT statement */
96496   int regData            /* Register holding data to be sorted */
96497 ){
96498   Vdbe *v = pParse->pVdbe;
96499   int nExpr = pOrderBy->nExpr;
96500   int regBase = sqlite3GetTempRange(pParse, nExpr+2);
96501   int regRecord = sqlite3GetTempReg(pParse);
96502   int op;
96503   sqlite3ExprCacheClear(pParse);
96504   sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
96505   sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
96506   sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
96507   sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
96508   if( pSelect->selFlags & SF_UseSorter ){
96509     op = OP_SorterInsert;
96510   }else{
96511     op = OP_IdxInsert;
96512   }
96513   sqlite3VdbeAddOp2(v, op, pOrderBy->iECursor, regRecord);
96514   sqlite3ReleaseTempReg(pParse, regRecord);
96515   sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
96516   if( pSelect->iLimit ){
96517     int addr1, addr2;
96518     int iLimit;
96519     if( pSelect->iOffset ){
96520       iLimit = pSelect->iOffset+1;
96521     }else{
96522       iLimit = pSelect->iLimit;
96523     }
96524     addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
96525     sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
96526     addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
96527     sqlite3VdbeJumpHere(v, addr1);
96528     sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
96529     sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
96530     sqlite3VdbeJumpHere(v, addr2);
96531   }
96532 }
96533
96534 /*
96535 ** Add code to implement the OFFSET
96536 */
96537 static void codeOffset(
96538   Vdbe *v,          /* Generate code into this VM */
96539   Select *p,        /* The SELECT statement being coded */
96540   int iContinue     /* Jump here to skip the current record */
96541 ){
96542   if( p->iOffset && iContinue!=0 ){
96543     int addr;
96544     sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
96545     addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
96546     sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
96547     VdbeComment((v, "skip OFFSET records"));
96548     sqlite3VdbeJumpHere(v, addr);
96549   }
96550 }
96551
96552 /*
96553 ** Add code that will check to make sure the N registers starting at iMem
96554 ** form a distinct entry.  iTab is a sorting index that holds previously
96555 ** seen combinations of the N values.  A new entry is made in iTab
96556 ** if the current N values are new.
96557 **
96558 ** A jump to addrRepeat is made and the N+1 values are popped from the
96559 ** stack if the top N elements are not distinct.
96560 */
96561 static void codeDistinct(
96562   Parse *pParse,     /* Parsing and code generating context */
96563   int iTab,          /* A sorting index used to test for distinctness */
96564   int addrRepeat,    /* Jump to here if not distinct */
96565   int N,             /* Number of elements */
96566   int iMem           /* First element */
96567 ){
96568   Vdbe *v;
96569   int r1;
96570
96571   v = pParse->pVdbe;
96572   r1 = sqlite3GetTempReg(pParse);
96573   sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
96574   sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
96575   sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
96576   sqlite3ReleaseTempReg(pParse, r1);
96577 }
96578
96579 #ifndef SQLITE_OMIT_SUBQUERY
96580 /*
96581 ** Generate an error message when a SELECT is used within a subexpression
96582 ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
96583 ** column.  We do this in a subroutine because the error used to occur
96584 ** in multiple places.  (The error only occurs in one place now, but we
96585 ** retain the subroutine to minimize code disruption.)
96586 */
96587 static int checkForMultiColumnSelectError(
96588   Parse *pParse,       /* Parse context. */
96589   SelectDest *pDest,   /* Destination of SELECT results */
96590   int nExpr            /* Number of result columns returned by SELECT */
96591 ){
96592   int eDest = pDest->eDest;
96593   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
96594     sqlite3ErrorMsg(pParse, "only a single result allowed for "
96595        "a SELECT that is part of an expression");
96596     return 1;
96597   }else{
96598     return 0;
96599   }
96600 }
96601 #endif
96602
96603 /*
96604 ** An instance of the following object is used to record information about
96605 ** how to process the DISTINCT keyword, to simplify passing that information
96606 ** into the selectInnerLoop() routine.
96607 */
96608 typedef struct DistinctCtx DistinctCtx;
96609 struct DistinctCtx {
96610   u8 isTnct;      /* True if the DISTINCT keyword is present */
96611   u8 eTnctType;   /* One of the WHERE_DISTINCT_* operators */
96612   int tabTnct;    /* Ephemeral table used for DISTINCT processing */
96613   int addrTnct;   /* Address of OP_OpenEphemeral opcode for tabTnct */
96614 };
96615
96616 /*
96617 ** This routine generates the code for the inside of the inner loop
96618 ** of a SELECT.
96619 **
96620 ** If srcTab and nColumn are both zero, then the pEList expressions
96621 ** are evaluated in order to get the data for this row.  If nColumn>0
96622 ** then data is pulled from srcTab and pEList is used only to get the
96623 ** datatypes for each column.
96624 */
96625 static void selectInnerLoop(
96626   Parse *pParse,          /* The parser context */
96627   Select *p,              /* The complete select statement being coded */
96628   ExprList *pEList,       /* List of values being extracted */
96629   int srcTab,             /* Pull data from this table */
96630   int nColumn,            /* Number of columns in the source table */
96631   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
96632   DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
96633   SelectDest *pDest,      /* How to dispose of the results */
96634   int iContinue,          /* Jump here to continue with next row */
96635   int iBreak              /* Jump here to break out of the inner loop */
96636 ){
96637   Vdbe *v = pParse->pVdbe;
96638   int i;
96639   int hasDistinct;        /* True if the DISTINCT keyword is present */
96640   int regResult;              /* Start of memory holding result set */
96641   int eDest = pDest->eDest;   /* How to dispose of results */
96642   int iParm = pDest->iSDParm; /* First argument to disposal method */
96643   int nResultCol;             /* Number of result columns */
96644
96645   assert( v );
96646   if( NEVER(v==0) ) return;
96647   assert( pEList!=0 );
96648   hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
96649   if( pOrderBy==0 && !hasDistinct ){
96650     codeOffset(v, p, iContinue);
96651   }
96652
96653   /* Pull the requested columns.
96654   */
96655   if( nColumn>0 ){
96656     nResultCol = nColumn;
96657   }else{
96658     nResultCol = pEList->nExpr;
96659   }
96660   if( pDest->iSdst==0 ){
96661     pDest->iSdst = pParse->nMem+1;
96662     pDest->nSdst = nResultCol;
96663     pParse->nMem += nResultCol;
96664   }else{ 
96665     assert( pDest->nSdst==nResultCol );
96666   }
96667   regResult = pDest->iSdst;
96668   if( nColumn>0 ){
96669     for(i=0; i<nColumn; i++){
96670       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
96671     }
96672   }else if( eDest!=SRT_Exists ){
96673     /* If the destination is an EXISTS(...) expression, the actual
96674     ** values returned by the SELECT are not required.
96675     */
96676     sqlite3ExprCacheClear(pParse);
96677     sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
96678   }
96679   nColumn = nResultCol;
96680
96681   /* If the DISTINCT keyword was present on the SELECT statement
96682   ** and this row has been seen before, then do not make this row
96683   ** part of the result.
96684   */
96685   if( hasDistinct ){
96686     assert( pEList!=0 );
96687     assert( pEList->nExpr==nColumn );
96688     switch( pDistinct->eTnctType ){
96689       case WHERE_DISTINCT_ORDERED: {
96690         VdbeOp *pOp;            /* No longer required OpenEphemeral instr. */
96691         int iJump;              /* Jump destination */
96692         int regPrev;            /* Previous row content */
96693
96694         /* Allocate space for the previous row */
96695         regPrev = pParse->nMem+1;
96696         pParse->nMem += nColumn;
96697
96698         /* Change the OP_OpenEphemeral coded earlier to an OP_Null
96699         ** sets the MEM_Cleared bit on the first register of the
96700         ** previous value.  This will cause the OP_Ne below to always
96701         ** fail on the first iteration of the loop even if the first
96702         ** row is all NULLs.
96703         */
96704         sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
96705         pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
96706         pOp->opcode = OP_Null;
96707         pOp->p1 = 1;
96708         pOp->p2 = regPrev;
96709
96710         iJump = sqlite3VdbeCurrentAddr(v) + nColumn;
96711         for(i=0; i<nColumn; i++){
96712           CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
96713           if( i<nColumn-1 ){
96714             sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
96715           }else{
96716             sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
96717           }
96718           sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
96719           sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
96720         }
96721         assert( sqlite3VdbeCurrentAddr(v)==iJump );
96722         sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nColumn-1);
96723         break;
96724       }
96725
96726       case WHERE_DISTINCT_UNIQUE: {
96727         sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
96728         break;
96729       }
96730
96731       default: {
96732         assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
96733         codeDistinct(pParse, pDistinct->tabTnct, iContinue, nColumn, regResult);
96734         break;
96735       }
96736     }
96737     if( pOrderBy==0 ){
96738       codeOffset(v, p, iContinue);
96739     }
96740   }
96741
96742   switch( eDest ){
96743     /* In this mode, write each query result to the key of the temporary
96744     ** table iParm.
96745     */
96746 #ifndef SQLITE_OMIT_COMPOUND_SELECT
96747     case SRT_Union: {
96748       int r1;
96749       r1 = sqlite3GetTempReg(pParse);
96750       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
96751       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
96752       sqlite3ReleaseTempReg(pParse, r1);
96753       break;
96754     }
96755
96756     /* Construct a record from the query result, but instead of
96757     ** saving that record, use it as a key to delete elements from
96758     ** the temporary table iParm.
96759     */
96760     case SRT_Except: {
96761       sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
96762       break;
96763     }
96764 #endif
96765
96766     /* Store the result as data using a unique key.
96767     */
96768     case SRT_Table:
96769     case SRT_EphemTab: {
96770       int r1 = sqlite3GetTempReg(pParse);
96771       testcase( eDest==SRT_Table );
96772       testcase( eDest==SRT_EphemTab );
96773       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
96774       if( pOrderBy ){
96775         pushOntoSorter(pParse, pOrderBy, p, r1);
96776       }else{
96777         int r2 = sqlite3GetTempReg(pParse);
96778         sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
96779         sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
96780         sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
96781         sqlite3ReleaseTempReg(pParse, r2);
96782       }
96783       sqlite3ReleaseTempReg(pParse, r1);
96784       break;
96785     }
96786
96787 #ifndef SQLITE_OMIT_SUBQUERY
96788     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
96789     ** then there should be a single item on the stack.  Write this
96790     ** item into the set table with bogus data.
96791     */
96792     case SRT_Set: {
96793       assert( nColumn==1 );
96794       pDest->affSdst =
96795                   sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst);
96796       if( pOrderBy ){
96797         /* At first glance you would think we could optimize out the
96798         ** ORDER BY in this case since the order of entries in the set
96799         ** does not matter.  But there might be a LIMIT clause, in which
96800         ** case the order does matter */
96801         pushOntoSorter(pParse, pOrderBy, p, regResult);
96802       }else{
96803         int r1 = sqlite3GetTempReg(pParse);
96804         sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult,1,r1, &pDest->affSdst, 1);
96805         sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
96806         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
96807         sqlite3ReleaseTempReg(pParse, r1);
96808       }
96809       break;
96810     }
96811
96812     /* If any row exist in the result set, record that fact and abort.
96813     */
96814     case SRT_Exists: {
96815       sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
96816       /* The LIMIT clause will terminate the loop for us */
96817       break;
96818     }
96819
96820     /* If this is a scalar select that is part of an expression, then
96821     ** store the results in the appropriate memory cell and break out
96822     ** of the scan loop.
96823     */
96824     case SRT_Mem: {
96825       assert( nColumn==1 );
96826       if( pOrderBy ){
96827         pushOntoSorter(pParse, pOrderBy, p, regResult);
96828       }else{
96829         sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
96830         /* The LIMIT clause will jump out of the loop for us */
96831       }
96832       break;
96833     }
96834 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
96835
96836     /* Send the data to the callback function or to a subroutine.  In the
96837     ** case of a subroutine, the subroutine itself is responsible for
96838     ** popping the data from the stack.
96839     */
96840     case SRT_Coroutine:
96841     case SRT_Output: {
96842       testcase( eDest==SRT_Coroutine );
96843       testcase( eDest==SRT_Output );
96844       if( pOrderBy ){
96845         int r1 = sqlite3GetTempReg(pParse);
96846         sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
96847         pushOntoSorter(pParse, pOrderBy, p, r1);
96848         sqlite3ReleaseTempReg(pParse, r1);
96849       }else if( eDest==SRT_Coroutine ){
96850         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
96851       }else{
96852         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
96853         sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
96854       }
96855       break;
96856     }
96857
96858 #if !defined(SQLITE_OMIT_TRIGGER)
96859     /* Discard the results.  This is used for SELECT statements inside
96860     ** the body of a TRIGGER.  The purpose of such selects is to call
96861     ** user-defined functions that have side effects.  We do not care
96862     ** about the actual results of the select.
96863     */
96864     default: {
96865       assert( eDest==SRT_Discard );
96866       break;
96867     }
96868 #endif
96869   }
96870
96871   /* Jump to the end of the loop if the LIMIT is reached.  Except, if
96872   ** there is a sorter, in which case the sorter has already limited
96873   ** the output for us.
96874   */
96875   if( pOrderBy==0 && p->iLimit ){
96876     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
96877   }
96878 }
96879
96880 /*
96881 ** Given an expression list, generate a KeyInfo structure that records
96882 ** the collating sequence for each expression in that expression list.
96883 **
96884 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
96885 ** KeyInfo structure is appropriate for initializing a virtual index to
96886 ** implement that clause.  If the ExprList is the result set of a SELECT
96887 ** then the KeyInfo structure is appropriate for initializing a virtual
96888 ** index to implement a DISTINCT test.
96889 **
96890 ** Space to hold the KeyInfo structure is obtain from malloc.  The calling
96891 ** function is responsible for seeing that this structure is eventually
96892 ** freed.  Add the KeyInfo structure to the P4 field of an opcode using
96893 ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
96894 */
96895 static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
96896   sqlite3 *db = pParse->db;
96897   int nExpr;
96898   KeyInfo *pInfo;
96899   struct ExprList_item *pItem;
96900   int i;
96901
96902   nExpr = pList->nExpr;
96903   pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
96904   if( pInfo ){
96905     pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
96906     pInfo->nField = (u16)nExpr;
96907     pInfo->enc = ENC(db);
96908     pInfo->db = db;
96909     for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
96910       CollSeq *pColl;
96911       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
96912       if( !pColl ){
96913         pColl = db->pDfltColl;
96914       }
96915       pInfo->aColl[i] = pColl;
96916       pInfo->aSortOrder[i] = pItem->sortOrder;
96917     }
96918   }
96919   return pInfo;
96920 }
96921
96922 #ifndef SQLITE_OMIT_COMPOUND_SELECT
96923 /*
96924 ** Name of the connection operator, used for error messages.
96925 */
96926 static const char *selectOpName(int id){
96927   char *z;
96928   switch( id ){
96929     case TK_ALL:       z = "UNION ALL";   break;
96930     case TK_INTERSECT: z = "INTERSECT";   break;
96931     case TK_EXCEPT:    z = "EXCEPT";      break;
96932     default:           z = "UNION";       break;
96933   }
96934   return z;
96935 }
96936 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
96937
96938 #ifndef SQLITE_OMIT_EXPLAIN
96939 /*
96940 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
96941 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
96942 ** where the caption is of the form:
96943 **
96944 **   "USE TEMP B-TREE FOR xxx"
96945 **
96946 ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
96947 ** is determined by the zUsage argument.
96948 */
96949 static void explainTempTable(Parse *pParse, const char *zUsage){
96950   if( pParse->explain==2 ){
96951     Vdbe *v = pParse->pVdbe;
96952     char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
96953     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
96954   }
96955 }
96956
96957 /*
96958 ** Assign expression b to lvalue a. A second, no-op, version of this macro
96959 ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
96960 ** in sqlite3Select() to assign values to structure member variables that
96961 ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
96962 ** code with #ifndef directives.
96963 */
96964 # define explainSetInteger(a, b) a = b
96965
96966 #else
96967 /* No-op versions of the explainXXX() functions and macros. */
96968 # define explainTempTable(y,z)
96969 # define explainSetInteger(y,z)
96970 #endif
96971
96972 #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
96973 /*
96974 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
96975 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
96976 ** where the caption is of one of the two forms:
96977 **
96978 **   "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
96979 **   "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
96980 **
96981 ** where iSub1 and iSub2 are the integers passed as the corresponding
96982 ** function parameters, and op is the text representation of the parameter
96983 ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
96984 ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is 
96985 ** false, or the second form if it is true.
96986 */
96987 static void explainComposite(
96988   Parse *pParse,                  /* Parse context */
96989   int op,                         /* One of TK_UNION, TK_EXCEPT etc. */
96990   int iSub1,                      /* Subquery id 1 */
96991   int iSub2,                      /* Subquery id 2 */
96992   int bUseTmp                     /* True if a temp table was used */
96993 ){
96994   assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
96995   if( pParse->explain==2 ){
96996     Vdbe *v = pParse->pVdbe;
96997     char *zMsg = sqlite3MPrintf(
96998         pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
96999         bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
97000     );
97001     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
97002   }
97003 }
97004 #else
97005 /* No-op versions of the explainXXX() functions and macros. */
97006 # define explainComposite(v,w,x,y,z)
97007 #endif
97008
97009 /*
97010 ** If the inner loop was generated using a non-null pOrderBy argument,
97011 ** then the results were placed in a sorter.  After the loop is terminated
97012 ** we need to run the sorter and output the results.  The following
97013 ** routine generates the code needed to do that.
97014 */
97015 static void generateSortTail(
97016   Parse *pParse,    /* Parsing context */
97017   Select *p,        /* The SELECT statement */
97018   Vdbe *v,          /* Generate code into this VDBE */
97019   int nColumn,      /* Number of columns of data */
97020   SelectDest *pDest /* Write the sorted results here */
97021 ){
97022   int addrBreak = sqlite3VdbeMakeLabel(v);     /* Jump here to exit loop */
97023   int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
97024   int addr;
97025   int iTab;
97026   int pseudoTab = 0;
97027   ExprList *pOrderBy = p->pOrderBy;
97028
97029   int eDest = pDest->eDest;
97030   int iParm = pDest->iSDParm;
97031
97032   int regRow;
97033   int regRowid;
97034
97035   iTab = pOrderBy->iECursor;
97036   regRow = sqlite3GetTempReg(pParse);
97037   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
97038     pseudoTab = pParse->nTab++;
97039     sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
97040     regRowid = 0;
97041   }else{
97042     regRowid = sqlite3GetTempReg(pParse);
97043   }
97044   if( p->selFlags & SF_UseSorter ){
97045     int regSortOut = ++pParse->nMem;
97046     int ptab2 = pParse->nTab++;
97047     sqlite3VdbeAddOp3(v, OP_OpenPseudo, ptab2, regSortOut, pOrderBy->nExpr+2);
97048     addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
97049     codeOffset(v, p, addrContinue);
97050     sqlite3VdbeAddOp2(v, OP_SorterData, iTab, regSortOut);
97051     sqlite3VdbeAddOp3(v, OP_Column, ptab2, pOrderBy->nExpr+1, regRow);
97052     sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
97053   }else{
97054     addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
97055     codeOffset(v, p, addrContinue);
97056     sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr+1, regRow);
97057   }
97058   switch( eDest ){
97059     case SRT_Table:
97060     case SRT_EphemTab: {
97061       testcase( eDest==SRT_Table );
97062       testcase( eDest==SRT_EphemTab );
97063       sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
97064       sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
97065       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
97066       break;
97067     }
97068 #ifndef SQLITE_OMIT_SUBQUERY
97069     case SRT_Set: {
97070       assert( nColumn==1 );
97071       sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid,
97072                         &pDest->affSdst, 1);
97073       sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
97074       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
97075       break;
97076     }
97077     case SRT_Mem: {
97078       assert( nColumn==1 );
97079       sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
97080       /* The LIMIT clause will terminate the loop for us */
97081       break;
97082     }
97083 #endif
97084     default: {
97085       int i;
97086       assert( eDest==SRT_Output || eDest==SRT_Coroutine ); 
97087       testcase( eDest==SRT_Output );
97088       testcase( eDest==SRT_Coroutine );
97089       for(i=0; i<nColumn; i++){
97090         assert( regRow!=pDest->iSdst+i );
97091         sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iSdst+i);
97092         if( i==0 ){
97093           sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
97094         }
97095       }
97096       if( eDest==SRT_Output ){
97097         sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
97098         sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
97099       }else{
97100         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
97101       }
97102       break;
97103     }
97104   }
97105   sqlite3ReleaseTempReg(pParse, regRow);
97106   sqlite3ReleaseTempReg(pParse, regRowid);
97107
97108   /* The bottom of the loop
97109   */
97110   sqlite3VdbeResolveLabel(v, addrContinue);
97111   if( p->selFlags & SF_UseSorter ){
97112     sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr);
97113   }else{
97114     sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
97115   }
97116   sqlite3VdbeResolveLabel(v, addrBreak);
97117   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
97118     sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
97119   }
97120 }
97121
97122 /*
97123 ** Return a pointer to a string containing the 'declaration type' of the
97124 ** expression pExpr. The string may be treated as static by the caller.
97125 **
97126 ** The declaration type is the exact datatype definition extracted from the
97127 ** original CREATE TABLE statement if the expression is a column. The
97128 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
97129 ** is considered a column can be complex in the presence of subqueries. The
97130 ** result-set expression in all of the following SELECT statements is 
97131 ** considered a column by this function.
97132 **
97133 **   SELECT col FROM tbl;
97134 **   SELECT (SELECT col FROM tbl;
97135 **   SELECT (SELECT col FROM tbl);
97136 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
97137 ** 
97138 ** The declaration type for any expression other than a column is NULL.
97139 */
97140 static const char *columnType(
97141   NameContext *pNC, 
97142   Expr *pExpr,
97143   const char **pzOriginDb,
97144   const char **pzOriginTab,
97145   const char **pzOriginCol
97146 ){
97147   char const *zType = 0;
97148   char const *zOriginDb = 0;
97149   char const *zOriginTab = 0;
97150   char const *zOriginCol = 0;
97151   int j;
97152   if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
97153
97154   switch( pExpr->op ){
97155     case TK_AGG_COLUMN:
97156     case TK_COLUMN: {
97157       /* The expression is a column. Locate the table the column is being
97158       ** extracted from in NameContext.pSrcList. This table may be real
97159       ** database table or a subquery.
97160       */
97161       Table *pTab = 0;            /* Table structure column is extracted from */
97162       Select *pS = 0;             /* Select the column is extracted from */
97163       int iCol = pExpr->iColumn;  /* Index of column in pTab */
97164       testcase( pExpr->op==TK_AGG_COLUMN );
97165       testcase( pExpr->op==TK_COLUMN );
97166       while( pNC && !pTab ){
97167         SrcList *pTabList = pNC->pSrcList;
97168         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
97169         if( j<pTabList->nSrc ){
97170           pTab = pTabList->a[j].pTab;
97171           pS = pTabList->a[j].pSelect;
97172         }else{
97173           pNC = pNC->pNext;
97174         }
97175       }
97176
97177       if( pTab==0 ){
97178         /* At one time, code such as "SELECT new.x" within a trigger would
97179         ** cause this condition to run.  Since then, we have restructured how
97180         ** trigger code is generated and so this condition is no longer 
97181         ** possible. However, it can still be true for statements like
97182         ** the following:
97183         **
97184         **   CREATE TABLE t1(col INTEGER);
97185         **   SELECT (SELECT t1.col) FROM FROM t1;
97186         **
97187         ** when columnType() is called on the expression "t1.col" in the 
97188         ** sub-select. In this case, set the column type to NULL, even
97189         ** though it should really be "INTEGER".
97190         **
97191         ** This is not a problem, as the column type of "t1.col" is never
97192         ** used. When columnType() is called on the expression 
97193         ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
97194         ** branch below.  */
97195         break;
97196       }
97197
97198       assert( pTab && pExpr->pTab==pTab );
97199       if( pS ){
97200         /* The "table" is actually a sub-select or a view in the FROM clause
97201         ** of the SELECT statement. Return the declaration type and origin
97202         ** data for the result-set column of the sub-select.
97203         */
97204         if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
97205           /* If iCol is less than zero, then the expression requests the
97206           ** rowid of the sub-select or view. This expression is legal (see 
97207           ** test case misc2.2.2) - it always evaluates to NULL.
97208           */
97209           NameContext sNC;
97210           Expr *p = pS->pEList->a[iCol].pExpr;
97211           sNC.pSrcList = pS->pSrc;
97212           sNC.pNext = pNC;
97213           sNC.pParse = pNC->pParse;
97214           zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
97215         }
97216       }else if( ALWAYS(pTab->pSchema) ){
97217         /* A real table */
97218         assert( !pS );
97219         if( iCol<0 ) iCol = pTab->iPKey;
97220         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
97221         if( iCol<0 ){
97222           zType = "INTEGER";
97223           zOriginCol = "rowid";
97224         }else{
97225           zType = pTab->aCol[iCol].zType;
97226           zOriginCol = pTab->aCol[iCol].zName;
97227         }
97228         zOriginTab = pTab->zName;
97229         if( pNC->pParse ){
97230           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
97231           zOriginDb = pNC->pParse->db->aDb[iDb].zName;
97232         }
97233       }
97234       break;
97235     }
97236 #ifndef SQLITE_OMIT_SUBQUERY
97237     case TK_SELECT: {
97238       /* The expression is a sub-select. Return the declaration type and
97239       ** origin info for the single column in the result set of the SELECT
97240       ** statement.
97241       */
97242       NameContext sNC;
97243       Select *pS = pExpr->x.pSelect;
97244       Expr *p = pS->pEList->a[0].pExpr;
97245       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
97246       sNC.pSrcList = pS->pSrc;
97247       sNC.pNext = pNC;
97248       sNC.pParse = pNC->pParse;
97249       zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
97250       break;
97251     }
97252 #endif
97253   }
97254   
97255   if( pzOriginDb ){
97256     assert( pzOriginTab && pzOriginCol );
97257     *pzOriginDb = zOriginDb;
97258     *pzOriginTab = zOriginTab;
97259     *pzOriginCol = zOriginCol;
97260   }
97261   return zType;
97262 }
97263
97264 /*
97265 ** Generate code that will tell the VDBE the declaration types of columns
97266 ** in the result set.
97267 */
97268 static void generateColumnTypes(
97269   Parse *pParse,      /* Parser context */
97270   SrcList *pTabList,  /* List of tables */
97271   ExprList *pEList    /* Expressions defining the result set */
97272 ){
97273 #ifndef SQLITE_OMIT_DECLTYPE
97274   Vdbe *v = pParse->pVdbe;
97275   int i;
97276   NameContext sNC;
97277   sNC.pSrcList = pTabList;
97278   sNC.pParse = pParse;
97279   for(i=0; i<pEList->nExpr; i++){
97280     Expr *p = pEList->a[i].pExpr;
97281     const char *zType;
97282 #ifdef SQLITE_ENABLE_COLUMN_METADATA
97283     const char *zOrigDb = 0;
97284     const char *zOrigTab = 0;
97285     const char *zOrigCol = 0;
97286     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
97287
97288     /* The vdbe must make its own copy of the column-type and other 
97289     ** column specific strings, in case the schema is reset before this
97290     ** virtual machine is deleted.
97291     */
97292     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
97293     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
97294     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
97295 #else
97296     zType = columnType(&sNC, p, 0, 0, 0);
97297 #endif
97298     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
97299   }
97300 #endif /* SQLITE_OMIT_DECLTYPE */
97301 }
97302
97303 /*
97304 ** Generate code that will tell the VDBE the names of columns
97305 ** in the result set.  This information is used to provide the
97306 ** azCol[] values in the callback.
97307 */
97308 static void generateColumnNames(
97309   Parse *pParse,      /* Parser context */
97310   SrcList *pTabList,  /* List of tables */
97311   ExprList *pEList    /* Expressions defining the result set */
97312 ){
97313   Vdbe *v = pParse->pVdbe;
97314   int i, j;
97315   sqlite3 *db = pParse->db;
97316   int fullNames, shortNames;
97317
97318 #ifndef SQLITE_OMIT_EXPLAIN
97319   /* If this is an EXPLAIN, skip this step */
97320   if( pParse->explain ){
97321     return;
97322   }
97323 #endif
97324
97325   if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
97326   pParse->colNamesSet = 1;
97327   fullNames = (db->flags & SQLITE_FullColNames)!=0;
97328   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
97329   sqlite3VdbeSetNumCols(v, pEList->nExpr);
97330   for(i=0; i<pEList->nExpr; i++){
97331     Expr *p;
97332     p = pEList->a[i].pExpr;
97333     if( NEVER(p==0) ) continue;
97334     if( pEList->a[i].zName ){
97335       char *zName = pEList->a[i].zName;
97336       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
97337     }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
97338       Table *pTab;
97339       char *zCol;
97340       int iCol = p->iColumn;
97341       for(j=0; ALWAYS(j<pTabList->nSrc); j++){
97342         if( pTabList->a[j].iCursor==p->iTable ) break;
97343       }
97344       assert( j<pTabList->nSrc );
97345       pTab = pTabList->a[j].pTab;
97346       if( iCol<0 ) iCol = pTab->iPKey;
97347       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
97348       if( iCol<0 ){
97349         zCol = "rowid";
97350       }else{
97351         zCol = pTab->aCol[iCol].zName;
97352       }
97353       if( !shortNames && !fullNames ){
97354         sqlite3VdbeSetColName(v, i, COLNAME_NAME, 
97355             sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
97356       }else if( fullNames ){
97357         char *zName = 0;
97358         zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
97359         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
97360       }else{
97361         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
97362       }
97363     }else{
97364       sqlite3VdbeSetColName(v, i, COLNAME_NAME, 
97365           sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
97366     }
97367   }
97368   generateColumnTypes(pParse, pTabList, pEList);
97369 }
97370
97371 /*
97372 ** Given a an expression list (which is really the list of expressions
97373 ** that form the result set of a SELECT statement) compute appropriate
97374 ** column names for a table that would hold the expression list.
97375 **
97376 ** All column names will be unique.
97377 **
97378 ** Only the column names are computed.  Column.zType, Column.zColl,
97379 ** and other fields of Column are zeroed.
97380 **
97381 ** Return SQLITE_OK on success.  If a memory allocation error occurs,
97382 ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
97383 */
97384 static int selectColumnsFromExprList(
97385   Parse *pParse,          /* Parsing context */
97386   ExprList *pEList,       /* Expr list from which to derive column names */
97387   i16 *pnCol,             /* Write the number of columns here */
97388   Column **paCol          /* Write the new column list here */
97389 ){
97390   sqlite3 *db = pParse->db;   /* Database connection */
97391   int i, j;                   /* Loop counters */
97392   int cnt;                    /* Index added to make the name unique */
97393   Column *aCol, *pCol;        /* For looping over result columns */
97394   int nCol;                   /* Number of columns in the result set */
97395   Expr *p;                    /* Expression for a single result column */
97396   char *zName;                /* Column name */
97397   int nName;                  /* Size of name in zName[] */
97398
97399   if( pEList ){
97400     nCol = pEList->nExpr;
97401     aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
97402     testcase( aCol==0 );
97403   }else{
97404     nCol = 0;
97405     aCol = 0;
97406   }
97407   *pnCol = nCol;
97408   *paCol = aCol;
97409
97410   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
97411     /* Get an appropriate name for the column
97412     */
97413     p = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
97414     if( (zName = pEList->a[i].zName)!=0 ){
97415       /* If the column contains an "AS <name>" phrase, use <name> as the name */
97416       zName = sqlite3DbStrDup(db, zName);
97417     }else{
97418       Expr *pColExpr = p;  /* The expression that is the result column name */
97419       Table *pTab;         /* Table associated with this expression */
97420       while( pColExpr->op==TK_DOT ){
97421         pColExpr = pColExpr->pRight;
97422         assert( pColExpr!=0 );
97423       }
97424       if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
97425         /* For columns use the column name name */
97426         int iCol = pColExpr->iColumn;
97427         pTab = pColExpr->pTab;
97428         if( iCol<0 ) iCol = pTab->iPKey;
97429         zName = sqlite3MPrintf(db, "%s",
97430                  iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
97431       }else if( pColExpr->op==TK_ID ){
97432         assert( !ExprHasProperty(pColExpr, EP_IntValue) );
97433         zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
97434       }else{
97435         /* Use the original text of the column expression as its name */
97436         zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
97437       }
97438     }
97439     if( db->mallocFailed ){
97440       sqlite3DbFree(db, zName);
97441       break;
97442     }
97443
97444     /* Make sure the column name is unique.  If the name is not unique,
97445     ** append a integer to the name so that it becomes unique.
97446     */
97447     nName = sqlite3Strlen30(zName);
97448     for(j=cnt=0; j<i; j++){
97449       if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
97450         char *zNewName;
97451         int k;
97452         for(k=nName-1; k>1 && sqlite3Isdigit(zName[k]); k--){}
97453         if( zName[k]==':' ) nName = k;
97454         zName[nName] = 0;
97455         zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
97456         sqlite3DbFree(db, zName);
97457         zName = zNewName;
97458         j = -1;
97459         if( zName==0 ) break;
97460       }
97461     }
97462     pCol->zName = zName;
97463   }
97464   if( db->mallocFailed ){
97465     for(j=0; j<i; j++){
97466       sqlite3DbFree(db, aCol[j].zName);
97467     }
97468     sqlite3DbFree(db, aCol);
97469     *paCol = 0;
97470     *pnCol = 0;
97471     return SQLITE_NOMEM;
97472   }
97473   return SQLITE_OK;
97474 }
97475
97476 /*
97477 ** Add type and collation information to a column list based on
97478 ** a SELECT statement.
97479 ** 
97480 ** The column list presumably came from selectColumnNamesFromExprList().
97481 ** The column list has only names, not types or collations.  This
97482 ** routine goes through and adds the types and collations.
97483 **
97484 ** This routine requires that all identifiers in the SELECT
97485 ** statement be resolved.
97486 */
97487 static void selectAddColumnTypeAndCollation(
97488   Parse *pParse,        /* Parsing contexts */
97489   int nCol,             /* Number of columns */
97490   Column *aCol,         /* List of columns */
97491   Select *pSelect       /* SELECT used to determine types and collations */
97492 ){
97493   sqlite3 *db = pParse->db;
97494   NameContext sNC;
97495   Column *pCol;
97496   CollSeq *pColl;
97497   int i;
97498   Expr *p;
97499   struct ExprList_item *a;
97500
97501   assert( pSelect!=0 );
97502   assert( (pSelect->selFlags & SF_Resolved)!=0 );
97503   assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
97504   if( db->mallocFailed ) return;
97505   memset(&sNC, 0, sizeof(sNC));
97506   sNC.pSrcList = pSelect->pSrc;
97507   a = pSelect->pEList->a;
97508   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
97509     p = a[i].pExpr;
97510     pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
97511     pCol->affinity = sqlite3ExprAffinity(p);
97512     if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
97513     pColl = sqlite3ExprCollSeq(pParse, p);
97514     if( pColl ){
97515       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
97516     }
97517   }
97518 }
97519
97520 /*
97521 ** Given a SELECT statement, generate a Table structure that describes
97522 ** the result set of that SELECT.
97523 */
97524 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
97525   Table *pTab;
97526   sqlite3 *db = pParse->db;
97527   int savedFlags;
97528
97529   savedFlags = db->flags;
97530   db->flags &= ~SQLITE_FullColNames;
97531   db->flags |= SQLITE_ShortColNames;
97532   sqlite3SelectPrep(pParse, pSelect, 0);
97533   if( pParse->nErr ) return 0;
97534   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
97535   db->flags = savedFlags;
97536   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
97537   if( pTab==0 ){
97538     return 0;
97539   }
97540   /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
97541   ** is disabled */
97542   assert( db->lookaside.bEnabled==0 );
97543   pTab->nRef = 1;
97544   pTab->zName = 0;
97545   pTab->nRowEst = 1000000;
97546   selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
97547   selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
97548   pTab->iPKey = -1;
97549   if( db->mallocFailed ){
97550     sqlite3DeleteTable(db, pTab);
97551     return 0;
97552   }
97553   return pTab;
97554 }
97555
97556 /*
97557 ** Get a VDBE for the given parser context.  Create a new one if necessary.
97558 ** If an error occurs, return NULL and leave a message in pParse.
97559 */
97560 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
97561   Vdbe *v = pParse->pVdbe;
97562   if( v==0 ){
97563     v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
97564 #ifndef SQLITE_OMIT_TRACE
97565     if( v ){
97566       sqlite3VdbeAddOp0(v, OP_Trace);
97567     }
97568 #endif
97569   }
97570   return v;
97571 }
97572
97573
97574 /*
97575 ** Compute the iLimit and iOffset fields of the SELECT based on the
97576 ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
97577 ** that appear in the original SQL statement after the LIMIT and OFFSET
97578 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset 
97579 ** are the integer memory register numbers for counters used to compute 
97580 ** the limit and offset.  If there is no limit and/or offset, then 
97581 ** iLimit and iOffset are negative.
97582 **
97583 ** This routine changes the values of iLimit and iOffset only if
97584 ** a limit or offset is defined by pLimit and pOffset.  iLimit and
97585 ** iOffset should have been preset to appropriate default values
97586 ** (usually but not always -1) prior to calling this routine.
97587 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
97588 ** redefined.  The UNION ALL operator uses this property to force
97589 ** the reuse of the same limit and offset registers across multiple
97590 ** SELECT statements.
97591 */
97592 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
97593   Vdbe *v = 0;
97594   int iLimit = 0;
97595   int iOffset;
97596   int addr1, n;
97597   if( p->iLimit ) return;
97598
97599   /* 
97600   ** "LIMIT -1" always shows all rows.  There is some
97601   ** contraversy about what the correct behavior should be.
97602   ** The current implementation interprets "LIMIT 0" to mean
97603   ** no rows.
97604   */
97605   sqlite3ExprCacheClear(pParse);
97606   assert( p->pOffset==0 || p->pLimit!=0 );
97607   if( p->pLimit ){
97608     p->iLimit = iLimit = ++pParse->nMem;
97609     v = sqlite3GetVdbe(pParse);
97610     if( NEVER(v==0) ) return;  /* VDBE should have already been allocated */
97611     if( sqlite3ExprIsInteger(p->pLimit, &n) ){
97612       sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
97613       VdbeComment((v, "LIMIT counter"));
97614       if( n==0 ){
97615         sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
97616       }else{
97617         if( p->nSelectRow > (double)n ) p->nSelectRow = (double)n;
97618       }
97619     }else{
97620       sqlite3ExprCode(pParse, p->pLimit, iLimit);
97621       sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
97622       VdbeComment((v, "LIMIT counter"));
97623       sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
97624     }
97625     if( p->pOffset ){
97626       p->iOffset = iOffset = ++pParse->nMem;
97627       pParse->nMem++;   /* Allocate an extra register for limit+offset */
97628       sqlite3ExprCode(pParse, p->pOffset, iOffset);
97629       sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
97630       VdbeComment((v, "OFFSET counter"));
97631       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
97632       sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
97633       sqlite3VdbeJumpHere(v, addr1);
97634       sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
97635       VdbeComment((v, "LIMIT+OFFSET"));
97636       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
97637       sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
97638       sqlite3VdbeJumpHere(v, addr1);
97639     }
97640   }
97641 }
97642
97643 #ifndef SQLITE_OMIT_COMPOUND_SELECT
97644 /*
97645 ** Return the appropriate collating sequence for the iCol-th column of
97646 ** the result set for the compound-select statement "p".  Return NULL if
97647 ** the column has no default collating sequence.
97648 **
97649 ** The collating sequence for the compound select is taken from the
97650 ** left-most term of the select that has a collating sequence.
97651 */
97652 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
97653   CollSeq *pRet;
97654   if( p->pPrior ){
97655     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
97656   }else{
97657     pRet = 0;
97658   }
97659   assert( iCol>=0 );
97660   if( pRet==0 && iCol<p->pEList->nExpr ){
97661     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
97662   }
97663   return pRet;
97664 }
97665 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
97666
97667 /* Forward reference */
97668 static int multiSelectOrderBy(
97669   Parse *pParse,        /* Parsing context */
97670   Select *p,            /* The right-most of SELECTs to be coded */
97671   SelectDest *pDest     /* What to do with query results */
97672 );
97673
97674
97675 #ifndef SQLITE_OMIT_COMPOUND_SELECT
97676 /*
97677 ** This routine is called to process a compound query form from
97678 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
97679 ** INTERSECT
97680 **
97681 ** "p" points to the right-most of the two queries.  the query on the
97682 ** left is p->pPrior.  The left query could also be a compound query
97683 ** in which case this routine will be called recursively. 
97684 **
97685 ** The results of the total query are to be written into a destination
97686 ** of type eDest with parameter iParm.
97687 **
97688 ** Example 1:  Consider a three-way compound SQL statement.
97689 **
97690 **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
97691 **
97692 ** This statement is parsed up as follows:
97693 **
97694 **     SELECT c FROM t3
97695 **      |
97696 **      `----->  SELECT b FROM t2
97697 **                |
97698 **                `------>  SELECT a FROM t1
97699 **
97700 ** The arrows in the diagram above represent the Select.pPrior pointer.
97701 ** So if this routine is called with p equal to the t3 query, then
97702 ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
97703 **
97704 ** Notice that because of the way SQLite parses compound SELECTs, the
97705 ** individual selects always group from left to right.
97706 */
97707 static int multiSelect(
97708   Parse *pParse,        /* Parsing context */
97709   Select *p,            /* The right-most of SELECTs to be coded */
97710   SelectDest *pDest     /* What to do with query results */
97711 ){
97712   int rc = SQLITE_OK;   /* Success code from a subroutine */
97713   Select *pPrior;       /* Another SELECT immediately to our left */
97714   Vdbe *v;              /* Generate code to this VDBE */
97715   SelectDest dest;      /* Alternative data destination */
97716   Select *pDelete = 0;  /* Chain of simple selects to delete */
97717   sqlite3 *db;          /* Database connection */
97718 #ifndef SQLITE_OMIT_EXPLAIN
97719   int iSub1;            /* EQP id of left-hand query */
97720   int iSub2;            /* EQP id of right-hand query */
97721 #endif
97722
97723   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
97724   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
97725   */
97726   assert( p && p->pPrior );  /* Calling function guarantees this much */
97727   db = pParse->db;
97728   pPrior = p->pPrior;
97729   assert( pPrior->pRightmost!=pPrior );
97730   assert( pPrior->pRightmost==p->pRightmost );
97731   dest = *pDest;
97732   if( pPrior->pOrderBy ){
97733     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
97734       selectOpName(p->op));
97735     rc = 1;
97736     goto multi_select_end;
97737   }
97738   if( pPrior->pLimit ){
97739     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
97740       selectOpName(p->op));
97741     rc = 1;
97742     goto multi_select_end;
97743   }
97744
97745   v = sqlite3GetVdbe(pParse);
97746   assert( v!=0 );  /* The VDBE already created by calling function */
97747
97748   /* Create the destination temporary table if necessary
97749   */
97750   if( dest.eDest==SRT_EphemTab ){
97751     assert( p->pEList );
97752     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
97753     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
97754     dest.eDest = SRT_Table;
97755   }
97756
97757   /* Make sure all SELECTs in the statement have the same number of elements
97758   ** in their result sets.
97759   */
97760   assert( p->pEList && pPrior->pEList );
97761   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
97762     if( p->selFlags & SF_Values ){
97763       sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
97764     }else{
97765       sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
97766         " do not have the same number of result columns", selectOpName(p->op));
97767     }
97768     rc = 1;
97769     goto multi_select_end;
97770   }
97771
97772   /* Compound SELECTs that have an ORDER BY clause are handled separately.
97773   */
97774   if( p->pOrderBy ){
97775     return multiSelectOrderBy(pParse, p, pDest);
97776   }
97777
97778   /* Generate code for the left and right SELECT statements.
97779   */
97780   switch( p->op ){
97781     case TK_ALL: {
97782       int addr = 0;
97783       int nLimit;
97784       assert( !pPrior->pLimit );
97785       pPrior->iLimit = p->iLimit;
97786       pPrior->iOffset = p->iOffset;
97787       pPrior->pLimit = p->pLimit;
97788       pPrior->pOffset = p->pOffset;
97789       explainSetInteger(iSub1, pParse->iNextSelectId);
97790       rc = sqlite3Select(pParse, pPrior, &dest);
97791       p->pLimit = 0;
97792       p->pOffset = 0;
97793       if( rc ){
97794         goto multi_select_end;
97795       }
97796       p->pPrior = 0;
97797       p->iLimit = pPrior->iLimit;
97798       p->iOffset = pPrior->iOffset;
97799       if( p->iLimit ){
97800         addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
97801         VdbeComment((v, "Jump ahead if LIMIT reached"));
97802       }
97803       explainSetInteger(iSub2, pParse->iNextSelectId);
97804       rc = sqlite3Select(pParse, p, &dest);
97805       testcase( rc!=SQLITE_OK );
97806       pDelete = p->pPrior;
97807       p->pPrior = pPrior;
97808       p->nSelectRow += pPrior->nSelectRow;
97809       if( pPrior->pLimit
97810        && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
97811        && p->nSelectRow > (double)nLimit 
97812       ){
97813         p->nSelectRow = (double)nLimit;
97814       }
97815       if( addr ){
97816         sqlite3VdbeJumpHere(v, addr);
97817       }
97818       break;
97819     }
97820     case TK_EXCEPT:
97821     case TK_UNION: {
97822       int unionTab;    /* Cursor number of the temporary table holding result */
97823       u8 op = 0;       /* One of the SRT_ operations to apply to self */
97824       int priorOp;     /* The SRT_ operation to apply to prior selects */
97825       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
97826       int addr;
97827       SelectDest uniondest;
97828
97829       testcase( p->op==TK_EXCEPT );
97830       testcase( p->op==TK_UNION );
97831       priorOp = SRT_Union;
97832       if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
97833         /* We can reuse a temporary table generated by a SELECT to our
97834         ** right.
97835         */
97836         assert( p->pRightmost!=p );  /* Can only happen for leftward elements
97837                                      ** of a 3-way or more compound */
97838         assert( p->pLimit==0 );      /* Not allowed on leftward elements */
97839         assert( p->pOffset==0 );     /* Not allowed on leftward elements */
97840         unionTab = dest.iSDParm;
97841       }else{
97842         /* We will need to create our own temporary table to hold the
97843         ** intermediate results.
97844         */
97845         unionTab = pParse->nTab++;
97846         assert( p->pOrderBy==0 );
97847         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
97848         assert( p->addrOpenEphm[0] == -1 );
97849         p->addrOpenEphm[0] = addr;
97850         p->pRightmost->selFlags |= SF_UsesEphemeral;
97851         assert( p->pEList );
97852       }
97853
97854       /* Code the SELECT statements to our left
97855       */
97856       assert( !pPrior->pOrderBy );
97857       sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
97858       explainSetInteger(iSub1, pParse->iNextSelectId);
97859       rc = sqlite3Select(pParse, pPrior, &uniondest);
97860       if( rc ){
97861         goto multi_select_end;
97862       }
97863
97864       /* Code the current SELECT statement
97865       */
97866       if( p->op==TK_EXCEPT ){
97867         op = SRT_Except;
97868       }else{
97869         assert( p->op==TK_UNION );
97870         op = SRT_Union;
97871       }
97872       p->pPrior = 0;
97873       pLimit = p->pLimit;
97874       p->pLimit = 0;
97875       pOffset = p->pOffset;
97876       p->pOffset = 0;
97877       uniondest.eDest = op;
97878       explainSetInteger(iSub2, pParse->iNextSelectId);
97879       rc = sqlite3Select(pParse, p, &uniondest);
97880       testcase( rc!=SQLITE_OK );
97881       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
97882       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
97883       sqlite3ExprListDelete(db, p->pOrderBy);
97884       pDelete = p->pPrior;
97885       p->pPrior = pPrior;
97886       p->pOrderBy = 0;
97887       if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
97888       sqlite3ExprDelete(db, p->pLimit);
97889       p->pLimit = pLimit;
97890       p->pOffset = pOffset;
97891       p->iLimit = 0;
97892       p->iOffset = 0;
97893
97894       /* Convert the data in the temporary table into whatever form
97895       ** it is that we currently need.
97896       */
97897       assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
97898       if( dest.eDest!=priorOp ){
97899         int iCont, iBreak, iStart;
97900         assert( p->pEList );
97901         if( dest.eDest==SRT_Output ){
97902           Select *pFirst = p;
97903           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
97904           generateColumnNames(pParse, 0, pFirst->pEList);
97905         }
97906         iBreak = sqlite3VdbeMakeLabel(v);
97907         iCont = sqlite3VdbeMakeLabel(v);
97908         computeLimitRegisters(pParse, p, iBreak);
97909         sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
97910         iStart = sqlite3VdbeCurrentAddr(v);
97911         selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
97912                         0, 0, &dest, iCont, iBreak);
97913         sqlite3VdbeResolveLabel(v, iCont);
97914         sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
97915         sqlite3VdbeResolveLabel(v, iBreak);
97916         sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
97917       }
97918       break;
97919     }
97920     default: assert( p->op==TK_INTERSECT ); {
97921       int tab1, tab2;
97922       int iCont, iBreak, iStart;
97923       Expr *pLimit, *pOffset;
97924       int addr;
97925       SelectDest intersectdest;
97926       int r1;
97927
97928       /* INTERSECT is different from the others since it requires
97929       ** two temporary tables.  Hence it has its own case.  Begin
97930       ** by allocating the tables we will need.
97931       */
97932       tab1 = pParse->nTab++;
97933       tab2 = pParse->nTab++;
97934       assert( p->pOrderBy==0 );
97935
97936       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
97937       assert( p->addrOpenEphm[0] == -1 );
97938       p->addrOpenEphm[0] = addr;
97939       p->pRightmost->selFlags |= SF_UsesEphemeral;
97940       assert( p->pEList );
97941
97942       /* Code the SELECTs to our left into temporary table "tab1".
97943       */
97944       sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
97945       explainSetInteger(iSub1, pParse->iNextSelectId);
97946       rc = sqlite3Select(pParse, pPrior, &intersectdest);
97947       if( rc ){
97948         goto multi_select_end;
97949       }
97950
97951       /* Code the current SELECT into temporary table "tab2"
97952       */
97953       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
97954       assert( p->addrOpenEphm[1] == -1 );
97955       p->addrOpenEphm[1] = addr;
97956       p->pPrior = 0;
97957       pLimit = p->pLimit;
97958       p->pLimit = 0;
97959       pOffset = p->pOffset;
97960       p->pOffset = 0;
97961       intersectdest.iSDParm = tab2;
97962       explainSetInteger(iSub2, pParse->iNextSelectId);
97963       rc = sqlite3Select(pParse, p, &intersectdest);
97964       testcase( rc!=SQLITE_OK );
97965       pDelete = p->pPrior;
97966       p->pPrior = pPrior;
97967       if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
97968       sqlite3ExprDelete(db, p->pLimit);
97969       p->pLimit = pLimit;
97970       p->pOffset = pOffset;
97971
97972       /* Generate code to take the intersection of the two temporary
97973       ** tables.
97974       */
97975       assert( p->pEList );
97976       if( dest.eDest==SRT_Output ){
97977         Select *pFirst = p;
97978         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
97979         generateColumnNames(pParse, 0, pFirst->pEList);
97980       }
97981       iBreak = sqlite3VdbeMakeLabel(v);
97982       iCont = sqlite3VdbeMakeLabel(v);
97983       computeLimitRegisters(pParse, p, iBreak);
97984       sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
97985       r1 = sqlite3GetTempReg(pParse);
97986       iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
97987       sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
97988       sqlite3ReleaseTempReg(pParse, r1);
97989       selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
97990                       0, 0, &dest, iCont, iBreak);
97991       sqlite3VdbeResolveLabel(v, iCont);
97992       sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
97993       sqlite3VdbeResolveLabel(v, iBreak);
97994       sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
97995       sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
97996       break;
97997     }
97998   }
97999
98000   explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
98001
98002   /* Compute collating sequences used by 
98003   ** temporary tables needed to implement the compound select.
98004   ** Attach the KeyInfo structure to all temporary tables.
98005   **
98006   ** This section is run by the right-most SELECT statement only.
98007   ** SELECT statements to the left always skip this part.  The right-most
98008   ** SELECT might also skip this part if it has no ORDER BY clause and
98009   ** no temp tables are required.
98010   */
98011   if( p->selFlags & SF_UsesEphemeral ){
98012     int i;                        /* Loop counter */
98013     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
98014     Select *pLoop;                /* For looping through SELECT statements */
98015     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
98016     int nCol;                     /* Number of columns in result set */
98017
98018     assert( p->pRightmost==p );
98019     nCol = p->pEList->nExpr;
98020     pKeyInfo = sqlite3DbMallocZero(db,
98021                        sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
98022     if( !pKeyInfo ){
98023       rc = SQLITE_NOMEM;
98024       goto multi_select_end;
98025     }
98026
98027     pKeyInfo->enc = ENC(db);
98028     pKeyInfo->nField = (u16)nCol;
98029
98030     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
98031       *apColl = multiSelectCollSeq(pParse, p, i);
98032       if( 0==*apColl ){
98033         *apColl = db->pDfltColl;
98034       }
98035     }
98036     pKeyInfo->aSortOrder = (u8*)apColl;
98037
98038     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
98039       for(i=0; i<2; i++){
98040         int addr = pLoop->addrOpenEphm[i];
98041         if( addr<0 ){
98042           /* If [0] is unused then [1] is also unused.  So we can
98043           ** always safely abort as soon as the first unused slot is found */
98044           assert( pLoop->addrOpenEphm[1]<0 );
98045           break;
98046         }
98047         sqlite3VdbeChangeP2(v, addr, nCol);
98048         sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
98049         pLoop->addrOpenEphm[i] = -1;
98050       }
98051     }
98052     sqlite3DbFree(db, pKeyInfo);
98053   }
98054
98055 multi_select_end:
98056   pDest->iSdst = dest.iSdst;
98057   pDest->nSdst = dest.nSdst;
98058   sqlite3SelectDelete(db, pDelete);
98059   return rc;
98060 }
98061 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
98062
98063 /*
98064 ** Code an output subroutine for a coroutine implementation of a
98065 ** SELECT statment.
98066 **
98067 ** The data to be output is contained in pIn->iSdst.  There are
98068 ** pIn->nSdst columns to be output.  pDest is where the output should
98069 ** be sent.
98070 **
98071 ** regReturn is the number of the register holding the subroutine
98072 ** return address.
98073 **
98074 ** If regPrev>0 then it is the first register in a vector that
98075 ** records the previous output.  mem[regPrev] is a flag that is false
98076 ** if there has been no previous output.  If regPrev>0 then code is
98077 ** generated to suppress duplicates.  pKeyInfo is used for comparing
98078 ** keys.
98079 **
98080 ** If the LIMIT found in p->iLimit is reached, jump immediately to
98081 ** iBreak.
98082 */
98083 static int generateOutputSubroutine(
98084   Parse *pParse,          /* Parsing context */
98085   Select *p,              /* The SELECT statement */
98086   SelectDest *pIn,        /* Coroutine supplying data */
98087   SelectDest *pDest,      /* Where to send the data */
98088   int regReturn,          /* The return address register */
98089   int regPrev,            /* Previous result register.  No uniqueness if 0 */
98090   KeyInfo *pKeyInfo,      /* For comparing with previous entry */
98091   int p4type,             /* The p4 type for pKeyInfo */
98092   int iBreak              /* Jump here if we hit the LIMIT */
98093 ){
98094   Vdbe *v = pParse->pVdbe;
98095   int iContinue;
98096   int addr;
98097
98098   addr = sqlite3VdbeCurrentAddr(v);
98099   iContinue = sqlite3VdbeMakeLabel(v);
98100
98101   /* Suppress duplicates for UNION, EXCEPT, and INTERSECT 
98102   */
98103   if( regPrev ){
98104     int j1, j2;
98105     j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
98106     j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
98107                               (char*)pKeyInfo, p4type);
98108     sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
98109     sqlite3VdbeJumpHere(v, j1);
98110     sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
98111     sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
98112   }
98113   if( pParse->db->mallocFailed ) return 0;
98114
98115   /* Suppress the first OFFSET entries if there is an OFFSET clause
98116   */
98117   codeOffset(v, p, iContinue);
98118
98119   switch( pDest->eDest ){
98120     /* Store the result as data using a unique key.
98121     */
98122     case SRT_Table:
98123     case SRT_EphemTab: {
98124       int r1 = sqlite3GetTempReg(pParse);
98125       int r2 = sqlite3GetTempReg(pParse);
98126       testcase( pDest->eDest==SRT_Table );
98127       testcase( pDest->eDest==SRT_EphemTab );
98128       sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
98129       sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
98130       sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
98131       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
98132       sqlite3ReleaseTempReg(pParse, r2);
98133       sqlite3ReleaseTempReg(pParse, r1);
98134       break;
98135     }
98136
98137 #ifndef SQLITE_OMIT_SUBQUERY
98138     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
98139     ** then there should be a single item on the stack.  Write this
98140     ** item into the set table with bogus data.
98141     */
98142     case SRT_Set: {
98143       int r1;
98144       assert( pIn->nSdst==1 );
98145       pDest->affSdst = 
98146          sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst);
98147       r1 = sqlite3GetTempReg(pParse);
98148       sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &pDest->affSdst,1);
98149       sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1);
98150       sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1);
98151       sqlite3ReleaseTempReg(pParse, r1);
98152       break;
98153     }
98154
98155 #if 0  /* Never occurs on an ORDER BY query */
98156     /* If any row exist in the result set, record that fact and abort.
98157     */
98158     case SRT_Exists: {
98159       sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iSDParm);
98160       /* The LIMIT clause will terminate the loop for us */
98161       break;
98162     }
98163 #endif
98164
98165     /* If this is a scalar select that is part of an expression, then
98166     ** store the results in the appropriate memory cell and break out
98167     ** of the scan loop.
98168     */
98169     case SRT_Mem: {
98170       assert( pIn->nSdst==1 );
98171       sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
98172       /* The LIMIT clause will jump out of the loop for us */
98173       break;
98174     }
98175 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
98176
98177     /* The results are stored in a sequence of registers
98178     ** starting at pDest->iSdst.  Then the co-routine yields.
98179     */
98180     case SRT_Coroutine: {
98181       if( pDest->iSdst==0 ){
98182         pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
98183         pDest->nSdst = pIn->nSdst;
98184       }
98185       sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pDest->nSdst);
98186       sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
98187       break;
98188     }
98189
98190     /* If none of the above, then the result destination must be
98191     ** SRT_Output.  This routine is never called with any other
98192     ** destination other than the ones handled above or SRT_Output.
98193     **
98194     ** For SRT_Output, results are stored in a sequence of registers.  
98195     ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
98196     ** return the next row of result.
98197     */
98198     default: {
98199       assert( pDest->eDest==SRT_Output );
98200       sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
98201       sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
98202       break;
98203     }
98204   }
98205
98206   /* Jump to the end of the loop if the LIMIT is reached.
98207   */
98208   if( p->iLimit ){
98209     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
98210   }
98211
98212   /* Generate the subroutine return
98213   */
98214   sqlite3VdbeResolveLabel(v, iContinue);
98215   sqlite3VdbeAddOp1(v, OP_Return, regReturn);
98216
98217   return addr;
98218 }
98219
98220 /*
98221 ** Alternative compound select code generator for cases when there
98222 ** is an ORDER BY clause.
98223 **
98224 ** We assume a query of the following form:
98225 **
98226 **      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
98227 **
98228 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
98229 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
98230 ** co-routines.  Then run the co-routines in parallel and merge the results
98231 ** into the output.  In addition to the two coroutines (called selectA and
98232 ** selectB) there are 7 subroutines:
98233 **
98234 **    outA:    Move the output of the selectA coroutine into the output
98235 **             of the compound query.
98236 **
98237 **    outB:    Move the output of the selectB coroutine into the output
98238 **             of the compound query.  (Only generated for UNION and
98239 **             UNION ALL.  EXCEPT and INSERTSECT never output a row that
98240 **             appears only in B.)
98241 **
98242 **    AltB:    Called when there is data from both coroutines and A<B.
98243 **
98244 **    AeqB:    Called when there is data from both coroutines and A==B.
98245 **
98246 **    AgtB:    Called when there is data from both coroutines and A>B.
98247 **
98248 **    EofA:    Called when data is exhausted from selectA.
98249 **
98250 **    EofB:    Called when data is exhausted from selectB.
98251 **
98252 ** The implementation of the latter five subroutines depend on which 
98253 ** <operator> is used:
98254 **
98255 **
98256 **             UNION ALL         UNION            EXCEPT          INTERSECT
98257 **          -------------  -----------------  --------------  -----------------
98258 **   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
98259 **
98260 **   AeqB:   outA, nextA         nextA             nextA         outA, nextA
98261 **
98262 **   AgtB:   outB, nextB      outB, nextB          nextB            nextB
98263 **
98264 **   EofA:   outB, nextB      outB, nextB          halt             halt
98265 **
98266 **   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
98267 **
98268 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
98269 ** causes an immediate jump to EofA and an EOF on B following nextB causes
98270 ** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
98271 ** following nextX causes a jump to the end of the select processing.
98272 **
98273 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
98274 ** within the output subroutine.  The regPrev register set holds the previously
98275 ** output value.  A comparison is made against this value and the output
98276 ** is skipped if the next results would be the same as the previous.
98277 **
98278 ** The implementation plan is to implement the two coroutines and seven
98279 ** subroutines first, then put the control logic at the bottom.  Like this:
98280 **
98281 **          goto Init
98282 **     coA: coroutine for left query (A)
98283 **     coB: coroutine for right query (B)
98284 **    outA: output one row of A
98285 **    outB: output one row of B (UNION and UNION ALL only)
98286 **    EofA: ...
98287 **    EofB: ...
98288 **    AltB: ...
98289 **    AeqB: ...
98290 **    AgtB: ...
98291 **    Init: initialize coroutine registers
98292 **          yield coA
98293 **          if eof(A) goto EofA
98294 **          yield coB
98295 **          if eof(B) goto EofB
98296 **    Cmpr: Compare A, B
98297 **          Jump AltB, AeqB, AgtB
98298 **     End: ...
98299 **
98300 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
98301 ** actually called using Gosub and they do not Return.  EofA and EofB loop
98302 ** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
98303 ** and AgtB jump to either L2 or to one of EofA or EofB.
98304 */
98305 #ifndef SQLITE_OMIT_COMPOUND_SELECT
98306 static int multiSelectOrderBy(
98307   Parse *pParse,        /* Parsing context */
98308   Select *p,            /* The right-most of SELECTs to be coded */
98309   SelectDest *pDest     /* What to do with query results */
98310 ){
98311   int i, j;             /* Loop counters */
98312   Select *pPrior;       /* Another SELECT immediately to our left */
98313   Vdbe *v;              /* Generate code to this VDBE */
98314   SelectDest destA;     /* Destination for coroutine A */
98315   SelectDest destB;     /* Destination for coroutine B */
98316   int regAddrA;         /* Address register for select-A coroutine */
98317   int regEofA;          /* Flag to indicate when select-A is complete */
98318   int regAddrB;         /* Address register for select-B coroutine */
98319   int regEofB;          /* Flag to indicate when select-B is complete */
98320   int addrSelectA;      /* Address of the select-A coroutine */
98321   int addrSelectB;      /* Address of the select-B coroutine */
98322   int regOutA;          /* Address register for the output-A subroutine */
98323   int regOutB;          /* Address register for the output-B subroutine */
98324   int addrOutA;         /* Address of the output-A subroutine */
98325   int addrOutB = 0;     /* Address of the output-B subroutine */
98326   int addrEofA;         /* Address of the select-A-exhausted subroutine */
98327   int addrEofB;         /* Address of the select-B-exhausted subroutine */
98328   int addrAltB;         /* Address of the A<B subroutine */
98329   int addrAeqB;         /* Address of the A==B subroutine */
98330   int addrAgtB;         /* Address of the A>B subroutine */
98331   int regLimitA;        /* Limit register for select-A */
98332   int regLimitB;        /* Limit register for select-A */
98333   int regPrev;          /* A range of registers to hold previous output */
98334   int savedLimit;       /* Saved value of p->iLimit */
98335   int savedOffset;      /* Saved value of p->iOffset */
98336   int labelCmpr;        /* Label for the start of the merge algorithm */
98337   int labelEnd;         /* Label for the end of the overall SELECT stmt */
98338   int j1;               /* Jump instructions that get retargetted */
98339   int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
98340   KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
98341   KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
98342   sqlite3 *db;          /* Database connection */
98343   ExprList *pOrderBy;   /* The ORDER BY clause */
98344   int nOrderBy;         /* Number of terms in the ORDER BY clause */
98345   int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
98346 #ifndef SQLITE_OMIT_EXPLAIN
98347   int iSub1;            /* EQP id of left-hand query */
98348   int iSub2;            /* EQP id of right-hand query */
98349 #endif
98350
98351   assert( p->pOrderBy!=0 );
98352   assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
98353   db = pParse->db;
98354   v = pParse->pVdbe;
98355   assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
98356   labelEnd = sqlite3VdbeMakeLabel(v);
98357   labelCmpr = sqlite3VdbeMakeLabel(v);
98358
98359
98360   /* Patch up the ORDER BY clause
98361   */
98362   op = p->op;  
98363   pPrior = p->pPrior;
98364   assert( pPrior->pOrderBy==0 );
98365   pOrderBy = p->pOrderBy;
98366   assert( pOrderBy );
98367   nOrderBy = pOrderBy->nExpr;
98368
98369   /* For operators other than UNION ALL we have to make sure that
98370   ** the ORDER BY clause covers every term of the result set.  Add
98371   ** terms to the ORDER BY clause as necessary.
98372   */
98373   if( op!=TK_ALL ){
98374     for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
98375       struct ExprList_item *pItem;
98376       for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
98377         assert( pItem->iOrderByCol>0 );
98378         if( pItem->iOrderByCol==i ) break;
98379       }
98380       if( j==nOrderBy ){
98381         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
98382         if( pNew==0 ) return SQLITE_NOMEM;
98383         pNew->flags |= EP_IntValue;
98384         pNew->u.iValue = i;
98385         pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
98386         if( pOrderBy ) pOrderBy->a[nOrderBy++].iOrderByCol = (u16)i;
98387       }
98388     }
98389   }
98390
98391   /* Compute the comparison permutation and keyinfo that is used with
98392   ** the permutation used to determine if the next
98393   ** row of results comes from selectA or selectB.  Also add explicit
98394   ** collations to the ORDER BY clause terms so that when the subqueries
98395   ** to the right and the left are evaluated, they use the correct
98396   ** collation.
98397   */
98398   aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
98399   if( aPermute ){
98400     struct ExprList_item *pItem;
98401     for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
98402       assert( pItem->iOrderByCol>0  && pItem->iOrderByCol<=p->pEList->nExpr );
98403       aPermute[i] = pItem->iOrderByCol - 1;
98404     }
98405     pKeyMerge =
98406       sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
98407     if( pKeyMerge ){
98408       pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
98409       pKeyMerge->nField = (u16)nOrderBy;
98410       pKeyMerge->enc = ENC(db);
98411       for(i=0; i<nOrderBy; i++){
98412         CollSeq *pColl;
98413         Expr *pTerm = pOrderBy->a[i].pExpr;
98414         if( pTerm->flags & EP_Collate ){
98415           pColl = sqlite3ExprCollSeq(pParse, pTerm);
98416         }else{
98417           pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
98418           if( pColl==0 ) pColl = db->pDfltColl;
98419           pOrderBy->a[i].pExpr =
98420              sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
98421         }
98422         pKeyMerge->aColl[i] = pColl;
98423         pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
98424       }
98425     }
98426   }else{
98427     pKeyMerge = 0;
98428   }
98429
98430   /* Reattach the ORDER BY clause to the query.
98431   */
98432   p->pOrderBy = pOrderBy;
98433   pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
98434
98435   /* Allocate a range of temporary registers and the KeyInfo needed
98436   ** for the logic that removes duplicate result rows when the
98437   ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
98438   */
98439   if( op==TK_ALL ){
98440     regPrev = 0;
98441   }else{
98442     int nExpr = p->pEList->nExpr;
98443     assert( nOrderBy>=nExpr || db->mallocFailed );
98444     regPrev = pParse->nMem+1;
98445     pParse->nMem += nExpr+1;
98446     sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
98447     pKeyDup = sqlite3DbMallocZero(db,
98448                   sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
98449     if( pKeyDup ){
98450       pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
98451       pKeyDup->nField = (u16)nExpr;
98452       pKeyDup->enc = ENC(db);
98453       for(i=0; i<nExpr; i++){
98454         pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
98455         pKeyDup->aSortOrder[i] = 0;
98456       }
98457     }
98458   }
98459  
98460   /* Separate the left and the right query from one another
98461   */
98462   p->pPrior = 0;
98463   sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
98464   if( pPrior->pPrior==0 ){
98465     sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
98466   }
98467
98468   /* Compute the limit registers */
98469   computeLimitRegisters(pParse, p, labelEnd);
98470   if( p->iLimit && op==TK_ALL ){
98471     regLimitA = ++pParse->nMem;
98472     regLimitB = ++pParse->nMem;
98473     sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
98474                                   regLimitA);
98475     sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
98476   }else{
98477     regLimitA = regLimitB = 0;
98478   }
98479   sqlite3ExprDelete(db, p->pLimit);
98480   p->pLimit = 0;
98481   sqlite3ExprDelete(db, p->pOffset);
98482   p->pOffset = 0;
98483
98484   regAddrA = ++pParse->nMem;
98485   regEofA = ++pParse->nMem;
98486   regAddrB = ++pParse->nMem;
98487   regEofB = ++pParse->nMem;
98488   regOutA = ++pParse->nMem;
98489   regOutB = ++pParse->nMem;
98490   sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
98491   sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
98492
98493   /* Jump past the various subroutines and coroutines to the main
98494   ** merge loop
98495   */
98496   j1 = sqlite3VdbeAddOp0(v, OP_Goto);
98497   addrSelectA = sqlite3VdbeCurrentAddr(v);
98498
98499
98500   /* Generate a coroutine to evaluate the SELECT statement to the
98501   ** left of the compound operator - the "A" select.
98502   */
98503   VdbeNoopComment((v, "Begin coroutine for left SELECT"));
98504   pPrior->iLimit = regLimitA;
98505   explainSetInteger(iSub1, pParse->iNextSelectId);
98506   sqlite3Select(pParse, pPrior, &destA);
98507   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
98508   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
98509   VdbeNoopComment((v, "End coroutine for left SELECT"));
98510
98511   /* Generate a coroutine to evaluate the SELECT statement on 
98512   ** the right - the "B" select
98513   */
98514   addrSelectB = sqlite3VdbeCurrentAddr(v);
98515   VdbeNoopComment((v, "Begin coroutine for right SELECT"));
98516   savedLimit = p->iLimit;
98517   savedOffset = p->iOffset;
98518   p->iLimit = regLimitB;
98519   p->iOffset = 0;  
98520   explainSetInteger(iSub2, pParse->iNextSelectId);
98521   sqlite3Select(pParse, p, &destB);
98522   p->iLimit = savedLimit;
98523   p->iOffset = savedOffset;
98524   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
98525   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
98526   VdbeNoopComment((v, "End coroutine for right SELECT"));
98527
98528   /* Generate a subroutine that outputs the current row of the A
98529   ** select as the next output row of the compound select.
98530   */
98531   VdbeNoopComment((v, "Output routine for A"));
98532   addrOutA = generateOutputSubroutine(pParse,
98533                  p, &destA, pDest, regOutA,
98534                  regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
98535   
98536   /* Generate a subroutine that outputs the current row of the B
98537   ** select as the next output row of the compound select.
98538   */
98539   if( op==TK_ALL || op==TK_UNION ){
98540     VdbeNoopComment((v, "Output routine for B"));
98541     addrOutB = generateOutputSubroutine(pParse,
98542                  p, &destB, pDest, regOutB,
98543                  regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
98544   }
98545
98546   /* Generate a subroutine to run when the results from select A
98547   ** are exhausted and only data in select B remains.
98548   */
98549   VdbeNoopComment((v, "eof-A subroutine"));
98550   if( op==TK_EXCEPT || op==TK_INTERSECT ){
98551     addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
98552   }else{  
98553     addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
98554     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
98555     sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
98556     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
98557     p->nSelectRow += pPrior->nSelectRow;
98558   }
98559
98560   /* Generate a subroutine to run when the results from select B
98561   ** are exhausted and only data in select A remains.
98562   */
98563   if( op==TK_INTERSECT ){
98564     addrEofB = addrEofA;
98565     if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
98566   }else{  
98567     VdbeNoopComment((v, "eof-B subroutine"));
98568     addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
98569     sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
98570     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
98571     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
98572   }
98573
98574   /* Generate code to handle the case of A<B
98575   */
98576   VdbeNoopComment((v, "A-lt-B subroutine"));
98577   addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
98578   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
98579   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
98580   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
98581
98582   /* Generate code to handle the case of A==B
98583   */
98584   if( op==TK_ALL ){
98585     addrAeqB = addrAltB;
98586   }else if( op==TK_INTERSECT ){
98587     addrAeqB = addrAltB;
98588     addrAltB++;
98589   }else{
98590     VdbeNoopComment((v, "A-eq-B subroutine"));
98591     addrAeqB =
98592     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
98593     sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
98594     sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
98595   }
98596
98597   /* Generate code to handle the case of A>B
98598   */
98599   VdbeNoopComment((v, "A-gt-B subroutine"));
98600   addrAgtB = sqlite3VdbeCurrentAddr(v);
98601   if( op==TK_ALL || op==TK_UNION ){
98602     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
98603   }
98604   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
98605   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
98606   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
98607
98608   /* This code runs once to initialize everything.
98609   */
98610   sqlite3VdbeJumpHere(v, j1);
98611   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
98612   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
98613   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
98614   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
98615   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
98616   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
98617
98618   /* Implement the main merge loop
98619   */
98620   sqlite3VdbeResolveLabel(v, labelCmpr);
98621   sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
98622   sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
98623                          (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
98624   sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
98625   sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
98626
98627   /* Jump to the this point in order to terminate the query.
98628   */
98629   sqlite3VdbeResolveLabel(v, labelEnd);
98630
98631   /* Set the number of output columns
98632   */
98633   if( pDest->eDest==SRT_Output ){
98634     Select *pFirst = pPrior;
98635     while( pFirst->pPrior ) pFirst = pFirst->pPrior;
98636     generateColumnNames(pParse, 0, pFirst->pEList);
98637   }
98638
98639   /* Reassembly the compound query so that it will be freed correctly
98640   ** by the calling function */
98641   if( p->pPrior ){
98642     sqlite3SelectDelete(db, p->pPrior);
98643   }
98644   p->pPrior = pPrior;
98645
98646   /*** TBD:  Insert subroutine calls to close cursors on incomplete
98647   **** subqueries ****/
98648   explainComposite(pParse, p->op, iSub1, iSub2, 0);
98649   return SQLITE_OK;
98650 }
98651 #endif
98652
98653 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
98654 /* Forward Declarations */
98655 static void substExprList(sqlite3*, ExprList*, int, ExprList*);
98656 static void substSelect(sqlite3*, Select *, int, ExprList *);
98657
98658 /*
98659 ** Scan through the expression pExpr.  Replace every reference to
98660 ** a column in table number iTable with a copy of the iColumn-th
98661 ** entry in pEList.  (But leave references to the ROWID column 
98662 ** unchanged.)
98663 **
98664 ** This routine is part of the flattening procedure.  A subquery
98665 ** whose result set is defined by pEList appears as entry in the
98666 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
98667 ** FORM clause entry is iTable.  This routine make the necessary 
98668 ** changes to pExpr so that it refers directly to the source table
98669 ** of the subquery rather the result set of the subquery.
98670 */
98671 static Expr *substExpr(
98672   sqlite3 *db,        /* Report malloc errors to this connection */
98673   Expr *pExpr,        /* Expr in which substitution occurs */
98674   int iTable,         /* Table to be substituted */
98675   ExprList *pEList    /* Substitute expressions */
98676 ){
98677   if( pExpr==0 ) return 0;
98678   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
98679     if( pExpr->iColumn<0 ){
98680       pExpr->op = TK_NULL;
98681     }else{
98682       Expr *pNew;
98683       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
98684       assert( pExpr->pLeft==0 && pExpr->pRight==0 );
98685       pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
98686       sqlite3ExprDelete(db, pExpr);
98687       pExpr = pNew;
98688     }
98689   }else{
98690     pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
98691     pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
98692     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
98693       substSelect(db, pExpr->x.pSelect, iTable, pEList);
98694     }else{
98695       substExprList(db, pExpr->x.pList, iTable, pEList);
98696     }
98697   }
98698   return pExpr;
98699 }
98700 static void substExprList(
98701   sqlite3 *db,         /* Report malloc errors here */
98702   ExprList *pList,     /* List to scan and in which to make substitutes */
98703   int iTable,          /* Table to be substituted */
98704   ExprList *pEList     /* Substitute values */
98705 ){
98706   int i;
98707   if( pList==0 ) return;
98708   for(i=0; i<pList->nExpr; i++){
98709     pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
98710   }
98711 }
98712 static void substSelect(
98713   sqlite3 *db,         /* Report malloc errors here */
98714   Select *p,           /* SELECT statement in which to make substitutions */
98715   int iTable,          /* Table to be replaced */
98716   ExprList *pEList     /* Substitute values */
98717 ){
98718   SrcList *pSrc;
98719   struct SrcList_item *pItem;
98720   int i;
98721   if( !p ) return;
98722   substExprList(db, p->pEList, iTable, pEList);
98723   substExprList(db, p->pGroupBy, iTable, pEList);
98724   substExprList(db, p->pOrderBy, iTable, pEList);
98725   p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
98726   p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
98727   substSelect(db, p->pPrior, iTable, pEList);
98728   pSrc = p->pSrc;
98729   assert( pSrc );  /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
98730   if( ALWAYS(pSrc) ){
98731     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
98732       substSelect(db, pItem->pSelect, iTable, pEList);
98733     }
98734   }
98735 }
98736 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
98737
98738 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
98739 /*
98740 ** This routine attempts to flatten subqueries as a performance optimization.
98741 ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
98742 **
98743 ** To understand the concept of flattening, consider the following
98744 ** query:
98745 **
98746 **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
98747 **
98748 ** The default way of implementing this query is to execute the
98749 ** subquery first and store the results in a temporary table, then
98750 ** run the outer query on that temporary table.  This requires two
98751 ** passes over the data.  Furthermore, because the temporary table
98752 ** has no indices, the WHERE clause on the outer query cannot be
98753 ** optimized.
98754 **
98755 ** This routine attempts to rewrite queries such as the above into
98756 ** a single flat select, like this:
98757 **
98758 **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
98759 **
98760 ** The code generated for this simpification gives the same result
98761 ** but only has to scan the data once.  And because indices might 
98762 ** exist on the table t1, a complete scan of the data might be
98763 ** avoided.
98764 **
98765 ** Flattening is only attempted if all of the following are true:
98766 **
98767 **   (1)  The subquery and the outer query do not both use aggregates.
98768 **
98769 **   (2)  The subquery is not an aggregate or the outer query is not a join.
98770 **
98771 **   (3)  The subquery is not the right operand of a left outer join
98772 **        (Originally ticket #306.  Strengthened by ticket #3300)
98773 **
98774 **   (4)  The subquery is not DISTINCT.
98775 **
98776 **  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
98777 **        sub-queries that were excluded from this optimization. Restriction 
98778 **        (4) has since been expanded to exclude all DISTINCT subqueries.
98779 **
98780 **   (6)  The subquery does not use aggregates or the outer query is not
98781 **        DISTINCT.
98782 **
98783 **   (7)  The subquery has a FROM clause.  TODO:  For subqueries without
98784 **        A FROM clause, consider adding a FROM close with the special
98785 **        table sqlite_once that consists of a single row containing a
98786 **        single NULL.
98787 **
98788 **   (8)  The subquery does not use LIMIT or the outer query is not a join.
98789 **
98790 **   (9)  The subquery does not use LIMIT or the outer query does not use
98791 **        aggregates.
98792 **
98793 **  (10)  The subquery does not use aggregates or the outer query does not
98794 **        use LIMIT.
98795 **
98796 **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
98797 **
98798 **  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
98799 **        a separate restriction deriving from ticket #350.
98800 **
98801 **  (13)  The subquery and outer query do not both use LIMIT.
98802 **
98803 **  (14)  The subquery does not use OFFSET.
98804 **
98805 **  (15)  The outer query is not part of a compound select or the
98806 **        subquery does not have a LIMIT clause.
98807 **        (See ticket #2339 and ticket [02a8e81d44]).
98808 **
98809 **  (16)  The outer query is not an aggregate or the subquery does
98810 **        not contain ORDER BY.  (Ticket #2942)  This used to not matter
98811 **        until we introduced the group_concat() function.  
98812 **
98813 **  (17)  The sub-query is not a compound select, or it is a UNION ALL 
98814 **        compound clause made up entirely of non-aggregate queries, and 
98815 **        the parent query:
98816 **
98817 **          * is not itself part of a compound select,
98818 **          * is not an aggregate or DISTINCT query, and
98819 **          * is not a join
98820 **
98821 **        The parent and sub-query may contain WHERE clauses. Subject to
98822 **        rules (11), (13) and (14), they may also contain ORDER BY,
98823 **        LIMIT and OFFSET clauses.  The subquery cannot use any compound
98824 **        operator other than UNION ALL because all the other compound
98825 **        operators have an implied DISTINCT which is disallowed by
98826 **        restriction (4).
98827 **
98828 **        Also, each component of the sub-query must return the same number
98829 **        of result columns. This is actually a requirement for any compound
98830 **        SELECT statement, but all the code here does is make sure that no
98831 **        such (illegal) sub-query is flattened. The caller will detect the
98832 **        syntax error and return a detailed message.
98833 **
98834 **  (18)  If the sub-query is a compound select, then all terms of the
98835 **        ORDER by clause of the parent must be simple references to 
98836 **        columns of the sub-query.
98837 **
98838 **  (19)  The subquery does not use LIMIT or the outer query does not
98839 **        have a WHERE clause.
98840 **
98841 **  (20)  If the sub-query is a compound select, then it must not use
98842 **        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
98843 **        somewhat by saying that the terms of the ORDER BY clause must
98844 **        appear as unmodified result columns in the outer query.  But we
98845 **        have other optimizations in mind to deal with that case.
98846 **
98847 **  (21)  The subquery does not use LIMIT or the outer query is not
98848 **        DISTINCT.  (See ticket [752e1646fc]).
98849 **
98850 ** In this routine, the "p" parameter is a pointer to the outer query.
98851 ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
98852 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
98853 **
98854 ** If flattening is not attempted, this routine is a no-op and returns 0.
98855 ** If flattening is attempted this routine returns 1.
98856 **
98857 ** All of the expression analysis must occur on both the outer query and
98858 ** the subquery before this routine runs.
98859 */
98860 static int flattenSubquery(
98861   Parse *pParse,       /* Parsing context */
98862   Select *p,           /* The parent or outer SELECT statement */
98863   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
98864   int isAgg,           /* True if outer SELECT uses aggregate functions */
98865   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
98866 ){
98867   const char *zSavedAuthContext = pParse->zAuthContext;
98868   Select *pParent;
98869   Select *pSub;       /* The inner query or "subquery" */
98870   Select *pSub1;      /* Pointer to the rightmost select in sub-query */
98871   SrcList *pSrc;      /* The FROM clause of the outer query */
98872   SrcList *pSubSrc;   /* The FROM clause of the subquery */
98873   ExprList *pList;    /* The result set of the outer query */
98874   int iParent;        /* VDBE cursor number of the pSub result set temp table */
98875   int i;              /* Loop counter */
98876   Expr *pWhere;                    /* The WHERE clause */
98877   struct SrcList_item *pSubitem;   /* The subquery */
98878   sqlite3 *db = pParse->db;
98879
98880   /* Check to see if flattening is permitted.  Return 0 if not.
98881   */
98882   assert( p!=0 );
98883   assert( p->pPrior==0 );  /* Unable to flatten compound queries */
98884   if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
98885   pSrc = p->pSrc;
98886   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
98887   pSubitem = &pSrc->a[iFrom];
98888   iParent = pSubitem->iCursor;
98889   pSub = pSubitem->pSelect;
98890   assert( pSub!=0 );
98891   if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
98892   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
98893   pSubSrc = pSub->pSrc;
98894   assert( pSubSrc );
98895   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
98896   ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
98897   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
98898   ** became arbitrary expressions, we were forced to add restrictions (13)
98899   ** and (14). */
98900   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
98901   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
98902   if( p->pRightmost && pSub->pLimit ){
98903     return 0;                                            /* Restriction (15) */
98904   }
98905   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
98906   if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (5)  */
98907   if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
98908      return 0;         /* Restrictions (8)(9) */
98909   }
98910   if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
98911      return 0;         /* Restriction (6)  */
98912   }
98913   if( p->pOrderBy && pSub->pOrderBy ){
98914      return 0;                                           /* Restriction (11) */
98915   }
98916   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
98917   if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
98918   if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
98919      return 0;         /* Restriction (21) */
98920   }
98921
98922   /* OBSOLETE COMMENT 1:
98923   ** Restriction 3:  If the subquery is a join, make sure the subquery is 
98924   ** not used as the right operand of an outer join.  Examples of why this
98925   ** is not allowed:
98926   **
98927   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
98928   **
98929   ** If we flatten the above, we would get
98930   **
98931   **         (t1 LEFT OUTER JOIN t2) JOIN t3
98932   **
98933   ** which is not at all the same thing.
98934   **
98935   ** OBSOLETE COMMENT 2:
98936   ** Restriction 12:  If the subquery is the right operand of a left outer
98937   ** join, make sure the subquery has no WHERE clause.
98938   ** An examples of why this is not allowed:
98939   **
98940   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
98941   **
98942   ** If we flatten the above, we would get
98943   **
98944   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
98945   **
98946   ** But the t2.x>0 test will always fail on a NULL row of t2, which
98947   ** effectively converts the OUTER JOIN into an INNER JOIN.
98948   **
98949   ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
98950   ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
98951   ** is fraught with danger.  Best to avoid the whole thing.  If the
98952   ** subquery is the right term of a LEFT JOIN, then do not flatten.
98953   */
98954   if( (pSubitem->jointype & JT_OUTER)!=0 ){
98955     return 0;
98956   }
98957
98958   /* Restriction 17: If the sub-query is a compound SELECT, then it must
98959   ** use only the UNION ALL operator. And none of the simple select queries
98960   ** that make up the compound SELECT are allowed to be aggregate or distinct
98961   ** queries.
98962   */
98963   if( pSub->pPrior ){
98964     if( pSub->pOrderBy ){
98965       return 0;  /* Restriction 20 */
98966     }
98967     if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
98968       return 0;
98969     }
98970     for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
98971       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
98972       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
98973       assert( pSub->pSrc!=0 );
98974       if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
98975        || (pSub1->pPrior && pSub1->op!=TK_ALL) 
98976        || pSub1->pSrc->nSrc<1
98977        || pSub->pEList->nExpr!=pSub1->pEList->nExpr
98978       ){
98979         return 0;
98980       }
98981       testcase( pSub1->pSrc->nSrc>1 );
98982     }
98983
98984     /* Restriction 18. */
98985     if( p->pOrderBy ){
98986       int ii;
98987       for(ii=0; ii<p->pOrderBy->nExpr; ii++){
98988         if( p->pOrderBy->a[ii].iOrderByCol==0 ) return 0;
98989       }
98990     }
98991   }
98992
98993   /***** If we reach this point, flattening is permitted. *****/
98994
98995   /* Authorize the subquery */
98996   pParse->zAuthContext = pSubitem->zName;
98997   TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
98998   testcase( i==SQLITE_DENY );
98999   pParse->zAuthContext = zSavedAuthContext;
99000
99001   /* If the sub-query is a compound SELECT statement, then (by restrictions
99002   ** 17 and 18 above) it must be a UNION ALL and the parent query must 
99003   ** be of the form:
99004   **
99005   **     SELECT <expr-list> FROM (<sub-query>) <where-clause> 
99006   **
99007   ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
99008   ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or 
99009   ** OFFSET clauses and joins them to the left-hand-side of the original
99010   ** using UNION ALL operators. In this case N is the number of simple
99011   ** select statements in the compound sub-query.
99012   **
99013   ** Example:
99014   **
99015   **     SELECT a+1 FROM (
99016   **        SELECT x FROM tab
99017   **        UNION ALL
99018   **        SELECT y FROM tab
99019   **        UNION ALL
99020   **        SELECT abs(z*2) FROM tab2
99021   **     ) WHERE a!=5 ORDER BY 1
99022   **
99023   ** Transformed into:
99024   **
99025   **     SELECT x+1 FROM tab WHERE x+1!=5
99026   **     UNION ALL
99027   **     SELECT y+1 FROM tab WHERE y+1!=5
99028   **     UNION ALL
99029   **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
99030   **     ORDER BY 1
99031   **
99032   ** We call this the "compound-subquery flattening".
99033   */
99034   for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
99035     Select *pNew;
99036     ExprList *pOrderBy = p->pOrderBy;
99037     Expr *pLimit = p->pLimit;
99038     Expr *pOffset = p->pOffset;
99039     Select *pPrior = p->pPrior;
99040     p->pOrderBy = 0;
99041     p->pSrc = 0;
99042     p->pPrior = 0;
99043     p->pLimit = 0;
99044     p->pOffset = 0;
99045     pNew = sqlite3SelectDup(db, p, 0);
99046     p->pOffset = pOffset;
99047     p->pLimit = pLimit;
99048     p->pOrderBy = pOrderBy;
99049     p->pSrc = pSrc;
99050     p->op = TK_ALL;
99051     p->pRightmost = 0;
99052     if( pNew==0 ){
99053       pNew = pPrior;
99054     }else{
99055       pNew->pPrior = pPrior;
99056       pNew->pRightmost = 0;
99057     }
99058     p->pPrior = pNew;
99059     if( db->mallocFailed ) return 1;
99060   }
99061
99062   /* Begin flattening the iFrom-th entry of the FROM clause 
99063   ** in the outer query.
99064   */
99065   pSub = pSub1 = pSubitem->pSelect;
99066
99067   /* Delete the transient table structure associated with the
99068   ** subquery
99069   */
99070   sqlite3DbFree(db, pSubitem->zDatabase);
99071   sqlite3DbFree(db, pSubitem->zName);
99072   sqlite3DbFree(db, pSubitem->zAlias);
99073   pSubitem->zDatabase = 0;
99074   pSubitem->zName = 0;
99075   pSubitem->zAlias = 0;
99076   pSubitem->pSelect = 0;
99077
99078   /* Defer deleting the Table object associated with the
99079   ** subquery until code generation is
99080   ** complete, since there may still exist Expr.pTab entries that
99081   ** refer to the subquery even after flattening.  Ticket #3346.
99082   **
99083   ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
99084   */
99085   if( ALWAYS(pSubitem->pTab!=0) ){
99086     Table *pTabToDel = pSubitem->pTab;
99087     if( pTabToDel->nRef==1 ){
99088       Parse *pToplevel = sqlite3ParseToplevel(pParse);
99089       pTabToDel->pNextZombie = pToplevel->pZombieTab;
99090       pToplevel->pZombieTab = pTabToDel;
99091     }else{
99092       pTabToDel->nRef--;
99093     }
99094     pSubitem->pTab = 0;
99095   }
99096
99097   /* The following loop runs once for each term in a compound-subquery
99098   ** flattening (as described above).  If we are doing a different kind
99099   ** of flattening - a flattening other than a compound-subquery flattening -
99100   ** then this loop only runs once.
99101   **
99102   ** This loop moves all of the FROM elements of the subquery into the
99103   ** the FROM clause of the outer query.  Before doing this, remember
99104   ** the cursor number for the original outer query FROM element in
99105   ** iParent.  The iParent cursor will never be used.  Subsequent code
99106   ** will scan expressions looking for iParent references and replace
99107   ** those references with expressions that resolve to the subquery FROM
99108   ** elements we are now copying in.
99109   */
99110   for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
99111     int nSubSrc;
99112     u8 jointype = 0;
99113     pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
99114     nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
99115     pSrc = pParent->pSrc;     /* FROM clause of the outer query */
99116
99117     if( pSrc ){
99118       assert( pParent==p );  /* First time through the loop */
99119       jointype = pSubitem->jointype;
99120     }else{
99121       assert( pParent!=p );  /* 2nd and subsequent times through the loop */
99122       pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
99123       if( pSrc==0 ){
99124         assert( db->mallocFailed );
99125         break;
99126       }
99127     }
99128
99129     /* The subquery uses a single slot of the FROM clause of the outer
99130     ** query.  If the subquery has more than one element in its FROM clause,
99131     ** then expand the outer query to make space for it to hold all elements
99132     ** of the subquery.
99133     **
99134     ** Example:
99135     **
99136     **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
99137     **
99138     ** The outer query has 3 slots in its FROM clause.  One slot of the
99139     ** outer query (the middle slot) is used by the subquery.  The next
99140     ** block of code will expand the out query to 4 slots.  The middle
99141     ** slot is expanded to two slots in order to make space for the
99142     ** two elements in the FROM clause of the subquery.
99143     */
99144     if( nSubSrc>1 ){
99145       pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
99146       if( db->mallocFailed ){
99147         break;
99148       }
99149     }
99150
99151     /* Transfer the FROM clause terms from the subquery into the
99152     ** outer query.
99153     */
99154     for(i=0; i<nSubSrc; i++){
99155       sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
99156       pSrc->a[i+iFrom] = pSubSrc->a[i];
99157       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
99158     }
99159     pSrc->a[iFrom].jointype = jointype;
99160   
99161     /* Now begin substituting subquery result set expressions for 
99162     ** references to the iParent in the outer query.
99163     ** 
99164     ** Example:
99165     **
99166     **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
99167     **   \                     \_____________ subquery __________/          /
99168     **    \_____________________ outer query ______________________________/
99169     **
99170     ** We look at every expression in the outer query and every place we see
99171     ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
99172     */
99173     pList = pParent->pEList;
99174     for(i=0; i<pList->nExpr; i++){
99175       if( pList->a[i].zName==0 ){
99176         char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan);
99177         sqlite3Dequote(zName);
99178         pList->a[i].zName = zName;
99179       }
99180     }
99181     substExprList(db, pParent->pEList, iParent, pSub->pEList);
99182     if( isAgg ){
99183       substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
99184       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
99185     }
99186     if( pSub->pOrderBy ){
99187       assert( pParent->pOrderBy==0 );
99188       pParent->pOrderBy = pSub->pOrderBy;
99189       pSub->pOrderBy = 0;
99190     }else if( pParent->pOrderBy ){
99191       substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
99192     }
99193     if( pSub->pWhere ){
99194       pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
99195     }else{
99196       pWhere = 0;
99197     }
99198     if( subqueryIsAgg ){
99199       assert( pParent->pHaving==0 );
99200       pParent->pHaving = pParent->pWhere;
99201       pParent->pWhere = pWhere;
99202       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
99203       pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving, 
99204                                   sqlite3ExprDup(db, pSub->pHaving, 0));
99205       assert( pParent->pGroupBy==0 );
99206       pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
99207     }else{
99208       pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
99209       pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
99210     }
99211   
99212     /* The flattened query is distinct if either the inner or the
99213     ** outer query is distinct. 
99214     */
99215     pParent->selFlags |= pSub->selFlags & SF_Distinct;
99216   
99217     /*
99218     ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
99219     **
99220     ** One is tempted to try to add a and b to combine the limits.  But this
99221     ** does not work if either limit is negative.
99222     */
99223     if( pSub->pLimit ){
99224       pParent->pLimit = pSub->pLimit;
99225       pSub->pLimit = 0;
99226     }
99227   }
99228
99229   /* Finially, delete what is left of the subquery and return
99230   ** success.
99231   */
99232   sqlite3SelectDelete(db, pSub1);
99233
99234   return 1;
99235 }
99236 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
99237
99238 /*
99239 ** Based on the contents of the AggInfo structure indicated by the first
99240 ** argument, this function checks if the following are true:
99241 **
99242 **    * the query contains just a single aggregate function,
99243 **    * the aggregate function is either min() or max(), and
99244 **    * the argument to the aggregate function is a column value.
99245 **
99246 ** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX
99247 ** is returned as appropriate. Also, *ppMinMax is set to point to the 
99248 ** list of arguments passed to the aggregate before returning.
99249 **
99250 ** Or, if the conditions above are not met, *ppMinMax is set to 0 and
99251 ** WHERE_ORDERBY_NORMAL is returned.
99252 */
99253 static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){
99254   int eRet = WHERE_ORDERBY_NORMAL;          /* Return value */
99255
99256   *ppMinMax = 0;
99257   if( pAggInfo->nFunc==1 ){
99258     Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */
99259     ExprList *pEList = pExpr->x.pList;      /* Arguments to agg function */
99260
99261     assert( pExpr->op==TK_AGG_FUNCTION );
99262     if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){
99263       const char *zFunc = pExpr->u.zToken;
99264       if( sqlite3StrICmp(zFunc, "min")==0 ){
99265         eRet = WHERE_ORDERBY_MIN;
99266         *ppMinMax = pEList;
99267       }else if( sqlite3StrICmp(zFunc, "max")==0 ){
99268         eRet = WHERE_ORDERBY_MAX;
99269         *ppMinMax = pEList;
99270       }
99271     }
99272   }
99273
99274   assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 );
99275   return eRet;
99276 }
99277
99278 /*
99279 ** The select statement passed as the first argument is an aggregate query.
99280 ** The second argment is the associated aggregate-info object. This 
99281 ** function tests if the SELECT is of the form:
99282 **
99283 **   SELECT count(*) FROM <tbl>
99284 **
99285 ** where table is a database table, not a sub-select or view. If the query
99286 ** does match this pattern, then a pointer to the Table object representing
99287 ** <tbl> is returned. Otherwise, 0 is returned.
99288 */
99289 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
99290   Table *pTab;
99291   Expr *pExpr;
99292
99293   assert( !p->pGroupBy );
99294
99295   if( p->pWhere || p->pEList->nExpr!=1 
99296    || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
99297   ){
99298     return 0;
99299   }
99300   pTab = p->pSrc->a[0].pTab;
99301   pExpr = p->pEList->a[0].pExpr;
99302   assert( pTab && !pTab->pSelect && pExpr );
99303
99304   if( IsVirtual(pTab) ) return 0;
99305   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
99306   if( NEVER(pAggInfo->nFunc==0) ) return 0;
99307   if( (pAggInfo->aFunc[0].pFunc->flags&SQLITE_FUNC_COUNT)==0 ) return 0;
99308   if( pExpr->flags&EP_Distinct ) return 0;
99309
99310   return pTab;
99311 }
99312
99313 /*
99314 ** If the source-list item passed as an argument was augmented with an
99315 ** INDEXED BY clause, then try to locate the specified index. If there
99316 ** was such a clause and the named index cannot be found, return 
99317 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate 
99318 ** pFrom->pIndex and return SQLITE_OK.
99319 */
99320 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
99321   if( pFrom->pTab && pFrom->zIndex ){
99322     Table *pTab = pFrom->pTab;
99323     char *zIndex = pFrom->zIndex;
99324     Index *pIdx;
99325     for(pIdx=pTab->pIndex; 
99326         pIdx && sqlite3StrICmp(pIdx->zName, zIndex); 
99327         pIdx=pIdx->pNext
99328     );
99329     if( !pIdx ){
99330       sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
99331       pParse->checkSchema = 1;
99332       return SQLITE_ERROR;
99333     }
99334     pFrom->pIndex = pIdx;
99335   }
99336   return SQLITE_OK;
99337 }
99338 /*
99339 ** Detect compound SELECT statements that use an ORDER BY clause with 
99340 ** an alternative collating sequence.
99341 **
99342 **    SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
99343 **
99344 ** These are rewritten as a subquery:
99345 **
99346 **    SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
99347 **     ORDER BY ... COLLATE ...
99348 **
99349 ** This transformation is necessary because the multiSelectOrderBy() routine
99350 ** above that generates the code for a compound SELECT with an ORDER BY clause
99351 ** uses a merge algorithm that requires the same collating sequence on the
99352 ** result columns as on the ORDER BY clause.  See ticket
99353 ** http://www.sqlite.org/src/info/6709574d2a
99354 **
99355 ** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
99356 ** The UNION ALL operator works fine with multiSelectOrderBy() even when
99357 ** there are COLLATE terms in the ORDER BY.
99358 */
99359 static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
99360   int i;
99361   Select *pNew;
99362   Select *pX;
99363   sqlite3 *db;
99364   struct ExprList_item *a;
99365   SrcList *pNewSrc;
99366   Parse *pParse;
99367   Token dummy;
99368
99369   if( p->pPrior==0 ) return WRC_Continue;
99370   if( p->pOrderBy==0 ) return WRC_Continue;
99371   for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
99372   if( pX==0 ) return WRC_Continue;
99373   a = p->pOrderBy->a;
99374   for(i=p->pOrderBy->nExpr-1; i>=0; i--){
99375     if( a[i].pExpr->flags & EP_Collate ) break;
99376   }
99377   if( i<0 ) return WRC_Continue;
99378
99379   /* If we reach this point, that means the transformation is required. */
99380
99381   pParse = pWalker->pParse;
99382   db = pParse->db;
99383   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
99384   if( pNew==0 ) return WRC_Abort;
99385   memset(&dummy, 0, sizeof(dummy));
99386   pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
99387   if( pNewSrc==0 ) return WRC_Abort;
99388   *pNew = *p;
99389   p->pSrc = pNewSrc;
99390   p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ALL, 0));
99391   p->op = TK_SELECT;
99392   p->pWhere = 0;
99393   pNew->pGroupBy = 0;
99394   pNew->pHaving = 0;
99395   pNew->pOrderBy = 0;
99396   p->pPrior = 0;
99397   pNew->pLimit = 0;
99398   pNew->pOffset = 0;
99399   return WRC_Continue;
99400 }
99401
99402 /*
99403 ** This routine is a Walker callback for "expanding" a SELECT statement.
99404 ** "Expanding" means to do the following:
99405 **
99406 **    (1)  Make sure VDBE cursor numbers have been assigned to every
99407 **         element of the FROM clause.
99408 **
99409 **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that 
99410 **         defines FROM clause.  When views appear in the FROM clause,
99411 **         fill pTabList->a[].pSelect with a copy of the SELECT statement
99412 **         that implements the view.  A copy is made of the view's SELECT
99413 **         statement so that we can freely modify or delete that statement
99414 **         without worrying about messing up the presistent representation
99415 **         of the view.
99416 **
99417 **    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
99418 **         on joins and the ON and USING clause of joins.
99419 **
99420 **    (4)  Scan the list of columns in the result set (pEList) looking
99421 **         for instances of the "*" operator or the TABLE.* operator.
99422 **         If found, expand each "*" to be every column in every table
99423 **         and TABLE.* to be every column in TABLE.
99424 **
99425 */
99426 static int selectExpander(Walker *pWalker, Select *p){
99427   Parse *pParse = pWalker->pParse;
99428   int i, j, k;
99429   SrcList *pTabList;
99430   ExprList *pEList;
99431   struct SrcList_item *pFrom;
99432   sqlite3 *db = pParse->db;
99433   Expr *pE, *pRight, *pExpr;
99434   u16 selFlags = p->selFlags;
99435
99436   p->selFlags |= SF_Expanded;
99437   if( db->mallocFailed  ){
99438     return WRC_Abort;
99439   }
99440   if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){
99441     return WRC_Prune;
99442   }
99443   pTabList = p->pSrc;
99444   pEList = p->pEList;
99445
99446   /* Make sure cursor numbers have been assigned to all entries in
99447   ** the FROM clause of the SELECT statement.
99448   */
99449   sqlite3SrcListAssignCursors(pParse, pTabList);
99450
99451   /* Look up every table named in the FROM clause of the select.  If
99452   ** an entry of the FROM clause is a subquery instead of a table or view,
99453   ** then create a transient table structure to describe the subquery.
99454   */
99455   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
99456     Table *pTab;
99457     if( pFrom->pTab!=0 ){
99458       /* This statement has already been prepared.  There is no need
99459       ** to go further. */
99460       assert( i==0 );
99461       return WRC_Prune;
99462     }
99463     if( pFrom->zName==0 ){
99464 #ifndef SQLITE_OMIT_SUBQUERY
99465       Select *pSel = pFrom->pSelect;
99466       /* A sub-query in the FROM clause of a SELECT */
99467       assert( pSel!=0 );
99468       assert( pFrom->pTab==0 );
99469       sqlite3WalkSelect(pWalker, pSel);
99470       pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
99471       if( pTab==0 ) return WRC_Abort;
99472       pTab->nRef = 1;
99473       pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
99474       while( pSel->pPrior ){ pSel = pSel->pPrior; }
99475       selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
99476       pTab->iPKey = -1;
99477       pTab->nRowEst = 1000000;
99478       pTab->tabFlags |= TF_Ephemeral;
99479 #endif
99480     }else{
99481       /* An ordinary table or view name in the FROM clause */
99482       assert( pFrom->pTab==0 );
99483       pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
99484       if( pTab==0 ) return WRC_Abort;
99485       if( pTab->nRef==0xffff ){
99486         sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
99487            pTab->zName);
99488         pFrom->pTab = 0;
99489         return WRC_Abort;
99490       }
99491       pTab->nRef++;
99492 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
99493       if( pTab->pSelect || IsVirtual(pTab) ){
99494         /* We reach here if the named table is a really a view */
99495         if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
99496         assert( pFrom->pSelect==0 );
99497         pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
99498         sqlite3WalkSelect(pWalker, pFrom->pSelect);
99499       }
99500 #endif
99501     }
99502
99503     /* Locate the index named by the INDEXED BY clause, if any. */
99504     if( sqlite3IndexedByLookup(pParse, pFrom) ){
99505       return WRC_Abort;
99506     }
99507   }
99508
99509   /* Process NATURAL keywords, and ON and USING clauses of joins.
99510   */
99511   if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
99512     return WRC_Abort;
99513   }
99514
99515   /* For every "*" that occurs in the column list, insert the names of
99516   ** all columns in all tables.  And for every TABLE.* insert the names
99517   ** of all columns in TABLE.  The parser inserted a special expression
99518   ** with the TK_ALL operator for each "*" that it found in the column list.
99519   ** The following code just has to locate the TK_ALL expressions and expand
99520   ** each one to the list of all columns in all tables.
99521   **
99522   ** The first loop just checks to see if there are any "*" operators
99523   ** that need expanding.
99524   */
99525   for(k=0; k<pEList->nExpr; k++){
99526     pE = pEList->a[k].pExpr;
99527     if( pE->op==TK_ALL ) break;
99528     assert( pE->op!=TK_DOT || pE->pRight!=0 );
99529     assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
99530     if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
99531   }
99532   if( k<pEList->nExpr ){
99533     /*
99534     ** If we get here it means the result set contains one or more "*"
99535     ** operators that need to be expanded.  Loop through each expression
99536     ** in the result set and expand them one by one.
99537     */
99538     struct ExprList_item *a = pEList->a;
99539     ExprList *pNew = 0;
99540     int flags = pParse->db->flags;
99541     int longNames = (flags & SQLITE_FullColNames)!=0
99542                       && (flags & SQLITE_ShortColNames)==0;
99543
99544     /* When processing FROM-clause subqueries, it is always the case
99545     ** that full_column_names=OFF and short_column_names=ON.  The
99546     ** sqlite3ResultSetOfSelect() routine makes it so. */
99547     assert( (p->selFlags & SF_NestedFrom)==0
99548           || ((flags & SQLITE_FullColNames)==0 &&
99549               (flags & SQLITE_ShortColNames)!=0) );
99550
99551     for(k=0; k<pEList->nExpr; k++){
99552       pE = a[k].pExpr;
99553       pRight = pE->pRight;
99554       assert( pE->op!=TK_DOT || pRight!=0 );
99555       if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pRight->op!=TK_ALL) ){
99556         /* This particular expression does not need to be expanded.
99557         */
99558         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
99559         if( pNew ){
99560           pNew->a[pNew->nExpr-1].zName = a[k].zName;
99561           pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
99562           a[k].zName = 0;
99563           a[k].zSpan = 0;
99564         }
99565         a[k].pExpr = 0;
99566       }else{
99567         /* This expression is a "*" or a "TABLE.*" and needs to be
99568         ** expanded. */
99569         int tableSeen = 0;      /* Set to 1 when TABLE matches */
99570         char *zTName = 0;       /* text of name of TABLE */
99571         if( pE->op==TK_DOT ){
99572           assert( pE->pLeft!=0 );
99573           assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
99574           zTName = pE->pLeft->u.zToken;
99575         }
99576         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
99577           Table *pTab = pFrom->pTab;
99578           Select *pSub = pFrom->pSelect;
99579           char *zTabName = pFrom->zAlias;
99580           const char *zSchemaName = 0;
99581           int iDb;
99582           if( zTabName==0 ){
99583             zTabName = pTab->zName;
99584           }
99585           if( db->mallocFailed ) break;
99586           if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
99587             pSub = 0;
99588             if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
99589               continue;
99590             }
99591             iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
99592             zSchemaName = iDb>=0 ? db->aDb[iDb].zName : "*";
99593           }
99594           for(j=0; j<pTab->nCol; j++){
99595             char *zName = pTab->aCol[j].zName;
99596             char *zColname;  /* The computed column name */
99597             char *zToFree;   /* Malloced string that needs to be freed */
99598             Token sColname;  /* Computed column name as a token */
99599
99600             assert( zName );
99601             if( zTName && pSub
99602              && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
99603             ){
99604               continue;
99605             }
99606
99607             /* If a column is marked as 'hidden' (currently only possible
99608             ** for virtual tables), do not include it in the expanded
99609             ** result-set list.
99610             */
99611             if( IsHiddenColumn(&pTab->aCol[j]) ){
99612               assert(IsVirtual(pTab));
99613               continue;
99614             }
99615             tableSeen = 1;
99616
99617             if( i>0 && zTName==0 ){
99618               if( (pFrom->jointype & JT_NATURAL)!=0
99619                 && tableAndColumnIndex(pTabList, i, zName, 0, 0)
99620               ){
99621                 /* In a NATURAL join, omit the join columns from the 
99622                 ** table to the right of the join */
99623                 continue;
99624               }
99625               if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
99626                 /* In a join with a USING clause, omit columns in the
99627                 ** using clause from the table on the right. */
99628                 continue;
99629               }
99630             }
99631             pRight = sqlite3Expr(db, TK_ID, zName);
99632             zColname = zName;
99633             zToFree = 0;
99634             if( longNames || pTabList->nSrc>1 ){
99635               Expr *pLeft;
99636               pLeft = sqlite3Expr(db, TK_ID, zTabName);
99637               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
99638               if( zSchemaName ){
99639                 pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
99640                 pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr, 0);
99641               }
99642               if( longNames ){
99643                 zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
99644                 zToFree = zColname;
99645               }
99646             }else{
99647               pExpr = pRight;
99648             }
99649             pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
99650             sColname.z = zColname;
99651             sColname.n = sqlite3Strlen30(zColname);
99652             sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
99653             if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
99654               struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
99655               if( pSub ){
99656                 pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
99657                 testcase( pX->zSpan==0 );
99658               }else{
99659                 pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
99660                                            zSchemaName, zTabName, zColname);
99661                 testcase( pX->zSpan==0 );
99662               }
99663               pX->bSpanIsTab = 1;
99664             }
99665             sqlite3DbFree(db, zToFree);
99666           }
99667         }
99668         if( !tableSeen ){
99669           if( zTName ){
99670             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
99671           }else{
99672             sqlite3ErrorMsg(pParse, "no tables specified");
99673           }
99674         }
99675       }
99676     }
99677     sqlite3ExprListDelete(db, pEList);
99678     p->pEList = pNew;
99679   }
99680 #if SQLITE_MAX_COLUMN
99681   if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
99682     sqlite3ErrorMsg(pParse, "too many columns in result set");
99683   }
99684 #endif
99685   return WRC_Continue;
99686 }
99687
99688 /*
99689 ** No-op routine for the parse-tree walker.
99690 **
99691 ** When this routine is the Walker.xExprCallback then expression trees
99692 ** are walked without any actions being taken at each node.  Presumably,
99693 ** when this routine is used for Walker.xExprCallback then 
99694 ** Walker.xSelectCallback is set to do something useful for every 
99695 ** subquery in the parser tree.
99696 */
99697 static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
99698   UNUSED_PARAMETER2(NotUsed, NotUsed2);
99699   return WRC_Continue;
99700 }
99701
99702 /*
99703 ** This routine "expands" a SELECT statement and all of its subqueries.
99704 ** For additional information on what it means to "expand" a SELECT
99705 ** statement, see the comment on the selectExpand worker callback above.
99706 **
99707 ** Expanding a SELECT statement is the first step in processing a
99708 ** SELECT statement.  The SELECT statement must be expanded before
99709 ** name resolution is performed.
99710 **
99711 ** If anything goes wrong, an error message is written into pParse.
99712 ** The calling function can detect the problem by looking at pParse->nErr
99713 ** and/or pParse->db->mallocFailed.
99714 */
99715 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
99716   Walker w;
99717   memset(&w, 0, sizeof(w));
99718   w.xSelectCallback = convertCompoundSelectToSubquery;
99719   w.xExprCallback = exprWalkNoop;
99720   w.pParse = pParse;
99721   sqlite3WalkSelect(&w, pSelect);
99722   w.xSelectCallback = selectExpander;
99723   sqlite3WalkSelect(&w, pSelect);
99724 }
99725
99726
99727 #ifndef SQLITE_OMIT_SUBQUERY
99728 /*
99729 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
99730 ** interface.
99731 **
99732 ** For each FROM-clause subquery, add Column.zType and Column.zColl
99733 ** information to the Table structure that represents the result set
99734 ** of that subquery.
99735 **
99736 ** The Table structure that represents the result set was constructed
99737 ** by selectExpander() but the type and collation information was omitted
99738 ** at that point because identifiers had not yet been resolved.  This
99739 ** routine is called after identifier resolution.
99740 */
99741 static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
99742   Parse *pParse;
99743   int i;
99744   SrcList *pTabList;
99745   struct SrcList_item *pFrom;
99746
99747   assert( p->selFlags & SF_Resolved );
99748   if( (p->selFlags & SF_HasTypeInfo)==0 ){
99749     p->selFlags |= SF_HasTypeInfo;
99750     pParse = pWalker->pParse;
99751     pTabList = p->pSrc;
99752     for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
99753       Table *pTab = pFrom->pTab;
99754       if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
99755         /* A sub-query in the FROM clause of a SELECT */
99756         Select *pSel = pFrom->pSelect;
99757         assert( pSel );
99758         while( pSel->pPrior ) pSel = pSel->pPrior;
99759         selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
99760       }
99761     }
99762   }
99763   return WRC_Continue;
99764 }
99765 #endif
99766
99767
99768 /*
99769 ** This routine adds datatype and collating sequence information to
99770 ** the Table structures of all FROM-clause subqueries in a
99771 ** SELECT statement.
99772 **
99773 ** Use this routine after name resolution.
99774 */
99775 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
99776 #ifndef SQLITE_OMIT_SUBQUERY
99777   Walker w;
99778   memset(&w, 0, sizeof(w));
99779   w.xSelectCallback = selectAddSubqueryTypeInfo;
99780   w.xExprCallback = exprWalkNoop;
99781   w.pParse = pParse;
99782   w.bSelectDepthFirst = 1;
99783   sqlite3WalkSelect(&w, pSelect);
99784 #endif
99785 }
99786
99787
99788 /*
99789 ** This routine sets up a SELECT statement for processing.  The
99790 ** following is accomplished:
99791 **
99792 **     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
99793 **     *  Ephemeral Table objects are created for all FROM-clause subqueries.
99794 **     *  ON and USING clauses are shifted into WHERE statements
99795 **     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
99796 **     *  Identifiers in expression are matched to tables.
99797 **
99798 ** This routine acts recursively on all subqueries within the SELECT.
99799 */
99800 SQLITE_PRIVATE void sqlite3SelectPrep(
99801   Parse *pParse,         /* The parser context */
99802   Select *p,             /* The SELECT statement being coded. */
99803   NameContext *pOuterNC  /* Name context for container */
99804 ){
99805   sqlite3 *db;
99806   if( NEVER(p==0) ) return;
99807   db = pParse->db;
99808   if( db->mallocFailed ) return;
99809   if( p->selFlags & SF_HasTypeInfo ) return;
99810   sqlite3SelectExpand(pParse, p);
99811   if( pParse->nErr || db->mallocFailed ) return;
99812   sqlite3ResolveSelectNames(pParse, p, pOuterNC);
99813   if( pParse->nErr || db->mallocFailed ) return;
99814   sqlite3SelectAddTypeInfo(pParse, p);
99815 }
99816
99817 /*
99818 ** Reset the aggregate accumulator.
99819 **
99820 ** The aggregate accumulator is a set of memory cells that hold
99821 ** intermediate results while calculating an aggregate.  This
99822 ** routine generates code that stores NULLs in all of those memory
99823 ** cells.
99824 */
99825 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
99826   Vdbe *v = pParse->pVdbe;
99827   int i;
99828   struct AggInfo_func *pFunc;
99829   if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
99830     return;
99831   }
99832   for(i=0; i<pAggInfo->nColumn; i++){
99833     sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
99834   }
99835   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
99836     sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
99837     if( pFunc->iDistinct>=0 ){
99838       Expr *pE = pFunc->pExpr;
99839       assert( !ExprHasProperty(pE, EP_xIsSelect) );
99840       if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
99841         sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
99842            "argument");
99843         pFunc->iDistinct = -1;
99844       }else{
99845         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);
99846         sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
99847                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
99848       }
99849     }
99850   }
99851 }
99852
99853 /*
99854 ** Invoke the OP_AggFinalize opcode for every aggregate function
99855 ** in the AggInfo structure.
99856 */
99857 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
99858   Vdbe *v = pParse->pVdbe;
99859   int i;
99860   struct AggInfo_func *pF;
99861   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
99862     ExprList *pList = pF->pExpr->x.pList;
99863     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
99864     sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
99865                       (void*)pF->pFunc, P4_FUNCDEF);
99866   }
99867 }
99868
99869 /*
99870 ** Update the accumulator memory cells for an aggregate based on
99871 ** the current cursor position.
99872 */
99873 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
99874   Vdbe *v = pParse->pVdbe;
99875   int i;
99876   int regHit = 0;
99877   int addrHitTest = 0;
99878   struct AggInfo_func *pF;
99879   struct AggInfo_col *pC;
99880
99881   pAggInfo->directMode = 1;
99882   sqlite3ExprCacheClear(pParse);
99883   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
99884     int nArg;
99885     int addrNext = 0;
99886     int regAgg;
99887     ExprList *pList = pF->pExpr->x.pList;
99888     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
99889     if( pList ){
99890       nArg = pList->nExpr;
99891       regAgg = sqlite3GetTempRange(pParse, nArg);
99892       sqlite3ExprCodeExprList(pParse, pList, regAgg, 1);
99893     }else{
99894       nArg = 0;
99895       regAgg = 0;
99896     }
99897     if( pF->iDistinct>=0 ){
99898       addrNext = sqlite3VdbeMakeLabel(v);
99899       assert( nArg==1 );
99900       codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
99901     }
99902     if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
99903       CollSeq *pColl = 0;
99904       struct ExprList_item *pItem;
99905       int j;
99906       assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
99907       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
99908         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
99909       }
99910       if( !pColl ){
99911         pColl = pParse->db->pDfltColl;
99912       }
99913       if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
99914       sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
99915     }
99916     sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
99917                       (void*)pF->pFunc, P4_FUNCDEF);
99918     sqlite3VdbeChangeP5(v, (u8)nArg);
99919     sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
99920     sqlite3ReleaseTempRange(pParse, regAgg, nArg);
99921     if( addrNext ){
99922       sqlite3VdbeResolveLabel(v, addrNext);
99923       sqlite3ExprCacheClear(pParse);
99924     }
99925   }
99926
99927   /* Before populating the accumulator registers, clear the column cache.
99928   ** Otherwise, if any of the required column values are already present 
99929   ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
99930   ** to pC->iMem. But by the time the value is used, the original register
99931   ** may have been used, invalidating the underlying buffer holding the
99932   ** text or blob value. See ticket [883034dcb5].
99933   **
99934   ** Another solution would be to change the OP_SCopy used to copy cached
99935   ** values to an OP_Copy.
99936   */
99937   if( regHit ){
99938     addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit);
99939   }
99940   sqlite3ExprCacheClear(pParse);
99941   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
99942     sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
99943   }
99944   pAggInfo->directMode = 0;
99945   sqlite3ExprCacheClear(pParse);
99946   if( addrHitTest ){
99947     sqlite3VdbeJumpHere(v, addrHitTest);
99948   }
99949 }
99950
99951 /*
99952 ** Add a single OP_Explain instruction to the VDBE to explain a simple
99953 ** count(*) query ("SELECT count(*) FROM pTab").
99954 */
99955 #ifndef SQLITE_OMIT_EXPLAIN
99956 static void explainSimpleCount(
99957   Parse *pParse,                  /* Parse context */
99958   Table *pTab,                    /* Table being queried */
99959   Index *pIdx                     /* Index used to optimize scan, or NULL */
99960 ){
99961   if( pParse->explain==2 ){
99962     char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s %s%s(~%d rows)",
99963         pTab->zName, 
99964         pIdx ? "USING COVERING INDEX " : "",
99965         pIdx ? pIdx->zName : "",
99966         pTab->nRowEst
99967     );
99968     sqlite3VdbeAddOp4(
99969         pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
99970     );
99971   }
99972 }
99973 #else
99974 # define explainSimpleCount(a,b,c)
99975 #endif
99976
99977 /*
99978 ** Generate code for the SELECT statement given in the p argument.  
99979 **
99980 ** The results are distributed in various ways depending on the
99981 ** contents of the SelectDest structure pointed to by argument pDest
99982 ** as follows:
99983 **
99984 **     pDest->eDest    Result
99985 **     ------------    -------------------------------------------
99986 **     SRT_Output      Generate a row of output (using the OP_ResultRow
99987 **                     opcode) for each row in the result set.
99988 **
99989 **     SRT_Mem         Only valid if the result is a single column.
99990 **                     Store the first column of the first result row
99991 **                     in register pDest->iSDParm then abandon the rest
99992 **                     of the query.  This destination implies "LIMIT 1".
99993 **
99994 **     SRT_Set         The result must be a single column.  Store each
99995 **                     row of result as the key in table pDest->iSDParm. 
99996 **                     Apply the affinity pDest->affSdst before storing
99997 **                     results.  Used to implement "IN (SELECT ...)".
99998 **
99999 **     SRT_Union       Store results as a key in a temporary table 
100000 **                     identified by pDest->iSDParm.
100001 **
100002 **     SRT_Except      Remove results from the temporary table pDest->iSDParm.
100003 **
100004 **     SRT_Table       Store results in temporary table pDest->iSDParm.
100005 **                     This is like SRT_EphemTab except that the table
100006 **                     is assumed to already be open.
100007 **
100008 **     SRT_EphemTab    Create an temporary table pDest->iSDParm and store
100009 **                     the result there. The cursor is left open after
100010 **                     returning.  This is like SRT_Table except that
100011 **                     this destination uses OP_OpenEphemeral to create
100012 **                     the table first.
100013 **
100014 **     SRT_Coroutine   Generate a co-routine that returns a new row of
100015 **                     results each time it is invoked.  The entry point
100016 **                     of the co-routine is stored in register pDest->iSDParm.
100017 **
100018 **     SRT_Exists      Store a 1 in memory cell pDest->iSDParm if the result
100019 **                     set is not empty.
100020 **
100021 **     SRT_Discard     Throw the results away.  This is used by SELECT
100022 **                     statements within triggers whose only purpose is
100023 **                     the side-effects of functions.
100024 **
100025 ** This routine returns the number of errors.  If any errors are
100026 ** encountered, then an appropriate error message is left in
100027 ** pParse->zErrMsg.
100028 **
100029 ** This routine does NOT free the Select structure passed in.  The
100030 ** calling function needs to do that.
100031 */
100032 SQLITE_PRIVATE int sqlite3Select(
100033   Parse *pParse,         /* The parser context */
100034   Select *p,             /* The SELECT statement being coded. */
100035   SelectDest *pDest      /* What to do with the query results */
100036 ){
100037   int i, j;              /* Loop counters */
100038   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
100039   Vdbe *v;               /* The virtual machine under construction */
100040   int isAgg;             /* True for select lists like "count(*)" */
100041   ExprList *pEList;      /* List of columns to extract. */
100042   SrcList *pTabList;     /* List of tables to select from */
100043   Expr *pWhere;          /* The WHERE clause.  May be NULL */
100044   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
100045   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
100046   Expr *pHaving;         /* The HAVING clause.  May be NULL */
100047   int rc = 1;            /* Value to return from this function */
100048   int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
100049   DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
100050   AggInfo sAggInfo;      /* Information used by aggregate queries */
100051   int iEnd;              /* Address of the end of the query */
100052   sqlite3 *db;           /* The database connection */
100053
100054 #ifndef SQLITE_OMIT_EXPLAIN
100055   int iRestoreSelectId = pParse->iSelectId;
100056   pParse->iSelectId = pParse->iNextSelectId++;
100057 #endif
100058
100059   db = pParse->db;
100060   if( p==0 || db->mallocFailed || pParse->nErr ){
100061     return 1;
100062   }
100063   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
100064   memset(&sAggInfo, 0, sizeof(sAggInfo));
100065
100066   if( IgnorableOrderby(pDest) ){
100067     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || 
100068            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
100069     /* If ORDER BY makes no difference in the output then neither does
100070     ** DISTINCT so it can be removed too. */
100071     sqlite3ExprListDelete(db, p->pOrderBy);
100072     p->pOrderBy = 0;
100073     p->selFlags &= ~SF_Distinct;
100074   }
100075   sqlite3SelectPrep(pParse, p, 0);
100076   pOrderBy = p->pOrderBy;
100077   pTabList = p->pSrc;
100078   pEList = p->pEList;
100079   if( pParse->nErr || db->mallocFailed ){
100080     goto select_end;
100081   }
100082   isAgg = (p->selFlags & SF_Aggregate)!=0;
100083   assert( pEList!=0 );
100084
100085   /* Begin generating code.
100086   */
100087   v = sqlite3GetVdbe(pParse);
100088   if( v==0 ) goto select_end;
100089
100090   /* If writing to memory or generating a set
100091   ** only a single column may be output.
100092   */
100093 #ifndef SQLITE_OMIT_SUBQUERY
100094   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
100095     goto select_end;
100096   }
100097 #endif
100098
100099   /* Generate code for all sub-queries in the FROM clause
100100   */
100101 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
100102   for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
100103     struct SrcList_item *pItem = &pTabList->a[i];
100104     SelectDest dest;
100105     Select *pSub = pItem->pSelect;
100106     int isAggSub;
100107
100108     if( pSub==0 ) continue;
100109
100110     /* Sometimes the code for a subquery will be generated more than
100111     ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
100112     ** for example.  In that case, do not regenerate the code to manifest
100113     ** a view or the co-routine to implement a view.  The first instance
100114     ** is sufficient, though the subroutine to manifest the view does need
100115     ** to be invoked again. */
100116     if( pItem->addrFillSub ){
100117       if( pItem->viaCoroutine==0 ){
100118         sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
100119       }
100120       continue;
100121     }
100122
100123     /* Increment Parse.nHeight by the height of the largest expression
100124     ** tree refered to by this, the parent select. The child select
100125     ** may contain expression trees of at most
100126     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
100127     ** more conservative than necessary, but much easier than enforcing
100128     ** an exact limit.
100129     */
100130     pParse->nHeight += sqlite3SelectExprHeight(p);
100131
100132     isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
100133     if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
100134       /* This subquery can be absorbed into its parent. */
100135       if( isAggSub ){
100136         isAgg = 1;
100137         p->selFlags |= SF_Aggregate;
100138       }
100139       i = -1;
100140     }else if( pTabList->nSrc==1 && (p->selFlags & SF_Materialize)==0
100141       && OptimizationEnabled(db, SQLITE_SubqCoroutine)
100142     ){
100143       /* Implement a co-routine that will return a single row of the result
100144       ** set on each invocation.
100145       */
100146       int addrTop;
100147       int addrEof;
100148       pItem->regReturn = ++pParse->nMem;
100149       addrEof = ++pParse->nMem;
100150       /* Before coding the OP_Goto to jump to the start of the main routine,
100151       ** ensure that the jump to the verify-schema routine has already
100152       ** been coded. Otherwise, the verify-schema would likely be coded as 
100153       ** part of the co-routine. If the main routine then accessed the 
100154       ** database before invoking the co-routine for the first time (for 
100155       ** example to initialize a LIMIT register from a sub-select), it would 
100156       ** be doing so without having verified the schema version and obtained 
100157       ** the required db locks. See ticket d6b36be38.  */
100158       sqlite3CodeVerifySchema(pParse, -1);
100159       sqlite3VdbeAddOp0(v, OP_Goto);
100160       addrTop = sqlite3VdbeAddOp1(v, OP_OpenPseudo, pItem->iCursor);
100161       sqlite3VdbeChangeP5(v, 1);
100162       VdbeComment((v, "coroutine for %s", pItem->pTab->zName));
100163       pItem->addrFillSub = addrTop;
100164       sqlite3VdbeAddOp2(v, OP_Integer, 0, addrEof);
100165       sqlite3VdbeChangeP5(v, 1);
100166       sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
100167       explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
100168       sqlite3Select(pParse, pSub, &dest);
100169       pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
100170       pItem->viaCoroutine = 1;
100171       sqlite3VdbeChangeP2(v, addrTop, dest.iSdst);
100172       sqlite3VdbeChangeP3(v, addrTop, dest.nSdst);
100173       sqlite3VdbeAddOp2(v, OP_Integer, 1, addrEof);
100174       sqlite3VdbeAddOp1(v, OP_Yield, pItem->regReturn);
100175       VdbeComment((v, "end %s", pItem->pTab->zName));
100176       sqlite3VdbeJumpHere(v, addrTop-1);
100177       sqlite3ClearTempRegCache(pParse);
100178     }else{
100179       /* Generate a subroutine that will fill an ephemeral table with
100180       ** the content of this subquery.  pItem->addrFillSub will point
100181       ** to the address of the generated subroutine.  pItem->regReturn
100182       ** is a register allocated to hold the subroutine return address
100183       */
100184       int topAddr;
100185       int onceAddr = 0;
100186       int retAddr;
100187       assert( pItem->addrFillSub==0 );
100188       pItem->regReturn = ++pParse->nMem;
100189       topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
100190       pItem->addrFillSub = topAddr+1;
100191       VdbeNoopComment((v, "materialize %s", pItem->pTab->zName));
100192       if( pItem->isCorrelated==0 ){
100193         /* If the subquery is not correlated and if we are not inside of
100194         ** a trigger, then we only need to compute the value of the subquery
100195         ** once. */
100196         onceAddr = sqlite3CodeOnce(pParse);
100197       }
100198       sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
100199       explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
100200       sqlite3Select(pParse, pSub, &dest);
100201       pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
100202       if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
100203       retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
100204       VdbeComment((v, "end %s", pItem->pTab->zName));
100205       sqlite3VdbeChangeP1(v, topAddr, retAddr);
100206       sqlite3ClearTempRegCache(pParse);
100207     }
100208     if( /*pParse->nErr ||*/ db->mallocFailed ){
100209       goto select_end;
100210     }
100211     pParse->nHeight -= sqlite3SelectExprHeight(p);
100212     pTabList = p->pSrc;
100213     if( !IgnorableOrderby(pDest) ){
100214       pOrderBy = p->pOrderBy;
100215     }
100216   }
100217   pEList = p->pEList;
100218 #endif
100219   pWhere = p->pWhere;
100220   pGroupBy = p->pGroupBy;
100221   pHaving = p->pHaving;
100222   sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
100223
100224 #ifndef SQLITE_OMIT_COMPOUND_SELECT
100225   /* If there is are a sequence of queries, do the earlier ones first.
100226   */
100227   if( p->pPrior ){
100228     if( p->pRightmost==0 ){
100229       Select *pLoop, *pRight = 0;
100230       int cnt = 0;
100231       int mxSelect;
100232       for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
100233         pLoop->pRightmost = p;
100234         pLoop->pNext = pRight;
100235         pRight = pLoop;
100236       }
100237       mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
100238       if( mxSelect && cnt>mxSelect ){
100239         sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
100240         goto select_end;
100241       }
100242     }
100243     rc = multiSelect(pParse, p, pDest);
100244     explainSetInteger(pParse->iSelectId, iRestoreSelectId);
100245     return rc;
100246   }
100247 #endif
100248
100249   /* If there is both a GROUP BY and an ORDER BY clause and they are
100250   ** identical, then disable the ORDER BY clause since the GROUP BY
100251   ** will cause elements to come out in the correct order.  This is
100252   ** an optimization - the correct answer should result regardless.
100253   ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER
100254   ** to disable this optimization for testing purposes.
100255   */
100256   if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy)==0
100257          && OptimizationEnabled(db, SQLITE_GroupByOrder) ){
100258     pOrderBy = 0;
100259   }
100260
100261   /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and 
100262   ** if the select-list is the same as the ORDER BY list, then this query
100263   ** can be rewritten as a GROUP BY. In other words, this:
100264   **
100265   **     SELECT DISTINCT xyz FROM ... ORDER BY xyz
100266   **
100267   ** is transformed to:
100268   **
100269   **     SELECT xyz FROM ... GROUP BY xyz
100270   **
100271   ** The second form is preferred as a single index (or temp-table) may be 
100272   ** used for both the ORDER BY and DISTINCT processing. As originally 
100273   ** written the query must use a temp-table for at least one of the ORDER 
100274   ** BY and DISTINCT, and an index or separate temp-table for the other.
100275   */
100276   if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct 
100277    && sqlite3ExprListCompare(pOrderBy, p->pEList)==0
100278   ){
100279     p->selFlags &= ~SF_Distinct;
100280     p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
100281     pGroupBy = p->pGroupBy;
100282     pOrderBy = 0;
100283     /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
100284     ** the sDistinct.isTnct is still set.  Hence, isTnct represents the
100285     ** original setting of the SF_Distinct flag, not the current setting */
100286     assert( sDistinct.isTnct );
100287   }
100288
100289   /* If there is an ORDER BY clause, then this sorting
100290   ** index might end up being unused if the data can be 
100291   ** extracted in pre-sorted order.  If that is the case, then the
100292   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
100293   ** we figure out that the sorting index is not needed.  The addrSortIndex
100294   ** variable is used to facilitate that change.
100295   */
100296   if( pOrderBy ){
100297     KeyInfo *pKeyInfo;
100298     pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
100299     pOrderBy->iECursor = pParse->nTab++;
100300     p->addrOpenEphm[2] = addrSortIndex =
100301       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
100302                            pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
100303                            (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
100304   }else{
100305     addrSortIndex = -1;
100306   }
100307
100308   /* If the output is destined for a temporary table, open that table.
100309   */
100310   if( pDest->eDest==SRT_EphemTab ){
100311     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
100312   }
100313
100314   /* Set the limiter.
100315   */
100316   iEnd = sqlite3VdbeMakeLabel(v);
100317   p->nSelectRow = (double)LARGEST_INT64;
100318   computeLimitRegisters(pParse, p, iEnd);
100319   if( p->iLimit==0 && addrSortIndex>=0 ){
100320     sqlite3VdbeGetOp(v, addrSortIndex)->opcode = OP_SorterOpen;
100321     p->selFlags |= SF_UseSorter;
100322   }
100323
100324   /* Open a virtual index to use for the distinct set.
100325   */
100326   if( p->selFlags & SF_Distinct ){
100327     sDistinct.tabTnct = pParse->nTab++;
100328     sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
100329                                 sDistinct.tabTnct, 0, 0,
100330                                 (char*)keyInfoFromExprList(pParse, p->pEList),
100331                                 P4_KEYINFO_HANDOFF);
100332     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
100333     sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
100334   }else{
100335     sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
100336   }
100337
100338   if( !isAgg && pGroupBy==0 ){
100339     /* No aggregate functions and no GROUP BY clause */
100340     ExprList *pDist = (sDistinct.isTnct ? p->pEList : 0);
100341
100342     /* Begin the database scan. */
100343     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pOrderBy, pDist, 0,0);
100344     if( pWInfo==0 ) goto select_end;
100345     if( pWInfo->nRowOut < p->nSelectRow ) p->nSelectRow = pWInfo->nRowOut;
100346     if( pWInfo->eDistinct ) sDistinct.eTnctType = pWInfo->eDistinct;
100347     if( pOrderBy && pWInfo->nOBSat==pOrderBy->nExpr ) pOrderBy = 0;
100348
100349     /* If sorting index that was created by a prior OP_OpenEphemeral 
100350     ** instruction ended up not being needed, then change the OP_OpenEphemeral
100351     ** into an OP_Noop.
100352     */
100353     if( addrSortIndex>=0 && pOrderBy==0 ){
100354       sqlite3VdbeChangeToNoop(v, addrSortIndex);
100355       p->addrOpenEphm[2] = -1;
100356     }
100357
100358     /* Use the standard inner loop. */
100359     selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, &sDistinct, pDest,
100360                     pWInfo->iContinue, pWInfo->iBreak);
100361
100362     /* End the database scan loop.
100363     */
100364     sqlite3WhereEnd(pWInfo);
100365   }else{
100366     /* This case when there exist aggregate functions or a GROUP BY clause
100367     ** or both */
100368     NameContext sNC;    /* Name context for processing aggregate information */
100369     int iAMem;          /* First Mem address for storing current GROUP BY */
100370     int iBMem;          /* First Mem address for previous GROUP BY */
100371     int iUseFlag;       /* Mem address holding flag indicating that at least
100372                         ** one row of the input to the aggregator has been
100373                         ** processed */
100374     int iAbortFlag;     /* Mem address which causes query abort if positive */
100375     int groupBySort;    /* Rows come from source in GROUP BY order */
100376     int addrEnd;        /* End of processing for this SELECT */
100377     int sortPTab = 0;   /* Pseudotable used to decode sorting results */
100378     int sortOut = 0;    /* Output register from the sorter */
100379
100380     /* Remove any and all aliases between the result set and the
100381     ** GROUP BY clause.
100382     */
100383     if( pGroupBy ){
100384       int k;                        /* Loop counter */
100385       struct ExprList_item *pItem;  /* For looping over expression in a list */
100386
100387       for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
100388         pItem->iAlias = 0;
100389       }
100390       for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
100391         pItem->iAlias = 0;
100392       }
100393       if( p->nSelectRow>(double)100 ) p->nSelectRow = (double)100;
100394     }else{
100395       p->nSelectRow = (double)1;
100396     }
100397
100398  
100399     /* Create a label to jump to when we want to abort the query */
100400     addrEnd = sqlite3VdbeMakeLabel(v);
100401
100402     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
100403     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
100404     ** SELECT statement.
100405     */
100406     memset(&sNC, 0, sizeof(sNC));
100407     sNC.pParse = pParse;
100408     sNC.pSrcList = pTabList;
100409     sNC.pAggInfo = &sAggInfo;
100410     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
100411     sAggInfo.pGroupBy = pGroupBy;
100412     sqlite3ExprAnalyzeAggList(&sNC, pEList);
100413     sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
100414     if( pHaving ){
100415       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
100416     }
100417     sAggInfo.nAccumulator = sAggInfo.nColumn;
100418     for(i=0; i<sAggInfo.nFunc; i++){
100419       assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
100420       sNC.ncFlags |= NC_InAggFunc;
100421       sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
100422       sNC.ncFlags &= ~NC_InAggFunc;
100423     }
100424     if( db->mallocFailed ) goto select_end;
100425
100426     /* Processing for aggregates with GROUP BY is very different and
100427     ** much more complex than aggregates without a GROUP BY.
100428     */
100429     if( pGroupBy ){
100430       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
100431       int j1;             /* A-vs-B comparision jump */
100432       int addrOutputRow;  /* Start of subroutine that outputs a result row */
100433       int regOutputRow;   /* Return address register for output subroutine */
100434       int addrSetAbort;   /* Set the abort flag and return */
100435       int addrTopOfLoop;  /* Top of the input loop */
100436       int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
100437       int addrReset;      /* Subroutine for resetting the accumulator */
100438       int regReset;       /* Return address register for reset subroutine */
100439
100440       /* If there is a GROUP BY clause we might need a sorting index to
100441       ** implement it.  Allocate that sorting index now.  If it turns out
100442       ** that we do not need it after all, the OP_SorterOpen instruction
100443       ** will be converted into a Noop.  
100444       */
100445       sAggInfo.sortingIdx = pParse->nTab++;
100446       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
100447       addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen, 
100448           sAggInfo.sortingIdx, sAggInfo.nSortingColumn, 
100449           0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
100450
100451       /* Initialize memory locations used by GROUP BY aggregate processing
100452       */
100453       iUseFlag = ++pParse->nMem;
100454       iAbortFlag = ++pParse->nMem;
100455       regOutputRow = ++pParse->nMem;
100456       addrOutputRow = sqlite3VdbeMakeLabel(v);
100457       regReset = ++pParse->nMem;
100458       addrReset = sqlite3VdbeMakeLabel(v);
100459       iAMem = pParse->nMem + 1;
100460       pParse->nMem += pGroupBy->nExpr;
100461       iBMem = pParse->nMem + 1;
100462       pParse->nMem += pGroupBy->nExpr;
100463       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
100464       VdbeComment((v, "clear abort flag"));
100465       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
100466       VdbeComment((v, "indicate accumulator empty"));
100467       sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
100468
100469       /* Begin a loop that will extract all source rows in GROUP BY order.
100470       ** This might involve two separate loops with an OP_Sort in between, or
100471       ** it might be a single loop that uses an index to extract information
100472       ** in the right order to begin with.
100473       */
100474       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
100475       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0, 0, 0);
100476       if( pWInfo==0 ) goto select_end;
100477       if( pWInfo->nOBSat==pGroupBy->nExpr ){
100478         /* The optimizer is able to deliver rows in group by order so
100479         ** we do not have to sort.  The OP_OpenEphemeral table will be
100480         ** cancelled later because we still need to use the pKeyInfo
100481         */
100482         groupBySort = 0;
100483       }else{
100484         /* Rows are coming out in undetermined order.  We have to push
100485         ** each row into a sorting index, terminate the first loop,
100486         ** then loop over the sorting index in order to get the output
100487         ** in sorted order
100488         */
100489         int regBase;
100490         int regRecord;
100491         int nCol;
100492         int nGroupBy;
100493
100494         explainTempTable(pParse, 
100495             (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
100496                     "DISTINCT" : "GROUP BY");
100497
100498         groupBySort = 1;
100499         nGroupBy = pGroupBy->nExpr;
100500         nCol = nGroupBy + 1;
100501         j = nGroupBy+1;
100502         for(i=0; i<sAggInfo.nColumn; i++){
100503           if( sAggInfo.aCol[i].iSorterColumn>=j ){
100504             nCol++;
100505             j++;
100506           }
100507         }
100508         regBase = sqlite3GetTempRange(pParse, nCol);
100509         sqlite3ExprCacheClear(pParse);
100510         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
100511         sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
100512         j = nGroupBy+1;
100513         for(i=0; i<sAggInfo.nColumn; i++){
100514           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
100515           if( pCol->iSorterColumn>=j ){
100516             int r1 = j + regBase;
100517             int r2;
100518
100519             r2 = sqlite3ExprCodeGetColumn(pParse, 
100520                                pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
100521             if( r1!=r2 ){
100522               sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
100523             }
100524             j++;
100525           }
100526         }
100527         regRecord = sqlite3GetTempReg(pParse);
100528         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
100529         sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
100530         sqlite3ReleaseTempReg(pParse, regRecord);
100531         sqlite3ReleaseTempRange(pParse, regBase, nCol);
100532         sqlite3WhereEnd(pWInfo);
100533         sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
100534         sortOut = sqlite3GetTempReg(pParse);
100535         sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
100536         sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
100537         VdbeComment((v, "GROUP BY sort"));
100538         sAggInfo.useSortingIdx = 1;
100539         sqlite3ExprCacheClear(pParse);
100540       }
100541
100542       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
100543       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
100544       ** Then compare the current GROUP BY terms against the GROUP BY terms
100545       ** from the previous row currently stored in a0, a1, a2...
100546       */
100547       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
100548       sqlite3ExprCacheClear(pParse);
100549       if( groupBySort ){
100550         sqlite3VdbeAddOp2(v, OP_SorterData, sAggInfo.sortingIdx, sortOut);
100551       }
100552       for(j=0; j<pGroupBy->nExpr; j++){
100553         if( groupBySort ){
100554           sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
100555           if( j==0 ) sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
100556         }else{
100557           sAggInfo.directMode = 1;
100558           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
100559         }
100560       }
100561       sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
100562                           (char*)pKeyInfo, P4_KEYINFO);
100563       j1 = sqlite3VdbeCurrentAddr(v);
100564       sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
100565
100566       /* Generate code that runs whenever the GROUP BY changes.
100567       ** Changes in the GROUP BY are detected by the previous code
100568       ** block.  If there were no changes, this block is skipped.
100569       **
100570       ** This code copies current group by terms in b0,b1,b2,...
100571       ** over to a0,a1,a2.  It then calls the output subroutine
100572       ** and resets the aggregate accumulator registers in preparation
100573       ** for the next GROUP BY batch.
100574       */
100575       sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
100576       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
100577       VdbeComment((v, "output one row"));
100578       sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
100579       VdbeComment((v, "check abort flag"));
100580       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
100581       VdbeComment((v, "reset accumulator"));
100582
100583       /* Update the aggregate accumulators based on the content of
100584       ** the current row
100585       */
100586       sqlite3VdbeJumpHere(v, j1);
100587       updateAccumulator(pParse, &sAggInfo);
100588       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
100589       VdbeComment((v, "indicate data in accumulator"));
100590
100591       /* End of the loop
100592       */
100593       if( groupBySort ){
100594         sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
100595       }else{
100596         sqlite3WhereEnd(pWInfo);
100597         sqlite3VdbeChangeToNoop(v, addrSortingIdx);
100598       }
100599
100600       /* Output the final row of result
100601       */
100602       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
100603       VdbeComment((v, "output final row"));
100604
100605       /* Jump over the subroutines
100606       */
100607       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
100608
100609       /* Generate a subroutine that outputs a single row of the result
100610       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
100611       ** is less than or equal to zero, the subroutine is a no-op.  If
100612       ** the processing calls for the query to abort, this subroutine
100613       ** increments the iAbortFlag memory location before returning in
100614       ** order to signal the caller to abort.
100615       */
100616       addrSetAbort = sqlite3VdbeCurrentAddr(v);
100617       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
100618       VdbeComment((v, "set abort flag"));
100619       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
100620       sqlite3VdbeResolveLabel(v, addrOutputRow);
100621       addrOutputRow = sqlite3VdbeCurrentAddr(v);
100622       sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
100623       VdbeComment((v, "Groupby result generator entry point"));
100624       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
100625       finalizeAggFunctions(pParse, &sAggInfo);
100626       sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
100627       selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
100628                       &sDistinct, pDest,
100629                       addrOutputRow+1, addrSetAbort);
100630       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
100631       VdbeComment((v, "end groupby result generator"));
100632
100633       /* Generate a subroutine that will reset the group-by accumulator
100634       */
100635       sqlite3VdbeResolveLabel(v, addrReset);
100636       resetAccumulator(pParse, &sAggInfo);
100637       sqlite3VdbeAddOp1(v, OP_Return, regReset);
100638      
100639     } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
100640     else {
100641       ExprList *pDel = 0;
100642 #ifndef SQLITE_OMIT_BTREECOUNT
100643       Table *pTab;
100644       if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
100645         /* If isSimpleCount() returns a pointer to a Table structure, then
100646         ** the SQL statement is of the form:
100647         **
100648         **   SELECT count(*) FROM <tbl>
100649         **
100650         ** where the Table structure returned represents table <tbl>.
100651         **
100652         ** This statement is so common that it is optimized specially. The
100653         ** OP_Count instruction is executed either on the intkey table that
100654         ** contains the data for table <tbl> or on one of its indexes. It
100655         ** is better to execute the op on an index, as indexes are almost
100656         ** always spread across less pages than their corresponding tables.
100657         */
100658         const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
100659         const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
100660         Index *pIdx;                         /* Iterator variable */
100661         KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
100662         Index *pBest = 0;                    /* Best index found so far */
100663         int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
100664
100665         sqlite3CodeVerifySchema(pParse, iDb);
100666         sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
100667
100668         /* Search for the index that has the least amount of columns. If
100669         ** there is such an index, and it has less columns than the table
100670         ** does, then we can assume that it consumes less space on disk and
100671         ** will therefore be cheaper to scan to determine the query result.
100672         ** In this case set iRoot to the root page number of the index b-tree
100673         ** and pKeyInfo to the KeyInfo structure required to navigate the
100674         ** index.
100675         **
100676         ** (2011-04-15) Do not do a full scan of an unordered index.
100677         **
100678         ** In practice the KeyInfo structure will not be used. It is only 
100679         ** passed to keep OP_OpenRead happy.
100680         */
100681         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
100682           if( pIdx->bUnordered==0 && (!pBest || pIdx->nColumn<pBest->nColumn) ){
100683             pBest = pIdx;
100684           }
100685         }
100686         if( pBest && pBest->nColumn<pTab->nCol ){
100687           iRoot = pBest->tnum;
100688           pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest);
100689         }
100690
100691         /* Open a read-only cursor, execute the OP_Count, close the cursor. */
100692         sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
100693         if( pKeyInfo ){
100694           sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);
100695         }
100696         sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
100697         sqlite3VdbeAddOp1(v, OP_Close, iCsr);
100698         explainSimpleCount(pParse, pTab, pBest);
100699       }else
100700 #endif /* SQLITE_OMIT_BTREECOUNT */
100701       {
100702         /* Check if the query is of one of the following forms:
100703         **
100704         **   SELECT min(x) FROM ...
100705         **   SELECT max(x) FROM ...
100706         **
100707         ** If it is, then ask the code in where.c to attempt to sort results
100708         ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause. 
100709         ** If where.c is able to produce results sorted in this order, then
100710         ** add vdbe code to break out of the processing loop after the 
100711         ** first iteration (since the first iteration of the loop is 
100712         ** guaranteed to operate on the row with the minimum or maximum 
100713         ** value of x, the only row required).
100714         **
100715         ** A special flag must be passed to sqlite3WhereBegin() to slightly
100716         ** modify behavior as follows:
100717         **
100718         **   + If the query is a "SELECT min(x)", then the loop coded by
100719         **     where.c should not iterate over any values with a NULL value
100720         **     for x.
100721         **
100722         **   + The optimizer code in where.c (the thing that decides which
100723         **     index or indices to use) should place a different priority on 
100724         **     satisfying the 'ORDER BY' clause than it does in other cases.
100725         **     Refer to code and comments in where.c for details.
100726         */
100727         ExprList *pMinMax = 0;
100728         u8 flag = WHERE_ORDERBY_NORMAL;
100729         
100730         assert( p->pGroupBy==0 );
100731         assert( flag==0 );
100732         if( p->pHaving==0 ){
100733           flag = minMaxQuery(&sAggInfo, &pMinMax);
100734         }
100735         assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) );
100736
100737         if( flag ){
100738           pMinMax = sqlite3ExprListDup(db, pMinMax, 0);
100739           pDel = pMinMax;
100740           if( pMinMax && !db->mallocFailed ){
100741             pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
100742             pMinMax->a[0].pExpr->op = TK_COLUMN;
100743           }
100744         }
100745   
100746         /* This case runs if the aggregate has no GROUP BY clause.  The
100747         ** processing is much simpler since there is only a single row
100748         ** of output.
100749         */
100750         resetAccumulator(pParse, &sAggInfo);
100751         pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0);
100752         if( pWInfo==0 ){
100753           sqlite3ExprListDelete(db, pDel);
100754           goto select_end;
100755         }
100756         updateAccumulator(pParse, &sAggInfo);
100757         assert( pMinMax==0 || pMinMax->nExpr==1 );
100758         if( pWInfo->nOBSat>0 ){
100759           sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
100760           VdbeComment((v, "%s() by index",
100761                 (flag==WHERE_ORDERBY_MIN?"min":"max")));
100762         }
100763         sqlite3WhereEnd(pWInfo);
100764         finalizeAggFunctions(pParse, &sAggInfo);
100765       }
100766
100767       pOrderBy = 0;
100768       sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
100769       selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, 0, 
100770                       pDest, addrEnd, addrEnd);
100771       sqlite3ExprListDelete(db, pDel);
100772     }
100773     sqlite3VdbeResolveLabel(v, addrEnd);
100774     
100775   } /* endif aggregate query */
100776
100777   if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
100778     explainTempTable(pParse, "DISTINCT");
100779   }
100780
100781   /* If there is an ORDER BY clause, then we need to sort the results
100782   ** and send them to the callback one by one.
100783   */
100784   if( pOrderBy ){
100785     explainTempTable(pParse, "ORDER BY");
100786     generateSortTail(pParse, p, v, pEList->nExpr, pDest);
100787   }
100788
100789   /* Jump here to skip this query
100790   */
100791   sqlite3VdbeResolveLabel(v, iEnd);
100792
100793   /* The SELECT was successfully coded.   Set the return code to 0
100794   ** to indicate no errors.
100795   */
100796   rc = 0;
100797
100798   /* Control jumps to here if an error is encountered above, or upon
100799   ** successful coding of the SELECT.
100800   */
100801 select_end:
100802   explainSetInteger(pParse->iSelectId, iRestoreSelectId);
100803
100804   /* Identify column names if results of the SELECT are to be output.
100805   */
100806   if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
100807     generateColumnNames(pParse, pTabList, pEList);
100808   }
100809
100810   sqlite3DbFree(db, sAggInfo.aCol);
100811   sqlite3DbFree(db, sAggInfo.aFunc);
100812   return rc;
100813 }
100814
100815 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
100816 /*
100817 ** Generate a human-readable description of a the Select object.
100818 */
100819 static void explainOneSelect(Vdbe *pVdbe, Select *p){
100820   sqlite3ExplainPrintf(pVdbe, "SELECT ");
100821   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
100822     if( p->selFlags & SF_Distinct ){
100823       sqlite3ExplainPrintf(pVdbe, "DISTINCT ");
100824     }
100825     if( p->selFlags & SF_Aggregate ){
100826       sqlite3ExplainPrintf(pVdbe, "agg_flag ");
100827     }
100828     sqlite3ExplainNL(pVdbe);
100829     sqlite3ExplainPrintf(pVdbe, "   ");
100830   }
100831   sqlite3ExplainExprList(pVdbe, p->pEList);
100832   sqlite3ExplainNL(pVdbe);
100833   if( p->pSrc && p->pSrc->nSrc ){
100834     int i;
100835     sqlite3ExplainPrintf(pVdbe, "FROM ");
100836     sqlite3ExplainPush(pVdbe);
100837     for(i=0; i<p->pSrc->nSrc; i++){
100838       struct SrcList_item *pItem = &p->pSrc->a[i];
100839       sqlite3ExplainPrintf(pVdbe, "{%d,*} = ", pItem->iCursor);
100840       if( pItem->pSelect ){
100841         sqlite3ExplainSelect(pVdbe, pItem->pSelect);
100842         if( pItem->pTab ){
100843           sqlite3ExplainPrintf(pVdbe, " (tabname=%s)", pItem->pTab->zName);
100844         }
100845       }else if( pItem->zName ){
100846         sqlite3ExplainPrintf(pVdbe, "%s", pItem->zName);
100847       }
100848       if( pItem->zAlias ){
100849         sqlite3ExplainPrintf(pVdbe, " (AS %s)", pItem->zAlias);
100850       }
100851       if( pItem->jointype & JT_LEFT ){
100852         sqlite3ExplainPrintf(pVdbe, " LEFT-JOIN");
100853       }
100854       sqlite3ExplainNL(pVdbe);
100855     }
100856     sqlite3ExplainPop(pVdbe);
100857   }
100858   if( p->pWhere ){
100859     sqlite3ExplainPrintf(pVdbe, "WHERE ");
100860     sqlite3ExplainExpr(pVdbe, p->pWhere);
100861     sqlite3ExplainNL(pVdbe);
100862   }
100863   if( p->pGroupBy ){
100864     sqlite3ExplainPrintf(pVdbe, "GROUPBY ");
100865     sqlite3ExplainExprList(pVdbe, p->pGroupBy);
100866     sqlite3ExplainNL(pVdbe);
100867   }
100868   if( p->pHaving ){
100869     sqlite3ExplainPrintf(pVdbe, "HAVING ");
100870     sqlite3ExplainExpr(pVdbe, p->pHaving);
100871     sqlite3ExplainNL(pVdbe);
100872   }
100873   if( p->pOrderBy ){
100874     sqlite3ExplainPrintf(pVdbe, "ORDERBY ");
100875     sqlite3ExplainExprList(pVdbe, p->pOrderBy);
100876     sqlite3ExplainNL(pVdbe);
100877   }
100878   if( p->pLimit ){
100879     sqlite3ExplainPrintf(pVdbe, "LIMIT ");
100880     sqlite3ExplainExpr(pVdbe, p->pLimit);
100881     sqlite3ExplainNL(pVdbe);
100882   }
100883   if( p->pOffset ){
100884     sqlite3ExplainPrintf(pVdbe, "OFFSET ");
100885     sqlite3ExplainExpr(pVdbe, p->pOffset);
100886     sqlite3ExplainNL(pVdbe);
100887   }
100888 }
100889 SQLITE_PRIVATE void sqlite3ExplainSelect(Vdbe *pVdbe, Select *p){
100890   if( p==0 ){
100891     sqlite3ExplainPrintf(pVdbe, "(null-select)");
100892     return;
100893   }
100894   while( p->pPrior ){
100895     p->pPrior->pNext = p;
100896     p = p->pPrior;
100897   }
100898   sqlite3ExplainPush(pVdbe);
100899   while( p ){
100900     explainOneSelect(pVdbe, p);
100901     p = p->pNext;
100902     if( p==0 ) break;
100903     sqlite3ExplainNL(pVdbe);
100904     sqlite3ExplainPrintf(pVdbe, "%s\n", selectOpName(p->op));
100905   }
100906   sqlite3ExplainPrintf(pVdbe, "END");
100907   sqlite3ExplainPop(pVdbe);
100908 }
100909
100910 /* End of the structure debug printing code
100911 *****************************************************************************/
100912 #endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
100913
100914 /************** End of select.c **********************************************/
100915 /************** Begin file table.c *******************************************/
100916 /*
100917 ** 2001 September 15
100918 **
100919 ** The author disclaims copyright to this source code.  In place of
100920 ** a legal notice, here is a blessing:
100921 **
100922 **    May you do good and not evil.
100923 **    May you find forgiveness for yourself and forgive others.
100924 **    May you share freely, never taking more than you give.
100925 **
100926 *************************************************************************
100927 ** This file contains the sqlite3_get_table() and sqlite3_free_table()
100928 ** interface routines.  These are just wrappers around the main
100929 ** interface routine of sqlite3_exec().
100930 **
100931 ** These routines are in a separate files so that they will not be linked
100932 ** if they are not used.
100933 */
100934 /* #include <stdlib.h> */
100935 /* #include <string.h> */
100936
100937 #ifndef SQLITE_OMIT_GET_TABLE
100938
100939 /*
100940 ** This structure is used to pass data from sqlite3_get_table() through
100941 ** to the callback function is uses to build the result.
100942 */
100943 typedef struct TabResult {
100944   char **azResult;   /* Accumulated output */
100945   char *zErrMsg;     /* Error message text, if an error occurs */
100946   int nAlloc;        /* Slots allocated for azResult[] */
100947   int nRow;          /* Number of rows in the result */
100948   int nColumn;       /* Number of columns in the result */
100949   int nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
100950   int rc;            /* Return code from sqlite3_exec() */
100951 } TabResult;
100952
100953 /*
100954 ** This routine is called once for each row in the result table.  Its job
100955 ** is to fill in the TabResult structure appropriately, allocating new
100956 ** memory as necessary.
100957 */
100958 static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
100959   TabResult *p = (TabResult*)pArg;  /* Result accumulator */
100960   int need;                         /* Slots needed in p->azResult[] */
100961   int i;                            /* Loop counter */
100962   char *z;                          /* A single column of result */
100963
100964   /* Make sure there is enough space in p->azResult to hold everything
100965   ** we need to remember from this invocation of the callback.
100966   */
100967   if( p->nRow==0 && argv!=0 ){
100968     need = nCol*2;
100969   }else{
100970     need = nCol;
100971   }
100972   if( p->nData + need > p->nAlloc ){
100973     char **azNew;
100974     p->nAlloc = p->nAlloc*2 + need;
100975     azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
100976     if( azNew==0 ) goto malloc_failed;
100977     p->azResult = azNew;
100978   }
100979
100980   /* If this is the first row, then generate an extra row containing
100981   ** the names of all columns.
100982   */
100983   if( p->nRow==0 ){
100984     p->nColumn = nCol;
100985     for(i=0; i<nCol; i++){
100986       z = sqlite3_mprintf("%s", colv[i]);
100987       if( z==0 ) goto malloc_failed;
100988       p->azResult[p->nData++] = z;
100989     }
100990   }else if( p->nColumn!=nCol ){
100991     sqlite3_free(p->zErrMsg);
100992     p->zErrMsg = sqlite3_mprintf(
100993        "sqlite3_get_table() called with two or more incompatible queries"
100994     );
100995     p->rc = SQLITE_ERROR;
100996     return 1;
100997   }
100998
100999   /* Copy over the row data
101000   */
101001   if( argv!=0 ){
101002     for(i=0; i<nCol; i++){
101003       if( argv[i]==0 ){
101004         z = 0;
101005       }else{
101006         int n = sqlite3Strlen30(argv[i])+1;
101007         z = sqlite3_malloc( n );
101008         if( z==0 ) goto malloc_failed;
101009         memcpy(z, argv[i], n);
101010       }
101011       p->azResult[p->nData++] = z;
101012     }
101013     p->nRow++;
101014   }
101015   return 0;
101016
101017 malloc_failed:
101018   p->rc = SQLITE_NOMEM;
101019   return 1;
101020 }
101021
101022 /*
101023 ** Query the database.  But instead of invoking a callback for each row,
101024 ** malloc() for space to hold the result and return the entire results
101025 ** at the conclusion of the call.
101026 **
101027 ** The result that is written to ***pazResult is held in memory obtained
101028 ** from malloc().  But the caller cannot free this memory directly.  
101029 ** Instead, the entire table should be passed to sqlite3_free_table() when
101030 ** the calling procedure is finished using it.
101031 */
101032 SQLITE_API int sqlite3_get_table(
101033   sqlite3 *db,                /* The database on which the SQL executes */
101034   const char *zSql,           /* The SQL to be executed */
101035   char ***pazResult,          /* Write the result table here */
101036   int *pnRow,                 /* Write the number of rows in the result here */
101037   int *pnColumn,              /* Write the number of columns of result here */
101038   char **pzErrMsg             /* Write error messages here */
101039 ){
101040   int rc;
101041   TabResult res;
101042
101043   *pazResult = 0;
101044   if( pnColumn ) *pnColumn = 0;
101045   if( pnRow ) *pnRow = 0;
101046   if( pzErrMsg ) *pzErrMsg = 0;
101047   res.zErrMsg = 0;
101048   res.nRow = 0;
101049   res.nColumn = 0;
101050   res.nData = 1;
101051   res.nAlloc = 20;
101052   res.rc = SQLITE_OK;
101053   res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
101054   if( res.azResult==0 ){
101055      db->errCode = SQLITE_NOMEM;
101056      return SQLITE_NOMEM;
101057   }
101058   res.azResult[0] = 0;
101059   rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
101060   assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
101061   res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
101062   if( (rc&0xff)==SQLITE_ABORT ){
101063     sqlite3_free_table(&res.azResult[1]);
101064     if( res.zErrMsg ){
101065       if( pzErrMsg ){
101066         sqlite3_free(*pzErrMsg);
101067         *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
101068       }
101069       sqlite3_free(res.zErrMsg);
101070     }
101071     db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
101072     return res.rc;
101073   }
101074   sqlite3_free(res.zErrMsg);
101075   if( rc!=SQLITE_OK ){
101076     sqlite3_free_table(&res.azResult[1]);
101077     return rc;
101078   }
101079   if( res.nAlloc>res.nData ){
101080     char **azNew;
101081     azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
101082     if( azNew==0 ){
101083       sqlite3_free_table(&res.azResult[1]);
101084       db->errCode = SQLITE_NOMEM;
101085       return SQLITE_NOMEM;
101086     }
101087     res.azResult = azNew;
101088   }
101089   *pazResult = &res.azResult[1];
101090   if( pnColumn ) *pnColumn = res.nColumn;
101091   if( pnRow ) *pnRow = res.nRow;
101092   return rc;
101093 }
101094
101095 /*
101096 ** This routine frees the space the sqlite3_get_table() malloced.
101097 */
101098 SQLITE_API void sqlite3_free_table(
101099   char **azResult            /* Result returned from from sqlite3_get_table() */
101100 ){
101101   if( azResult ){
101102     int i, n;
101103     azResult--;
101104     assert( azResult!=0 );
101105     n = SQLITE_PTR_TO_INT(azResult[0]);
101106     for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
101107     sqlite3_free(azResult);
101108   }
101109 }
101110
101111 #endif /* SQLITE_OMIT_GET_TABLE */
101112
101113 /************** End of table.c ***********************************************/
101114 /************** Begin file trigger.c *****************************************/
101115 /*
101116 **
101117 ** The author disclaims copyright to this source code.  In place of
101118 ** a legal notice, here is a blessing:
101119 **
101120 **    May you do good and not evil.
101121 **    May you find forgiveness for yourself and forgive others.
101122 **    May you share freely, never taking more than you give.
101123 **
101124 *************************************************************************
101125 ** This file contains the implementation for TRIGGERs
101126 */
101127
101128 #ifndef SQLITE_OMIT_TRIGGER
101129 /*
101130 ** Delete a linked list of TriggerStep structures.
101131 */
101132 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
101133   while( pTriggerStep ){
101134     TriggerStep * pTmp = pTriggerStep;
101135     pTriggerStep = pTriggerStep->pNext;
101136
101137     sqlite3ExprDelete(db, pTmp->pWhere);
101138     sqlite3ExprListDelete(db, pTmp->pExprList);
101139     sqlite3SelectDelete(db, pTmp->pSelect);
101140     sqlite3IdListDelete(db, pTmp->pIdList);
101141
101142     sqlite3DbFree(db, pTmp);
101143   }
101144 }
101145
101146 /*
101147 ** Given table pTab, return a list of all the triggers attached to 
101148 ** the table. The list is connected by Trigger.pNext pointers.
101149 **
101150 ** All of the triggers on pTab that are in the same database as pTab
101151 ** are already attached to pTab->pTrigger.  But there might be additional
101152 ** triggers on pTab in the TEMP schema.  This routine prepends all
101153 ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
101154 ** and returns the combined list.
101155 **
101156 ** To state it another way:  This routine returns a list of all triggers
101157 ** that fire off of pTab.  The list will include any TEMP triggers on
101158 ** pTab as well as the triggers lised in pTab->pTrigger.
101159 */
101160 SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
101161   Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
101162   Trigger *pList = 0;                  /* List of triggers to return */
101163
101164   if( pParse->disableTriggers ){
101165     return 0;
101166   }
101167
101168   if( pTmpSchema!=pTab->pSchema ){
101169     HashElem *p;
101170     assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
101171     for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
101172       Trigger *pTrig = (Trigger *)sqliteHashData(p);
101173       if( pTrig->pTabSchema==pTab->pSchema
101174        && 0==sqlite3StrICmp(pTrig->table, pTab->zName) 
101175       ){
101176         pTrig->pNext = (pList ? pList : pTab->pTrigger);
101177         pList = pTrig;
101178       }
101179     }
101180   }
101181
101182   return (pList ? pList : pTab->pTrigger);
101183 }
101184
101185 /*
101186 ** This is called by the parser when it sees a CREATE TRIGGER statement
101187 ** up to the point of the BEGIN before the trigger actions.  A Trigger
101188 ** structure is generated based on the information available and stored
101189 ** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
101190 ** sqlite3FinishTrigger() function is called to complete the trigger
101191 ** construction process.
101192 */
101193 SQLITE_PRIVATE void sqlite3BeginTrigger(
101194   Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
101195   Token *pName1,      /* The name of the trigger */
101196   Token *pName2,      /* The name of the trigger */
101197   int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
101198   int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
101199   IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
101200   SrcList *pTableName,/* The name of the table/view the trigger applies to */
101201   Expr *pWhen,        /* WHEN clause */
101202   int isTemp,         /* True if the TEMPORARY keyword is present */
101203   int noErr           /* Suppress errors if the trigger already exists */
101204 ){
101205   Trigger *pTrigger = 0;  /* The new trigger */
101206   Table *pTab;            /* Table that the trigger fires off of */
101207   char *zName = 0;        /* Name of the trigger */
101208   sqlite3 *db = pParse->db;  /* The database connection */
101209   int iDb;                /* The database to store the trigger in */
101210   Token *pName;           /* The unqualified db name */
101211   DbFixer sFix;           /* State vector for the DB fixer */
101212   int iTabDb;             /* Index of the database holding pTab */
101213
101214   assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
101215   assert( pName2!=0 );
101216   assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
101217   assert( op>0 && op<0xff );
101218   if( isTemp ){
101219     /* If TEMP was specified, then the trigger name may not be qualified. */
101220     if( pName2->n>0 ){
101221       sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
101222       goto trigger_cleanup;
101223     }
101224     iDb = 1;
101225     pName = pName1;
101226   }else{
101227     /* Figure out the db that the trigger will be created in */
101228     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
101229     if( iDb<0 ){
101230       goto trigger_cleanup;
101231     }
101232   }
101233   if( !pTableName || db->mallocFailed ){
101234     goto trigger_cleanup;
101235   }
101236
101237   /* A long-standing parser bug is that this syntax was allowed:
101238   **
101239   **    CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
101240   **                                                 ^^^^^^^^
101241   **
101242   ** To maintain backwards compatibility, ignore the database
101243   ** name on pTableName if we are reparsing our of SQLITE_MASTER.
101244   */
101245   if( db->init.busy && iDb!=1 ){
101246     sqlite3DbFree(db, pTableName->a[0].zDatabase);
101247     pTableName->a[0].zDatabase = 0;
101248   }
101249
101250   /* If the trigger name was unqualified, and the table is a temp table,
101251   ** then set iDb to 1 to create the trigger in the temporary database.
101252   ** If sqlite3SrcListLookup() returns 0, indicating the table does not
101253   ** exist, the error is caught by the block below.
101254   */
101255   pTab = sqlite3SrcListLookup(pParse, pTableName);
101256   if( db->init.busy==0 && pName2->n==0 && pTab
101257         && pTab->pSchema==db->aDb[1].pSchema ){
101258     iDb = 1;
101259   }
101260
101261   /* Ensure the table name matches database name and that the table exists */
101262   if( db->mallocFailed ) goto trigger_cleanup;
101263   assert( pTableName->nSrc==1 );
101264   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) && 
101265       sqlite3FixSrcList(&sFix, pTableName) ){
101266     goto trigger_cleanup;
101267   }
101268   pTab = sqlite3SrcListLookup(pParse, pTableName);
101269   if( !pTab ){
101270     /* The table does not exist. */
101271     if( db->init.iDb==1 ){
101272       /* Ticket #3810.
101273       ** Normally, whenever a table is dropped, all associated triggers are
101274       ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
101275       ** and the table is dropped by a different database connection, the
101276       ** trigger is not visible to the database connection that does the
101277       ** drop so the trigger cannot be dropped.  This results in an
101278       ** "orphaned trigger" - a trigger whose associated table is missing.
101279       */
101280       db->init.orphanTrigger = 1;
101281     }
101282     goto trigger_cleanup;
101283   }
101284   if( IsVirtual(pTab) ){
101285     sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
101286     goto trigger_cleanup;
101287   }
101288
101289   /* Check that the trigger name is not reserved and that no trigger of the
101290   ** specified name exists */
101291   zName = sqlite3NameFromToken(db, pName);
101292   if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
101293     goto trigger_cleanup;
101294   }
101295   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
101296   if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
101297                       zName, sqlite3Strlen30(zName)) ){
101298     if( !noErr ){
101299       sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
101300     }else{
101301       assert( !db->init.busy );
101302       sqlite3CodeVerifySchema(pParse, iDb);
101303     }
101304     goto trigger_cleanup;
101305   }
101306
101307   /* Do not create a trigger on a system table */
101308   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
101309     sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
101310     pParse->nErr++;
101311     goto trigger_cleanup;
101312   }
101313
101314   /* INSTEAD of triggers are only for views and views only support INSTEAD
101315   ** of triggers.
101316   */
101317   if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
101318     sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S", 
101319         (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
101320     goto trigger_cleanup;
101321   }
101322   if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
101323     sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
101324         " trigger on table: %S", pTableName, 0);
101325     goto trigger_cleanup;
101326   }
101327   iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
101328
101329 #ifndef SQLITE_OMIT_AUTHORIZATION
101330   {
101331     int code = SQLITE_CREATE_TRIGGER;
101332     const char *zDb = db->aDb[iTabDb].zName;
101333     const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
101334     if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
101335     if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
101336       goto trigger_cleanup;
101337     }
101338     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
101339       goto trigger_cleanup;
101340     }
101341   }
101342 #endif
101343
101344   /* INSTEAD OF triggers can only appear on views and BEFORE triggers
101345   ** cannot appear on views.  So we might as well translate every
101346   ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
101347   ** elsewhere.
101348   */
101349   if (tr_tm == TK_INSTEAD){
101350     tr_tm = TK_BEFORE;
101351   }
101352
101353   /* Build the Trigger object */
101354   pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
101355   if( pTrigger==0 ) goto trigger_cleanup;
101356   pTrigger->zName = zName;
101357   zName = 0;
101358   pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
101359   pTrigger->pSchema = db->aDb[iDb].pSchema;
101360   pTrigger->pTabSchema = pTab->pSchema;
101361   pTrigger->op = (u8)op;
101362   pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
101363   pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
101364   pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
101365   assert( pParse->pNewTrigger==0 );
101366   pParse->pNewTrigger = pTrigger;
101367
101368 trigger_cleanup:
101369   sqlite3DbFree(db, zName);
101370   sqlite3SrcListDelete(db, pTableName);
101371   sqlite3IdListDelete(db, pColumns);
101372   sqlite3ExprDelete(db, pWhen);
101373   if( !pParse->pNewTrigger ){
101374     sqlite3DeleteTrigger(db, pTrigger);
101375   }else{
101376     assert( pParse->pNewTrigger==pTrigger );
101377   }
101378 }
101379
101380 /*
101381 ** This routine is called after all of the trigger actions have been parsed
101382 ** in order to complete the process of building the trigger.
101383 */
101384 SQLITE_PRIVATE void sqlite3FinishTrigger(
101385   Parse *pParse,          /* Parser context */
101386   TriggerStep *pStepList, /* The triggered program */
101387   Token *pAll             /* Token that describes the complete CREATE TRIGGER */
101388 ){
101389   Trigger *pTrig = pParse->pNewTrigger;   /* Trigger being finished */
101390   char *zName;                            /* Name of trigger */
101391   sqlite3 *db = pParse->db;               /* The database */
101392   DbFixer sFix;                           /* Fixer object */
101393   int iDb;                                /* Database containing the trigger */
101394   Token nameToken;                        /* Trigger name for error reporting */
101395
101396   pParse->pNewTrigger = 0;
101397   if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
101398   zName = pTrig->zName;
101399   iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
101400   pTrig->step_list = pStepList;
101401   while( pStepList ){
101402     pStepList->pTrig = pTrig;
101403     pStepList = pStepList->pNext;
101404   }
101405   nameToken.z = pTrig->zName;
101406   nameToken.n = sqlite3Strlen30(nameToken.z);
101407   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken) 
101408           && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
101409     goto triggerfinish_cleanup;
101410   }
101411
101412   /* if we are not initializing,
101413   ** build the sqlite_master entry
101414   */
101415   if( !db->init.busy ){
101416     Vdbe *v;
101417     char *z;
101418
101419     /* Make an entry in the sqlite_master table */
101420     v = sqlite3GetVdbe(pParse);
101421     if( v==0 ) goto triggerfinish_cleanup;
101422     sqlite3BeginWriteOperation(pParse, 0, iDb);
101423     z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
101424     sqlite3NestedParse(pParse,
101425        "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
101426        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
101427        pTrig->table, z);
101428     sqlite3DbFree(db, z);
101429     sqlite3ChangeCookie(pParse, iDb);
101430     sqlite3VdbeAddParseSchemaOp(v, iDb,
101431         sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
101432   }
101433
101434   if( db->init.busy ){
101435     Trigger *pLink = pTrig;
101436     Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
101437     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
101438     pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
101439     if( pTrig ){
101440       db->mallocFailed = 1;
101441     }else if( pLink->pSchema==pLink->pTabSchema ){
101442       Table *pTab;
101443       int n = sqlite3Strlen30(pLink->table);
101444       pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
101445       assert( pTab!=0 );
101446       pLink->pNext = pTab->pTrigger;
101447       pTab->pTrigger = pLink;
101448     }
101449   }
101450
101451 triggerfinish_cleanup:
101452   sqlite3DeleteTrigger(db, pTrig);
101453   assert( !pParse->pNewTrigger );
101454   sqlite3DeleteTriggerStep(db, pStepList);
101455 }
101456
101457 /*
101458 ** Turn a SELECT statement (that the pSelect parameter points to) into
101459 ** a trigger step.  Return a pointer to a TriggerStep structure.
101460 **
101461 ** The parser calls this routine when it finds a SELECT statement in
101462 ** body of a TRIGGER.  
101463 */
101464 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
101465   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
101466   if( pTriggerStep==0 ) {
101467     sqlite3SelectDelete(db, pSelect);
101468     return 0;
101469   }
101470   pTriggerStep->op = TK_SELECT;
101471   pTriggerStep->pSelect = pSelect;
101472   pTriggerStep->orconf = OE_Default;
101473   return pTriggerStep;
101474 }
101475
101476 /*
101477 ** Allocate space to hold a new trigger step.  The allocated space
101478 ** holds both the TriggerStep object and the TriggerStep.target.z string.
101479 **
101480 ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
101481 */
101482 static TriggerStep *triggerStepAllocate(
101483   sqlite3 *db,                /* Database connection */
101484   u8 op,                      /* Trigger opcode */
101485   Token *pName                /* The target name */
101486 ){
101487   TriggerStep *pTriggerStep;
101488
101489   pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
101490   if( pTriggerStep ){
101491     char *z = (char*)&pTriggerStep[1];
101492     memcpy(z, pName->z, pName->n);
101493     pTriggerStep->target.z = z;
101494     pTriggerStep->target.n = pName->n;
101495     pTriggerStep->op = op;
101496   }
101497   return pTriggerStep;
101498 }
101499
101500 /*
101501 ** Build a trigger step out of an INSERT statement.  Return a pointer
101502 ** to the new trigger step.
101503 **
101504 ** The parser calls this routine when it sees an INSERT inside the
101505 ** body of a trigger.
101506 */
101507 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
101508   sqlite3 *db,        /* The database connection */
101509   Token *pTableName,  /* Name of the table into which we insert */
101510   IdList *pColumn,    /* List of columns in pTableName to insert into */
101511   ExprList *pEList,   /* The VALUE clause: a list of values to be inserted */
101512   Select *pSelect,    /* A SELECT statement that supplies values */
101513   u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
101514 ){
101515   TriggerStep *pTriggerStep;
101516
101517   assert(pEList == 0 || pSelect == 0);
101518   assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
101519
101520   pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
101521   if( pTriggerStep ){
101522     pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
101523     pTriggerStep->pIdList = pColumn;
101524     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
101525     pTriggerStep->orconf = orconf;
101526   }else{
101527     sqlite3IdListDelete(db, pColumn);
101528   }
101529   sqlite3ExprListDelete(db, pEList);
101530   sqlite3SelectDelete(db, pSelect);
101531
101532   return pTriggerStep;
101533 }
101534
101535 /*
101536 ** Construct a trigger step that implements an UPDATE statement and return
101537 ** a pointer to that trigger step.  The parser calls this routine when it
101538 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
101539 */
101540 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
101541   sqlite3 *db,         /* The database connection */
101542   Token *pTableName,   /* Name of the table to be updated */
101543   ExprList *pEList,    /* The SET clause: list of column and new values */
101544   Expr *pWhere,        /* The WHERE clause */
101545   u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
101546 ){
101547   TriggerStep *pTriggerStep;
101548
101549   pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
101550   if( pTriggerStep ){
101551     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
101552     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
101553     pTriggerStep->orconf = orconf;
101554   }
101555   sqlite3ExprListDelete(db, pEList);
101556   sqlite3ExprDelete(db, pWhere);
101557   return pTriggerStep;
101558 }
101559
101560 /*
101561 ** Construct a trigger step that implements a DELETE statement and return
101562 ** a pointer to that trigger step.  The parser calls this routine when it
101563 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
101564 */
101565 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
101566   sqlite3 *db,            /* Database connection */
101567   Token *pTableName,      /* The table from which rows are deleted */
101568   Expr *pWhere            /* The WHERE clause */
101569 ){
101570   TriggerStep *pTriggerStep;
101571
101572   pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
101573   if( pTriggerStep ){
101574     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
101575     pTriggerStep->orconf = OE_Default;
101576   }
101577   sqlite3ExprDelete(db, pWhere);
101578   return pTriggerStep;
101579 }
101580
101581 /* 
101582 ** Recursively delete a Trigger structure
101583 */
101584 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
101585   if( pTrigger==0 ) return;
101586   sqlite3DeleteTriggerStep(db, pTrigger->step_list);
101587   sqlite3DbFree(db, pTrigger->zName);
101588   sqlite3DbFree(db, pTrigger->table);
101589   sqlite3ExprDelete(db, pTrigger->pWhen);
101590   sqlite3IdListDelete(db, pTrigger->pColumns);
101591   sqlite3DbFree(db, pTrigger);
101592 }
101593
101594 /*
101595 ** This function is called to drop a trigger from the database schema. 
101596 **
101597 ** This may be called directly from the parser and therefore identifies
101598 ** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
101599 ** same job as this routine except it takes a pointer to the trigger
101600 ** instead of the trigger name.
101601 **/
101602 SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
101603   Trigger *pTrigger = 0;
101604   int i;
101605   const char *zDb;
101606   const char *zName;
101607   int nName;
101608   sqlite3 *db = pParse->db;
101609
101610   if( db->mallocFailed ) goto drop_trigger_cleanup;
101611   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
101612     goto drop_trigger_cleanup;
101613   }
101614
101615   assert( pName->nSrc==1 );
101616   zDb = pName->a[0].zDatabase;
101617   zName = pName->a[0].zName;
101618   nName = sqlite3Strlen30(zName);
101619   assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
101620   for(i=OMIT_TEMPDB; i<db->nDb; i++){
101621     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
101622     if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
101623     assert( sqlite3SchemaMutexHeld(db, j, 0) );
101624     pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
101625     if( pTrigger ) break;
101626   }
101627   if( !pTrigger ){
101628     if( !noErr ){
101629       sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
101630     }else{
101631       sqlite3CodeVerifyNamedSchema(pParse, zDb);
101632     }
101633     pParse->checkSchema = 1;
101634     goto drop_trigger_cleanup;
101635   }
101636   sqlite3DropTriggerPtr(pParse, pTrigger);
101637
101638 drop_trigger_cleanup:
101639   sqlite3SrcListDelete(db, pName);
101640 }
101641
101642 /*
101643 ** Return a pointer to the Table structure for the table that a trigger
101644 ** is set on.
101645 */
101646 static Table *tableOfTrigger(Trigger *pTrigger){
101647   int n = sqlite3Strlen30(pTrigger->table);
101648   return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
101649 }
101650
101651
101652 /*
101653 ** Drop a trigger given a pointer to that trigger. 
101654 */
101655 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
101656   Table   *pTable;
101657   Vdbe *v;
101658   sqlite3 *db = pParse->db;
101659   int iDb;
101660
101661   iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
101662   assert( iDb>=0 && iDb<db->nDb );
101663   pTable = tableOfTrigger(pTrigger);
101664   assert( pTable );
101665   assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
101666 #ifndef SQLITE_OMIT_AUTHORIZATION
101667   {
101668     int code = SQLITE_DROP_TRIGGER;
101669     const char *zDb = db->aDb[iDb].zName;
101670     const char *zTab = SCHEMA_TABLE(iDb);
101671     if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
101672     if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
101673       sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
101674       return;
101675     }
101676   }
101677 #endif
101678
101679   /* Generate code to destroy the database record of the trigger.
101680   */
101681   assert( pTable!=0 );
101682   if( (v = sqlite3GetVdbe(pParse))!=0 ){
101683     int base;
101684     static const VdbeOpList dropTrigger[] = {
101685       { OP_Rewind,     0, ADDR(9),  0},
101686       { OP_String8,    0, 1,        0}, /* 1 */
101687       { OP_Column,     0, 1,        2},
101688       { OP_Ne,         2, ADDR(8),  1},
101689       { OP_String8,    0, 1,        0}, /* 4: "trigger" */
101690       { OP_Column,     0, 0,        2},
101691       { OP_Ne,         2, ADDR(8),  1},
101692       { OP_Delete,     0, 0,        0},
101693       { OP_Next,       0, ADDR(1),  0}, /* 8 */
101694     };
101695
101696     sqlite3BeginWriteOperation(pParse, 0, iDb);
101697     sqlite3OpenMasterTable(pParse, iDb);
101698     base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger);
101699     sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
101700     sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
101701     sqlite3ChangeCookie(pParse, iDb);
101702     sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
101703     sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
101704     if( pParse->nMem<3 ){
101705       pParse->nMem = 3;
101706     }
101707   }
101708 }
101709
101710 /*
101711 ** Remove a trigger from the hash tables of the sqlite* pointer.
101712 */
101713 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
101714   Trigger *pTrigger;
101715   Hash *pHash;
101716
101717   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
101718   pHash = &(db->aDb[iDb].pSchema->trigHash);
101719   pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
101720   if( ALWAYS(pTrigger) ){
101721     if( pTrigger->pSchema==pTrigger->pTabSchema ){
101722       Table *pTab = tableOfTrigger(pTrigger);
101723       Trigger **pp;
101724       for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
101725       *pp = (*pp)->pNext;
101726     }
101727     sqlite3DeleteTrigger(db, pTrigger);
101728     db->flags |= SQLITE_InternChanges;
101729   }
101730 }
101731
101732 /*
101733 ** pEList is the SET clause of an UPDATE statement.  Each entry
101734 ** in pEList is of the format <id>=<expr>.  If any of the entries
101735 ** in pEList have an <id> which matches an identifier in pIdList,
101736 ** then return TRUE.  If pIdList==NULL, then it is considered a
101737 ** wildcard that matches anything.  Likewise if pEList==NULL then
101738 ** it matches anything so always return true.  Return false only
101739 ** if there is no match.
101740 */
101741 static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
101742   int e;
101743   if( pIdList==0 || NEVER(pEList==0) ) return 1;
101744   for(e=0; e<pEList->nExpr; e++){
101745     if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
101746   }
101747   return 0; 
101748 }
101749
101750 /*
101751 ** Return a list of all triggers on table pTab if there exists at least
101752 ** one trigger that must be fired when an operation of type 'op' is 
101753 ** performed on the table, and, if that operation is an UPDATE, if at
101754 ** least one of the columns in pChanges is being modified.
101755 */
101756 SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
101757   Parse *pParse,          /* Parse context */
101758   Table *pTab,            /* The table the contains the triggers */
101759   int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
101760   ExprList *pChanges,     /* Columns that change in an UPDATE statement */
101761   int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
101762 ){
101763   int mask = 0;
101764   Trigger *pList = 0;
101765   Trigger *p;
101766
101767   if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
101768     pList = sqlite3TriggerList(pParse, pTab);
101769   }
101770   assert( pList==0 || IsVirtual(pTab)==0 );
101771   for(p=pList; p; p=p->pNext){
101772     if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
101773       mask |= p->tr_tm;
101774     }
101775   }
101776   if( pMask ){
101777     *pMask = mask;
101778   }
101779   return (mask ? pList : 0);
101780 }
101781
101782 /*
101783 ** Convert the pStep->target token into a SrcList and return a pointer
101784 ** to that SrcList.
101785 **
101786 ** This routine adds a specific database name, if needed, to the target when
101787 ** forming the SrcList.  This prevents a trigger in one database from
101788 ** referring to a target in another database.  An exception is when the
101789 ** trigger is in TEMP in which case it can refer to any other database it
101790 ** wants.
101791 */
101792 static SrcList *targetSrcList(
101793   Parse *pParse,       /* The parsing context */
101794   TriggerStep *pStep   /* The trigger containing the target token */
101795 ){
101796   int iDb;             /* Index of the database to use */
101797   SrcList *pSrc;       /* SrcList to be returned */
101798
101799   pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
101800   if( pSrc ){
101801     assert( pSrc->nSrc>0 );
101802     assert( pSrc->a!=0 );
101803     iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
101804     if( iDb==0 || iDb>=2 ){
101805       sqlite3 *db = pParse->db;
101806       assert( iDb<pParse->db->nDb );
101807       pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
101808     }
101809   }
101810   return pSrc;
101811 }
101812
101813 /*
101814 ** Generate VDBE code for the statements inside the body of a single 
101815 ** trigger.
101816 */
101817 static int codeTriggerProgram(
101818   Parse *pParse,            /* The parser context */
101819   TriggerStep *pStepList,   /* List of statements inside the trigger body */
101820   int orconf                /* Conflict algorithm. (OE_Abort, etc) */  
101821 ){
101822   TriggerStep *pStep;
101823   Vdbe *v = pParse->pVdbe;
101824   sqlite3 *db = pParse->db;
101825
101826   assert( pParse->pTriggerTab && pParse->pToplevel );
101827   assert( pStepList );
101828   assert( v!=0 );
101829   for(pStep=pStepList; pStep; pStep=pStep->pNext){
101830     /* Figure out the ON CONFLICT policy that will be used for this step
101831     ** of the trigger program. If the statement that caused this trigger
101832     ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
101833     ** the ON CONFLICT policy that was specified as part of the trigger
101834     ** step statement. Example:
101835     **
101836     **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
101837     **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
101838     **   END;
101839     **
101840     **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
101841     **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
101842     */
101843     pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
101844
101845     /* Clear the cookieGoto flag. When coding triggers, the cookieGoto 
101846     ** variable is used as a flag to indicate to sqlite3ExprCodeConstants()
101847     ** that it is not safe to refactor constants (this happens after the
101848     ** start of the first loop in the SQL statement is coded - at that 
101849     ** point code may be conditionally executed, so it is no longer safe to 
101850     ** initialize constant register values).  */
101851     assert( pParse->cookieGoto==0 || pParse->cookieGoto==-1 );
101852     pParse->cookieGoto = 0;
101853
101854     switch( pStep->op ){
101855       case TK_UPDATE: {
101856         sqlite3Update(pParse, 
101857           targetSrcList(pParse, pStep),
101858           sqlite3ExprListDup(db, pStep->pExprList, 0), 
101859           sqlite3ExprDup(db, pStep->pWhere, 0), 
101860           pParse->eOrconf
101861         );
101862         break;
101863       }
101864       case TK_INSERT: {
101865         sqlite3Insert(pParse, 
101866           targetSrcList(pParse, pStep),
101867           sqlite3ExprListDup(db, pStep->pExprList, 0), 
101868           sqlite3SelectDup(db, pStep->pSelect, 0), 
101869           sqlite3IdListDup(db, pStep->pIdList), 
101870           pParse->eOrconf
101871         );
101872         break;
101873       }
101874       case TK_DELETE: {
101875         sqlite3DeleteFrom(pParse, 
101876           targetSrcList(pParse, pStep),
101877           sqlite3ExprDup(db, pStep->pWhere, 0)
101878         );
101879         break;
101880       }
101881       default: assert( pStep->op==TK_SELECT ); {
101882         SelectDest sDest;
101883         Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
101884         sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
101885         sqlite3Select(pParse, pSelect, &sDest);
101886         sqlite3SelectDelete(db, pSelect);
101887         break;
101888       }
101889     } 
101890     if( pStep->op!=TK_SELECT ){
101891       sqlite3VdbeAddOp0(v, OP_ResetCount);
101892     }
101893   }
101894
101895   return 0;
101896 }
101897
101898 #ifdef SQLITE_DEBUG
101899 /*
101900 ** This function is used to add VdbeComment() annotations to a VDBE
101901 ** program. It is not used in production code, only for debugging.
101902 */
101903 static const char *onErrorText(int onError){
101904   switch( onError ){
101905     case OE_Abort:    return "abort";
101906     case OE_Rollback: return "rollback";
101907     case OE_Fail:     return "fail";
101908     case OE_Replace:  return "replace";
101909     case OE_Ignore:   return "ignore";
101910     case OE_Default:  return "default";
101911   }
101912   return "n/a";
101913 }
101914 #endif
101915
101916 /*
101917 ** Parse context structure pFrom has just been used to create a sub-vdbe
101918 ** (trigger program). If an error has occurred, transfer error information
101919 ** from pFrom to pTo.
101920 */
101921 static void transferParseError(Parse *pTo, Parse *pFrom){
101922   assert( pFrom->zErrMsg==0 || pFrom->nErr );
101923   assert( pTo->zErrMsg==0 || pTo->nErr );
101924   if( pTo->nErr==0 ){
101925     pTo->zErrMsg = pFrom->zErrMsg;
101926     pTo->nErr = pFrom->nErr;
101927   }else{
101928     sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
101929   }
101930 }
101931
101932 /*
101933 ** Create and populate a new TriggerPrg object with a sub-program 
101934 ** implementing trigger pTrigger with ON CONFLICT policy orconf.
101935 */
101936 static TriggerPrg *codeRowTrigger(
101937   Parse *pParse,       /* Current parse context */
101938   Trigger *pTrigger,   /* Trigger to code */
101939   Table *pTab,         /* The table pTrigger is attached to */
101940   int orconf           /* ON CONFLICT policy to code trigger program with */
101941 ){
101942   Parse *pTop = sqlite3ParseToplevel(pParse);
101943   sqlite3 *db = pParse->db;   /* Database handle */
101944   TriggerPrg *pPrg;           /* Value to return */
101945   Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
101946   Vdbe *v;                    /* Temporary VM */
101947   NameContext sNC;            /* Name context for sub-vdbe */
101948   SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
101949   Parse *pSubParse;           /* Parse context for sub-vdbe */
101950   int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
101951
101952   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
101953   assert( pTop->pVdbe );
101954
101955   /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
101956   ** are freed if an error occurs, link them into the Parse.pTriggerPrg 
101957   ** list of the top-level Parse object sooner rather than later.  */
101958   pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
101959   if( !pPrg ) return 0;
101960   pPrg->pNext = pTop->pTriggerPrg;
101961   pTop->pTriggerPrg = pPrg;
101962   pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
101963   if( !pProgram ) return 0;
101964   sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
101965   pPrg->pTrigger = pTrigger;
101966   pPrg->orconf = orconf;
101967   pPrg->aColmask[0] = 0xffffffff;
101968   pPrg->aColmask[1] = 0xffffffff;
101969
101970   /* Allocate and populate a new Parse context to use for coding the 
101971   ** trigger sub-program.  */
101972   pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
101973   if( !pSubParse ) return 0;
101974   memset(&sNC, 0, sizeof(sNC));
101975   sNC.pParse = pSubParse;
101976   pSubParse->db = db;
101977   pSubParse->pTriggerTab = pTab;
101978   pSubParse->pToplevel = pTop;
101979   pSubParse->zAuthContext = pTrigger->zName;
101980   pSubParse->eTriggerOp = pTrigger->op;
101981   pSubParse->nQueryLoop = pParse->nQueryLoop;
101982
101983   v = sqlite3GetVdbe(pSubParse);
101984   if( v ){
101985     VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)", 
101986       pTrigger->zName, onErrorText(orconf),
101987       (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
101988         (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
101989         (pTrigger->op==TK_INSERT ? "INSERT" : ""),
101990         (pTrigger->op==TK_DELETE ? "DELETE" : ""),
101991       pTab->zName
101992     ));
101993 #ifndef SQLITE_OMIT_TRACE
101994     sqlite3VdbeChangeP4(v, -1, 
101995       sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
101996     );
101997 #endif
101998
101999     /* If one was specified, code the WHEN clause. If it evaluates to false
102000     ** (or NULL) the sub-vdbe is immediately halted by jumping to the 
102001     ** OP_Halt inserted at the end of the program.  */
102002     if( pTrigger->pWhen ){
102003       pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
102004       if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen) 
102005        && db->mallocFailed==0 
102006       ){
102007         iEndTrigger = sqlite3VdbeMakeLabel(v);
102008         sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
102009       }
102010       sqlite3ExprDelete(db, pWhen);
102011     }
102012
102013     /* Code the trigger program into the sub-vdbe. */
102014     codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
102015
102016     /* Insert an OP_Halt at the end of the sub-program. */
102017     if( iEndTrigger ){
102018       sqlite3VdbeResolveLabel(v, iEndTrigger);
102019     }
102020     sqlite3VdbeAddOp0(v, OP_Halt);
102021     VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
102022
102023     transferParseError(pParse, pSubParse);
102024     if( db->mallocFailed==0 ){
102025       pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
102026     }
102027     pProgram->nMem = pSubParse->nMem;
102028     pProgram->nCsr = pSubParse->nTab;
102029     pProgram->nOnce = pSubParse->nOnce;
102030     pProgram->token = (void *)pTrigger;
102031     pPrg->aColmask[0] = pSubParse->oldmask;
102032     pPrg->aColmask[1] = pSubParse->newmask;
102033     sqlite3VdbeDelete(v);
102034   }
102035
102036   assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
102037   assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
102038   sqlite3StackFree(db, pSubParse);
102039
102040   return pPrg;
102041 }
102042     
102043 /*
102044 ** Return a pointer to a TriggerPrg object containing the sub-program for
102045 ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
102046 ** TriggerPrg object exists, a new object is allocated and populated before
102047 ** being returned.
102048 */
102049 static TriggerPrg *getRowTrigger(
102050   Parse *pParse,       /* Current parse context */
102051   Trigger *pTrigger,   /* Trigger to code */
102052   Table *pTab,         /* The table trigger pTrigger is attached to */
102053   int orconf           /* ON CONFLICT algorithm. */
102054 ){
102055   Parse *pRoot = sqlite3ParseToplevel(pParse);
102056   TriggerPrg *pPrg;
102057
102058   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
102059
102060   /* It may be that this trigger has already been coded (or is in the
102061   ** process of being coded). If this is the case, then an entry with
102062   ** a matching TriggerPrg.pTrigger field will be present somewhere
102063   ** in the Parse.pTriggerPrg list. Search for such an entry.  */
102064   for(pPrg=pRoot->pTriggerPrg; 
102065       pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf); 
102066       pPrg=pPrg->pNext
102067   );
102068
102069   /* If an existing TriggerPrg could not be located, create a new one. */
102070   if( !pPrg ){
102071     pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
102072   }
102073
102074   return pPrg;
102075 }
102076
102077 /*
102078 ** Generate code for the trigger program associated with trigger p on 
102079 ** table pTab. The reg, orconf and ignoreJump parameters passed to this
102080 ** function are the same as those described in the header function for
102081 ** sqlite3CodeRowTrigger()
102082 */
102083 SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
102084   Parse *pParse,       /* Parse context */
102085   Trigger *p,          /* Trigger to code */
102086   Table *pTab,         /* The table to code triggers from */
102087   int reg,             /* Reg array containing OLD.* and NEW.* values */
102088   int orconf,          /* ON CONFLICT policy */
102089   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
102090 ){
102091   Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
102092   TriggerPrg *pPrg;
102093   pPrg = getRowTrigger(pParse, p, pTab, orconf);
102094   assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
102095
102096   /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program 
102097   ** is a pointer to the sub-vdbe containing the trigger program.  */
102098   if( pPrg ){
102099     int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
102100
102101     sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
102102     sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
102103     VdbeComment(
102104         (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
102105
102106     /* Set the P5 operand of the OP_Program instruction to non-zero if
102107     ** recursive invocation of this trigger program is disallowed. Recursive
102108     ** invocation is disallowed if (a) the sub-program is really a trigger,
102109     ** not a foreign key action, and (b) the flag to enable recursive triggers
102110     ** is clear.  */
102111     sqlite3VdbeChangeP5(v, (u8)bRecursive);
102112   }
102113 }
102114
102115 /*
102116 ** This is called to code the required FOR EACH ROW triggers for an operation
102117 ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
102118 ** is given by the op paramater. The tr_tm parameter determines whether the
102119 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
102120 ** parameter pChanges is passed the list of columns being modified.
102121 **
102122 ** If there are no triggers that fire at the specified time for the specified
102123 ** operation on pTab, this function is a no-op.
102124 **
102125 ** The reg argument is the address of the first in an array of registers 
102126 ** that contain the values substituted for the new.* and old.* references
102127 ** in the trigger program. If N is the number of columns in table pTab
102128 ** (a copy of pTab->nCol), then registers are populated as follows:
102129 **
102130 **   Register       Contains
102131 **   ------------------------------------------------------
102132 **   reg+0          OLD.rowid
102133 **   reg+1          OLD.* value of left-most column of pTab
102134 **   ...            ...
102135 **   reg+N          OLD.* value of right-most column of pTab
102136 **   reg+N+1        NEW.rowid
102137 **   reg+N+2        OLD.* value of left-most column of pTab
102138 **   ...            ...
102139 **   reg+N+N+1      NEW.* value of right-most column of pTab
102140 **
102141 ** For ON DELETE triggers, the registers containing the NEW.* values will
102142 ** never be accessed by the trigger program, so they are not allocated or 
102143 ** populated by the caller (there is no data to populate them with anyway). 
102144 ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
102145 ** are never accessed, and so are not allocated by the caller. So, for an
102146 ** ON INSERT trigger, the value passed to this function as parameter reg
102147 ** is not a readable register, although registers (reg+N) through 
102148 ** (reg+N+N+1) are.
102149 **
102150 ** Parameter orconf is the default conflict resolution algorithm for the
102151 ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
102152 ** is the instruction that control should jump to if a trigger program
102153 ** raises an IGNORE exception.
102154 */
102155 SQLITE_PRIVATE void sqlite3CodeRowTrigger(
102156   Parse *pParse,       /* Parse context */
102157   Trigger *pTrigger,   /* List of triggers on table pTab */
102158   int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
102159   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
102160   int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
102161   Table *pTab,         /* The table to code triggers from */
102162   int reg,             /* The first in an array of registers (see above) */
102163   int orconf,          /* ON CONFLICT policy */
102164   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
102165 ){
102166   Trigger *p;          /* Used to iterate through pTrigger list */
102167
102168   assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
102169   assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
102170   assert( (op==TK_UPDATE)==(pChanges!=0) );
102171
102172   for(p=pTrigger; p; p=p->pNext){
102173
102174     /* Sanity checking:  The schema for the trigger and for the table are
102175     ** always defined.  The trigger must be in the same schema as the table
102176     ** or else it must be a TEMP trigger. */
102177     assert( p->pSchema!=0 );
102178     assert( p->pTabSchema!=0 );
102179     assert( p->pSchema==p->pTabSchema 
102180          || p->pSchema==pParse->db->aDb[1].pSchema );
102181
102182     /* Determine whether we should code this trigger */
102183     if( p->op==op 
102184      && p->tr_tm==tr_tm 
102185      && checkColumnOverlap(p->pColumns, pChanges)
102186     ){
102187       sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
102188     }
102189   }
102190 }
102191
102192 /*
102193 ** Triggers may access values stored in the old.* or new.* pseudo-table. 
102194 ** This function returns a 32-bit bitmask indicating which columns of the 
102195 ** old.* or new.* tables actually are used by triggers. This information 
102196 ** may be used by the caller, for example, to avoid having to load the entire
102197 ** old.* record into memory when executing an UPDATE or DELETE command.
102198 **
102199 ** Bit 0 of the returned mask is set if the left-most column of the
102200 ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
102201 ** the second leftmost column value is required, and so on. If there
102202 ** are more than 32 columns in the table, and at least one of the columns
102203 ** with an index greater than 32 may be accessed, 0xffffffff is returned.
102204 **
102205 ** It is not possible to determine if the old.rowid or new.rowid column is 
102206 ** accessed by triggers. The caller must always assume that it is.
102207 **
102208 ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
102209 ** applies to the old.* table. If 1, the new.* table.
102210 **
102211 ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
102212 ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
102213 ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
102214 ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
102215 ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
102216 */
102217 SQLITE_PRIVATE u32 sqlite3TriggerColmask(
102218   Parse *pParse,       /* Parse context */
102219   Trigger *pTrigger,   /* List of triggers on table pTab */
102220   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
102221   int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
102222   int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
102223   Table *pTab,         /* The table to code triggers from */
102224   int orconf           /* Default ON CONFLICT policy for trigger steps */
102225 ){
102226   const int op = pChanges ? TK_UPDATE : TK_DELETE;
102227   u32 mask = 0;
102228   Trigger *p;
102229
102230   assert( isNew==1 || isNew==0 );
102231   for(p=pTrigger; p; p=p->pNext){
102232     if( p->op==op && (tr_tm&p->tr_tm)
102233      && checkColumnOverlap(p->pColumns,pChanges)
102234     ){
102235       TriggerPrg *pPrg;
102236       pPrg = getRowTrigger(pParse, p, pTab, orconf);
102237       if( pPrg ){
102238         mask |= pPrg->aColmask[isNew];
102239       }
102240     }
102241   }
102242
102243   return mask;
102244 }
102245
102246 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
102247
102248 /************** End of trigger.c *********************************************/
102249 /************** Begin file update.c ******************************************/
102250 /*
102251 ** 2001 September 15
102252 **
102253 ** The author disclaims copyright to this source code.  In place of
102254 ** a legal notice, here is a blessing:
102255 **
102256 **    May you do good and not evil.
102257 **    May you find forgiveness for yourself and forgive others.
102258 **    May you share freely, never taking more than you give.
102259 **
102260 *************************************************************************
102261 ** This file contains C code routines that are called by the parser
102262 ** to handle UPDATE statements.
102263 */
102264
102265 #ifndef SQLITE_OMIT_VIRTUALTABLE
102266 /* Forward declaration */
102267 static void updateVirtualTable(
102268   Parse *pParse,       /* The parsing context */
102269   SrcList *pSrc,       /* The virtual table to be modified */
102270   Table *pTab,         /* The virtual table */
102271   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
102272   Expr *pRowidExpr,    /* Expression used to recompute the rowid */
102273   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
102274   Expr *pWhere,        /* WHERE clause of the UPDATE statement */
102275   int onError          /* ON CONFLICT strategy */
102276 );
102277 #endif /* SQLITE_OMIT_VIRTUALTABLE */
102278
102279 /*
102280 ** The most recently coded instruction was an OP_Column to retrieve the
102281 ** i-th column of table pTab. This routine sets the P4 parameter of the 
102282 ** OP_Column to the default value, if any.
102283 **
102284 ** The default value of a column is specified by a DEFAULT clause in the 
102285 ** column definition. This was either supplied by the user when the table
102286 ** was created, or added later to the table definition by an ALTER TABLE
102287 ** command. If the latter, then the row-records in the table btree on disk
102288 ** may not contain a value for the column and the default value, taken
102289 ** from the P4 parameter of the OP_Column instruction, is returned instead.
102290 ** If the former, then all row-records are guaranteed to include a value
102291 ** for the column and the P4 value is not required.
102292 **
102293 ** Column definitions created by an ALTER TABLE command may only have 
102294 ** literal default values specified: a number, null or a string. (If a more
102295 ** complicated default expression value was provided, it is evaluated 
102296 ** when the ALTER TABLE is executed and one of the literal values written
102297 ** into the sqlite_master table.)
102298 **
102299 ** Therefore, the P4 parameter is only required if the default value for
102300 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
102301 ** function is capable of transforming these types of expressions into
102302 ** sqlite3_value objects.
102303 **
102304 ** If parameter iReg is not negative, code an OP_RealAffinity instruction
102305 ** on register iReg. This is used when an equivalent integer value is 
102306 ** stored in place of an 8-byte floating point value in order to save 
102307 ** space.
102308 */
102309 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
102310   assert( pTab!=0 );
102311   if( !pTab->pSelect ){
102312     sqlite3_value *pValue;
102313     u8 enc = ENC(sqlite3VdbeDb(v));
102314     Column *pCol = &pTab->aCol[i];
102315     VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
102316     assert( i<pTab->nCol );
102317     sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc, 
102318                          pCol->affinity, &pValue);
102319     if( pValue ){
102320       sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
102321     }
102322 #ifndef SQLITE_OMIT_FLOATING_POINT
102323     if( iReg>=0 && pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
102324       sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
102325     }
102326 #endif
102327   }
102328 }
102329
102330 /*
102331 ** Process an UPDATE statement.
102332 **
102333 **   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
102334 **          \_______/ \________/     \______/       \________________/
102335 *            onError   pTabList      pChanges             pWhere
102336 */
102337 SQLITE_PRIVATE void sqlite3Update(
102338   Parse *pParse,         /* The parser context */
102339   SrcList *pTabList,     /* The table in which we should change things */
102340   ExprList *pChanges,    /* Things to be changed */
102341   Expr *pWhere,          /* The WHERE clause.  May be null */
102342   int onError            /* How to handle constraint errors */
102343 ){
102344   int i, j;              /* Loop counters */
102345   Table *pTab;           /* The table to be updated */
102346   int addr = 0;          /* VDBE instruction address of the start of the loop */
102347   WhereInfo *pWInfo;     /* Information about the WHERE clause */
102348   Vdbe *v;               /* The virtual database engine */
102349   Index *pIdx;           /* For looping over indices */
102350   int nIdx;              /* Number of indices that need updating */
102351   int iCur;              /* VDBE Cursor number of pTab */
102352   sqlite3 *db;           /* The database structure */
102353   int *aRegIdx = 0;      /* One register assigned to each index to be updated */
102354   int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
102355                          ** an expression for the i-th column of the table.
102356                          ** aXRef[i]==-1 if the i-th column is not changed. */
102357   int chngRowid;         /* True if the record number is being changed */
102358   Expr *pRowidExpr = 0;  /* Expression defining the new record number */
102359   int openAll = 0;       /* True if all indices need to be opened */
102360   AuthContext sContext;  /* The authorization context */
102361   NameContext sNC;       /* The name-context to resolve expressions in */
102362   int iDb;               /* Database containing the table being updated */
102363   int okOnePass;         /* True for one-pass algorithm without the FIFO */
102364   int hasFK;             /* True if foreign key processing is required */
102365
102366 #ifndef SQLITE_OMIT_TRIGGER
102367   int isView;            /* True when updating a view (INSTEAD OF trigger) */
102368   Trigger *pTrigger;     /* List of triggers on pTab, if required */
102369   int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
102370 #endif
102371   int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
102372
102373   /* Register Allocations */
102374   int regRowCount = 0;   /* A count of rows changed */
102375   int regOldRowid;       /* The old rowid */
102376   int regNewRowid;       /* The new rowid */
102377   int regNew;            /* Content of the NEW.* table in triggers */
102378   int regOld = 0;        /* Content of OLD.* table in triggers */
102379   int regRowSet = 0;     /* Rowset of rows to be updated */
102380
102381   memset(&sContext, 0, sizeof(sContext));
102382   db = pParse->db;
102383   if( pParse->nErr || db->mallocFailed ){
102384     goto update_cleanup;
102385   }
102386   assert( pTabList->nSrc==1 );
102387
102388   /* Locate the table which we want to update. 
102389   */
102390   pTab = sqlite3SrcListLookup(pParse, pTabList);
102391   if( pTab==0 ) goto update_cleanup;
102392   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
102393
102394   /* Figure out if we have any triggers and if the table being
102395   ** updated is a view.
102396   */
102397 #ifndef SQLITE_OMIT_TRIGGER
102398   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
102399   isView = pTab->pSelect!=0;
102400   assert( pTrigger || tmask==0 );
102401 #else
102402 # define pTrigger 0
102403 # define isView 0
102404 # define tmask 0
102405 #endif
102406 #ifdef SQLITE_OMIT_VIEW
102407 # undef isView
102408 # define isView 0
102409 #endif
102410
102411   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
102412     goto update_cleanup;
102413   }
102414   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
102415     goto update_cleanup;
102416   }
102417   aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
102418   if( aXRef==0 ) goto update_cleanup;
102419   for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
102420
102421   /* Allocate a cursors for the main database table and for all indices.
102422   ** The index cursors might not be used, but if they are used they
102423   ** need to occur right after the database cursor.  So go ahead and
102424   ** allocate enough space, just in case.
102425   */
102426   pTabList->a[0].iCursor = iCur = pParse->nTab++;
102427   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
102428     pParse->nTab++;
102429   }
102430
102431   /* Initialize the name-context */
102432   memset(&sNC, 0, sizeof(sNC));
102433   sNC.pParse = pParse;
102434   sNC.pSrcList = pTabList;
102435
102436   /* Resolve the column names in all the expressions of the
102437   ** of the UPDATE statement.  Also find the column index
102438   ** for each column to be updated in the pChanges array.  For each
102439   ** column to be updated, make sure we have authorization to change
102440   ** that column.
102441   */
102442   chngRowid = 0;
102443   for(i=0; i<pChanges->nExpr; i++){
102444     if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
102445       goto update_cleanup;
102446     }
102447     for(j=0; j<pTab->nCol; j++){
102448       if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
102449         if( j==pTab->iPKey ){
102450           chngRowid = 1;
102451           pRowidExpr = pChanges->a[i].pExpr;
102452         }
102453         aXRef[j] = i;
102454         break;
102455       }
102456     }
102457     if( j>=pTab->nCol ){
102458       if( sqlite3IsRowid(pChanges->a[i].zName) ){
102459         j = -1;
102460         chngRowid = 1;
102461         pRowidExpr = pChanges->a[i].pExpr;
102462       }else{
102463         sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
102464         pParse->checkSchema = 1;
102465         goto update_cleanup;
102466       }
102467     }
102468 #ifndef SQLITE_OMIT_AUTHORIZATION
102469     {
102470       int rc;
102471       rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
102472                             j<0 ? "ROWID" : pTab->aCol[j].zName,
102473                             db->aDb[iDb].zName);
102474       if( rc==SQLITE_DENY ){
102475         goto update_cleanup;
102476       }else if( rc==SQLITE_IGNORE ){
102477         aXRef[j] = -1;
102478       }
102479     }
102480 #endif
102481   }
102482
102483   hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid);
102484
102485   /* Allocate memory for the array aRegIdx[].  There is one entry in the
102486   ** array for each index associated with table being updated.  Fill in
102487   ** the value with a register number for indices that are to be used
102488   ** and with zero for unused indices.
102489   */
102490   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
102491   if( nIdx>0 ){
102492     aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
102493     if( aRegIdx==0 ) goto update_cleanup;
102494   }
102495   for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
102496     int reg;
102497     if( hasFK || chngRowid ){
102498       reg = ++pParse->nMem;
102499     }else{
102500       reg = 0;
102501       for(i=0; i<pIdx->nColumn; i++){
102502         if( aXRef[pIdx->aiColumn[i]]>=0 ){
102503           reg = ++pParse->nMem;
102504           break;
102505         }
102506       }
102507     }
102508     aRegIdx[j] = reg;
102509   }
102510
102511   /* Begin generating code. */
102512   v = sqlite3GetVdbe(pParse);
102513   if( v==0 ) goto update_cleanup;
102514   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
102515   sqlite3BeginWriteOperation(pParse, 1, iDb);
102516
102517 #ifndef SQLITE_OMIT_VIRTUALTABLE
102518   /* Virtual tables must be handled separately */
102519   if( IsVirtual(pTab) ){
102520     updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
102521                        pWhere, onError);
102522     pWhere = 0;
102523     pTabList = 0;
102524     goto update_cleanup;
102525   }
102526 #endif
102527
102528   /* Allocate required registers. */
102529   regRowSet = ++pParse->nMem;
102530   regOldRowid = regNewRowid = ++pParse->nMem;
102531   if( pTrigger || hasFK ){
102532     regOld = pParse->nMem + 1;
102533     pParse->nMem += pTab->nCol;
102534   }
102535   if( chngRowid || pTrigger || hasFK ){
102536     regNewRowid = ++pParse->nMem;
102537   }
102538   regNew = pParse->nMem + 1;
102539   pParse->nMem += pTab->nCol;
102540
102541   /* Start the view context. */
102542   if( isView ){
102543     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
102544   }
102545
102546   /* If we are trying to update a view, realize that view into
102547   ** a ephemeral table.
102548   */
102549 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
102550   if( isView ){
102551     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
102552   }
102553 #endif
102554
102555   /* Resolve the column names in all the expressions in the
102556   ** WHERE clause.
102557   */
102558   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
102559     goto update_cleanup;
102560   }
102561
102562   /* Begin the database scan
102563   */
102564   sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
102565   pWInfo = sqlite3WhereBegin(
102566       pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED, 0
102567   );
102568   if( pWInfo==0 ) goto update_cleanup;
102569   okOnePass = pWInfo->okOnePass;
102570
102571   /* Remember the rowid of every item to be updated.
102572   */
102573   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
102574   if( !okOnePass ){
102575     sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
102576   }
102577
102578   /* End the database scan loop.
102579   */
102580   sqlite3WhereEnd(pWInfo);
102581
102582   /* Initialize the count of updated rows
102583   */
102584   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
102585     regRowCount = ++pParse->nMem;
102586     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
102587   }
102588
102589   if( !isView ){
102590     /* 
102591     ** Open every index that needs updating.  Note that if any
102592     ** index could potentially invoke a REPLACE conflict resolution 
102593     ** action, then we need to open all indices because we might need
102594     ** to be deleting some records.
102595     */
102596     if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite); 
102597     if( onError==OE_Replace ){
102598       openAll = 1;
102599     }else{
102600       openAll = 0;
102601       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
102602         if( pIdx->onError==OE_Replace ){
102603           openAll = 1;
102604           break;
102605         }
102606       }
102607     }
102608     for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
102609       assert( aRegIdx );
102610       if( openAll || aRegIdx[i]>0 ){
102611         KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
102612         sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
102613                        (char*)pKey, P4_KEYINFO_HANDOFF);
102614         assert( pParse->nTab>iCur+i+1 );
102615       }
102616     }
102617   }
102618
102619   /* Top of the update loop */
102620   if( okOnePass ){
102621     int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
102622     addr = sqlite3VdbeAddOp0(v, OP_Goto);
102623     sqlite3VdbeJumpHere(v, a1);
102624   }else{
102625     addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
102626   }
102627
102628   /* Make cursor iCur point to the record that is being updated. If
102629   ** this record does not exist for some reason (deleted by a trigger,
102630   ** for example, then jump to the next iteration of the RowSet loop.  */
102631   sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
102632
102633   /* If the record number will change, set register regNewRowid to
102634   ** contain the new value. If the record number is not being modified,
102635   ** then regNewRowid is the same register as regOldRowid, which is
102636   ** already populated.  */
102637   assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid );
102638   if( chngRowid ){
102639     sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
102640     sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
102641   }
102642
102643   /* If there are triggers on this table, populate an array of registers 
102644   ** with the required old.* column data.  */
102645   if( hasFK || pTrigger ){
102646     u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
102647     oldmask |= sqlite3TriggerColmask(pParse, 
102648         pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
102649     );
102650     for(i=0; i<pTab->nCol; i++){
102651       if( aXRef[i]<0 || oldmask==0xffffffff || (i<32 && (oldmask & (1<<i))) ){
102652         sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOld+i);
102653       }else{
102654         sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
102655       }
102656     }
102657     if( chngRowid==0 ){
102658       sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
102659     }
102660   }
102661
102662   /* Populate the array of registers beginning at regNew with the new
102663   ** row data. This array is used to check constaints, create the new
102664   ** table and index records, and as the values for any new.* references
102665   ** made by triggers.
102666   **
102667   ** If there are one or more BEFORE triggers, then do not populate the
102668   ** registers associated with columns that are (a) not modified by
102669   ** this UPDATE statement and (b) not accessed by new.* references. The
102670   ** values for registers not modified by the UPDATE must be reloaded from 
102671   ** the database after the BEFORE triggers are fired anyway (as the trigger 
102672   ** may have modified them). So not loading those that are not going to
102673   ** be used eliminates some redundant opcodes.
102674   */
102675   newmask = sqlite3TriggerColmask(
102676       pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
102677   );
102678   sqlite3VdbeAddOp3(v, OP_Null, 0, regNew, regNew+pTab->nCol-1);
102679   for(i=0; i<pTab->nCol; i++){
102680     if( i==pTab->iPKey ){
102681       /*sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);*/
102682     }else{
102683       j = aXRef[i];
102684       if( j>=0 ){
102685         sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
102686       }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask&(1<<i)) ){
102687         /* This branch loads the value of a column that will not be changed 
102688         ** into a register. This is done if there are no BEFORE triggers, or
102689         ** if there are one or more BEFORE triggers that use this value via
102690         ** a new.* reference in a trigger program.
102691         */
102692         testcase( i==31 );
102693         testcase( i==32 );
102694         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
102695         sqlite3ColumnDefault(v, pTab, i, regNew+i);
102696       }
102697     }
102698   }
102699
102700   /* Fire any BEFORE UPDATE triggers. This happens before constraints are
102701   ** verified. One could argue that this is wrong.
102702   */
102703   if( tmask&TRIGGER_BEFORE ){
102704     sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);
102705     sqlite3TableAffinityStr(v, pTab);
102706     sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
102707         TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);
102708
102709     /* The row-trigger may have deleted the row being updated. In this
102710     ** case, jump to the next row. No updates or AFTER triggers are 
102711     ** required. This behavior - what happens when the row being updated
102712     ** is deleted or renamed by a BEFORE trigger - is left undefined in the
102713     ** documentation.
102714     */
102715     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
102716
102717     /* If it did not delete it, the row-trigger may still have modified 
102718     ** some of the columns of the row being updated. Load the values for 
102719     ** all columns not modified by the update statement into their 
102720     ** registers in case this has happened.
102721     */
102722     for(i=0; i<pTab->nCol; i++){
102723       if( aXRef[i]<0 && i!=pTab->iPKey ){
102724         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
102725         sqlite3ColumnDefault(v, pTab, i, regNew+i);
102726       }
102727     }
102728   }
102729
102730   if( !isView ){
102731     int j1;                       /* Address of jump instruction */
102732
102733     /* Do constraint checks. */
102734     sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
102735         aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0);
102736
102737     /* Do FK constraint checks. */
102738     if( hasFK ){
102739       sqlite3FkCheck(pParse, pTab, regOldRowid, 0);
102740     }
102741
102742     /* Delete the index entries associated with the current record.  */
102743     j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
102744     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
102745   
102746     /* If changing the record number, delete the old record.  */
102747     if( hasFK || chngRowid ){
102748       sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
102749     }
102750     sqlite3VdbeJumpHere(v, j1);
102751
102752     if( hasFK ){
102753       sqlite3FkCheck(pParse, pTab, 0, regNewRowid);
102754     }
102755   
102756     /* Insert the new index entries and the new record. */
102757     sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0);
102758
102759     /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
102760     ** handle rows (possibly in other tables) that refer via a foreign key
102761     ** to the row just updated. */ 
102762     if( hasFK ){
102763       sqlite3FkActions(pParse, pTab, pChanges, regOldRowid);
102764     }
102765   }
102766
102767   /* Increment the row counter 
102768   */
102769   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
102770     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
102771   }
102772
102773   sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
102774       TRIGGER_AFTER, pTab, regOldRowid, onError, addr);
102775
102776   /* Repeat the above with the next record to be updated, until
102777   ** all record selected by the WHERE clause have been updated.
102778   */
102779   sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
102780   sqlite3VdbeJumpHere(v, addr);
102781
102782   /* Close all tables */
102783   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
102784     assert( aRegIdx );
102785     if( openAll || aRegIdx[i]>0 ){
102786       sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
102787     }
102788   }
102789   sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
102790
102791   /* Update the sqlite_sequence table by storing the content of the
102792   ** maximum rowid counter values recorded while inserting into
102793   ** autoincrement tables.
102794   */
102795   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
102796     sqlite3AutoincrementEnd(pParse);
102797   }
102798
102799   /*
102800   ** Return the number of rows that were changed. If this routine is 
102801   ** generating code because of a call to sqlite3NestedParse(), do not
102802   ** invoke the callback function.
102803   */
102804   if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
102805     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
102806     sqlite3VdbeSetNumCols(v, 1);
102807     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
102808   }
102809
102810 update_cleanup:
102811   sqlite3AuthContextPop(&sContext);
102812   sqlite3DbFree(db, aRegIdx);
102813   sqlite3DbFree(db, aXRef);
102814   sqlite3SrcListDelete(db, pTabList);
102815   sqlite3ExprListDelete(db, pChanges);
102816   sqlite3ExprDelete(db, pWhere);
102817   return;
102818 }
102819 /* Make sure "isView" and other macros defined above are undefined. Otherwise
102820 ** thely may interfere with compilation of other functions in this file
102821 ** (or in another file, if this file becomes part of the amalgamation).  */
102822 #ifdef isView
102823  #undef isView
102824 #endif
102825 #ifdef pTrigger
102826  #undef pTrigger
102827 #endif
102828
102829 #ifndef SQLITE_OMIT_VIRTUALTABLE
102830 /*
102831 ** Generate code for an UPDATE of a virtual table.
102832 **
102833 ** The strategy is that we create an ephemerial table that contains
102834 ** for each row to be changed:
102835 **
102836 **   (A)  The original rowid of that row.
102837 **   (B)  The revised rowid for the row. (note1)
102838 **   (C)  The content of every column in the row.
102839 **
102840 ** Then we loop over this ephemeral table and for each row in
102841 ** the ephermeral table call VUpdate.
102842 **
102843 ** When finished, drop the ephemeral table.
102844 **
102845 ** (note1) Actually, if we know in advance that (A) is always the same
102846 ** as (B) we only store (A), then duplicate (A) when pulling
102847 ** it out of the ephemeral table before calling VUpdate.
102848 */
102849 static void updateVirtualTable(
102850   Parse *pParse,       /* The parsing context */
102851   SrcList *pSrc,       /* The virtual table to be modified */
102852   Table *pTab,         /* The virtual table */
102853   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
102854   Expr *pRowid,        /* Expression used to recompute the rowid */
102855   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
102856   Expr *pWhere,        /* WHERE clause of the UPDATE statement */
102857   int onError          /* ON CONFLICT strategy */
102858 ){
102859   Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
102860   ExprList *pEList = 0;     /* The result set of the SELECT statement */
102861   Select *pSelect = 0;      /* The SELECT statement */
102862   Expr *pExpr;              /* Temporary expression */
102863   int ephemTab;             /* Table holding the result of the SELECT */
102864   int i;                    /* Loop counter */
102865   int addr;                 /* Address of top of loop */
102866   int iReg;                 /* First register in set passed to OP_VUpdate */
102867   sqlite3 *db = pParse->db; /* Database connection */
102868   const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
102869   SelectDest dest;
102870
102871   /* Construct the SELECT statement that will find the new values for
102872   ** all updated rows. 
102873   */
102874   pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
102875   if( pRowid ){
102876     pEList = sqlite3ExprListAppend(pParse, pEList,
102877                                    sqlite3ExprDup(db, pRowid, 0));
102878   }
102879   assert( pTab->iPKey<0 );
102880   for(i=0; i<pTab->nCol; i++){
102881     if( aXRef[i]>=0 ){
102882       pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
102883     }else{
102884       pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
102885     }
102886     pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
102887   }
102888   pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
102889   
102890   /* Create the ephemeral table into which the update results will
102891   ** be stored.
102892   */
102893   assert( v );
102894   ephemTab = pParse->nTab++;
102895   sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
102896   sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
102897
102898   /* fill the ephemeral table 
102899   */
102900   sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
102901   sqlite3Select(pParse, pSelect, &dest);
102902
102903   /* Generate code to scan the ephemeral table and call VUpdate. */
102904   iReg = ++pParse->nMem;
102905   pParse->nMem += pTab->nCol+1;
102906   addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
102907   sqlite3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);
102908   sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
102909   for(i=0; i<pTab->nCol; i++){
102910     sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
102911   }
102912   sqlite3VtabMakeWritable(pParse, pTab);
102913   sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
102914   sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
102915   sqlite3MayAbort(pParse);
102916   sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1);
102917   sqlite3VdbeJumpHere(v, addr);
102918   sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
102919
102920   /* Cleanup */
102921   sqlite3SelectDelete(db, pSelect);  
102922 }
102923 #endif /* SQLITE_OMIT_VIRTUALTABLE */
102924
102925 /************** End of update.c **********************************************/
102926 /************** Begin file vacuum.c ******************************************/
102927 /*
102928 ** 2003 April 6
102929 **
102930 ** The author disclaims copyright to this source code.  In place of
102931 ** a legal notice, here is a blessing:
102932 **
102933 **    May you do good and not evil.
102934 **    May you find forgiveness for yourself and forgive others.
102935 **    May you share freely, never taking more than you give.
102936 **
102937 *************************************************************************
102938 ** This file contains code used to implement the VACUUM command.
102939 **
102940 ** Most of the code in this file may be omitted by defining the
102941 ** SQLITE_OMIT_VACUUM macro.
102942 */
102943
102944 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
102945 /*
102946 ** Finalize a prepared statement.  If there was an error, store the
102947 ** text of the error message in *pzErrMsg.  Return the result code.
102948 */
102949 static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
102950   int rc;
102951   rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
102952   if( rc ){
102953     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
102954   }
102955   return rc;
102956 }
102957
102958 /*
102959 ** Execute zSql on database db. Return an error code.
102960 */
102961 static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
102962   sqlite3_stmt *pStmt;
102963   VVA_ONLY( int rc; )
102964   if( !zSql ){
102965     return SQLITE_NOMEM;
102966   }
102967   if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
102968     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
102969     return sqlite3_errcode(db);
102970   }
102971   VVA_ONLY( rc = ) sqlite3_step(pStmt);
102972   assert( rc!=SQLITE_ROW || (db->flags&SQLITE_CountRows) );
102973   return vacuumFinalize(db, pStmt, pzErrMsg);
102974 }
102975
102976 /*
102977 ** Execute zSql on database db. The statement returns exactly
102978 ** one column. Execute this as SQL on the same database.
102979 */
102980 static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
102981   sqlite3_stmt *pStmt;
102982   int rc;
102983
102984   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
102985   if( rc!=SQLITE_OK ) return rc;
102986
102987   while( SQLITE_ROW==sqlite3_step(pStmt) ){
102988     rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
102989     if( rc!=SQLITE_OK ){
102990       vacuumFinalize(db, pStmt, pzErrMsg);
102991       return rc;
102992     }
102993   }
102994
102995   return vacuumFinalize(db, pStmt, pzErrMsg);
102996 }
102997
102998 /*
102999 ** The non-standard VACUUM command is used to clean up the database,
103000 ** collapse free space, etc.  It is modelled after the VACUUM command
103001 ** in PostgreSQL.
103002 **
103003 ** In version 1.0.x of SQLite, the VACUUM command would call
103004 ** gdbm_reorganize() on all the database tables.  But beginning
103005 ** with 2.0.0, SQLite no longer uses GDBM so this command has
103006 ** become a no-op.
103007 */
103008 SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
103009   Vdbe *v = sqlite3GetVdbe(pParse);
103010   if( v ){
103011     sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
103012     sqlite3VdbeUsesBtree(v, 0);
103013   }
103014   return;
103015 }
103016
103017 /*
103018 ** This routine implements the OP_Vacuum opcode of the VDBE.
103019 */
103020 SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
103021   int rc = SQLITE_OK;     /* Return code from service routines */
103022   Btree *pMain;           /* The database being vacuumed */
103023   Btree *pTemp;           /* The temporary database we vacuum into */
103024   char *zSql = 0;         /* SQL statements */
103025   int saved_flags;        /* Saved value of the db->flags */
103026   int saved_nChange;      /* Saved value of db->nChange */
103027   int saved_nTotalChange; /* Saved value of db->nTotalChange */
103028   void (*saved_xTrace)(void*,const char*);  /* Saved db->xTrace */
103029   Db *pDb = 0;            /* Database to detach at end of vacuum */
103030   int isMemDb;            /* True if vacuuming a :memory: database */
103031   int nRes;               /* Bytes of reserved space at the end of each page */
103032   int nDb;                /* Number of attached databases */
103033
103034   if( !db->autoCommit ){
103035     sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
103036     return SQLITE_ERROR;
103037   }
103038   if( db->activeVdbeCnt>1 ){
103039     sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
103040     return SQLITE_ERROR;
103041   }
103042
103043   /* Save the current value of the database flags so that it can be 
103044   ** restored before returning. Then set the writable-schema flag, and
103045   ** disable CHECK and foreign key constraints.  */
103046   saved_flags = db->flags;
103047   saved_nChange = db->nChange;
103048   saved_nTotalChange = db->nTotalChange;
103049   saved_xTrace = db->xTrace;
103050   db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
103051   db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
103052   db->xTrace = 0;
103053
103054   pMain = db->aDb[0].pBt;
103055   isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
103056
103057   /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
103058   ** can be set to 'off' for this file, as it is not recovered if a crash
103059   ** occurs anyway. The integrity of the database is maintained by a
103060   ** (possibly synchronous) transaction opened on the main database before
103061   ** sqlite3BtreeCopyFile() is called.
103062   **
103063   ** An optimisation would be to use a non-journaled pager.
103064   ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
103065   ** that actually made the VACUUM run slower.  Very little journalling
103066   ** actually occurs when doing a vacuum since the vacuum_db is initially
103067   ** empty.  Only the journal header is written.  Apparently it takes more
103068   ** time to parse and run the PRAGMA to turn journalling off than it does
103069   ** to write the journal header file.
103070   */
103071   nDb = db->nDb;
103072   if( sqlite3TempInMemory(db) ){
103073     zSql = "ATTACH ':memory:' AS vacuum_db;";
103074   }else{
103075     zSql = "ATTACH '' AS vacuum_db;";
103076   }
103077   rc = execSql(db, pzErrMsg, zSql);
103078   if( db->nDb>nDb ){
103079     pDb = &db->aDb[db->nDb-1];
103080     assert( strcmp(pDb->zName,"vacuum_db")==0 );
103081   }
103082   if( rc!=SQLITE_OK ) goto end_of_vacuum;
103083   pTemp = db->aDb[db->nDb-1].pBt;
103084
103085   /* The call to execSql() to attach the temp database has left the file
103086   ** locked (as there was more than one active statement when the transaction
103087   ** to read the schema was concluded. Unlock it here so that this doesn't
103088   ** cause problems for the call to BtreeSetPageSize() below.  */
103089   sqlite3BtreeCommit(pTemp);
103090
103091   nRes = sqlite3BtreeGetReserve(pMain);
103092
103093   /* A VACUUM cannot change the pagesize of an encrypted database. */
103094 #ifdef SQLITE_HAS_CODEC
103095   if( db->nextPagesize ){
103096     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
103097     int nKey;
103098     char *zKey;
103099     sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
103100     if( nKey ) db->nextPagesize = 0;
103101   }
103102 #endif
103103
103104   rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
103105   if( rc!=SQLITE_OK ) goto end_of_vacuum;
103106
103107   /* Begin a transaction and take an exclusive lock on the main database
103108   ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
103109   ** to ensure that we do not try to change the page-size on a WAL database.
103110   */
103111   rc = execSql(db, pzErrMsg, "BEGIN;");
103112   if( rc!=SQLITE_OK ) goto end_of_vacuum;
103113   rc = sqlite3BtreeBeginTrans(pMain, 2);
103114   if( rc!=SQLITE_OK ) goto end_of_vacuum;
103115
103116   /* Do not attempt to change the page size for a WAL database */
103117   if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
103118                                                ==PAGER_JOURNALMODE_WAL ){
103119     db->nextPagesize = 0;
103120   }
103121
103122   if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
103123    || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
103124    || NEVER(db->mallocFailed)
103125   ){
103126     rc = SQLITE_NOMEM;
103127     goto end_of_vacuum;
103128   }
103129
103130 #ifndef SQLITE_OMIT_AUTOVACUUM
103131   sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
103132                                            sqlite3BtreeGetAutoVacuum(pMain));
103133 #endif
103134
103135   /* Query the schema of the main database. Create a mirror schema
103136   ** in the temporary database.
103137   */
103138   rc = execExecSql(db, pzErrMsg,
103139       "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
103140       "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
103141       "   AND rootpage>0"
103142   );
103143   if( rc!=SQLITE_OK ) goto end_of_vacuum;
103144   rc = execExecSql(db, pzErrMsg,
103145       "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
103146       "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
103147   if( rc!=SQLITE_OK ) goto end_of_vacuum;
103148   rc = execExecSql(db, pzErrMsg,
103149       "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
103150       "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
103151   if( rc!=SQLITE_OK ) goto end_of_vacuum;
103152
103153   /* Loop through the tables in the main database. For each, do
103154   ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
103155   ** the contents to the temporary database.
103156   */
103157   rc = execExecSql(db, pzErrMsg,
103158       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
103159       "|| ' SELECT * FROM main.' || quote(name) || ';'"
103160       "FROM main.sqlite_master "
103161       "WHERE type = 'table' AND name!='sqlite_sequence' "
103162       "  AND rootpage>0"
103163   );
103164   if( rc!=SQLITE_OK ) goto end_of_vacuum;
103165
103166   /* Copy over the sequence table
103167   */
103168   rc = execExecSql(db, pzErrMsg,
103169       "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
103170       "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
103171   );
103172   if( rc!=SQLITE_OK ) goto end_of_vacuum;
103173   rc = execExecSql(db, pzErrMsg,
103174       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
103175       "|| ' SELECT * FROM main.' || quote(name) || ';' "
103176       "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
103177   );
103178   if( rc!=SQLITE_OK ) goto end_of_vacuum;
103179
103180
103181   /* Copy the triggers, views, and virtual tables from the main database
103182   ** over to the temporary database.  None of these objects has any
103183   ** associated storage, so all we have to do is copy their entries
103184   ** from the SQLITE_MASTER table.
103185   */
103186   rc = execSql(db, pzErrMsg,
103187       "INSERT INTO vacuum_db.sqlite_master "
103188       "  SELECT type, name, tbl_name, rootpage, sql"
103189       "    FROM main.sqlite_master"
103190       "   WHERE type='view' OR type='trigger'"
103191       "      OR (type='table' AND rootpage=0)"
103192   );
103193   if( rc ) goto end_of_vacuum;
103194
103195   /* At this point, there is a write transaction open on both the 
103196   ** vacuum database and the main database. Assuming no error occurs,
103197   ** both transactions are closed by this block - the main database
103198   ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
103199   ** call to sqlite3BtreeCommit().
103200   */
103201   {
103202     u32 meta;
103203     int i;
103204
103205     /* This array determines which meta meta values are preserved in the
103206     ** vacuum.  Even entries are the meta value number and odd entries
103207     ** are an increment to apply to the meta value after the vacuum.
103208     ** The increment is used to increase the schema cookie so that other
103209     ** connections to the same database will know to reread the schema.
103210     */
103211     static const unsigned char aCopy[] = {
103212        BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
103213        BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
103214        BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
103215        BTREE_USER_VERSION,       0,  /* Preserve the user version */
103216        BTREE_APPLICATION_ID,     0,  /* Preserve the application id */
103217     };
103218
103219     assert( 1==sqlite3BtreeIsInTrans(pTemp) );
103220     assert( 1==sqlite3BtreeIsInTrans(pMain) );
103221
103222     /* Copy Btree meta values */
103223     for(i=0; i<ArraySize(aCopy); i+=2){
103224       /* GetMeta() and UpdateMeta() cannot fail in this context because
103225       ** we already have page 1 loaded into cache and marked dirty. */
103226       sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
103227       rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
103228       if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
103229     }
103230
103231     rc = sqlite3BtreeCopyFile(pMain, pTemp);
103232     if( rc!=SQLITE_OK ) goto end_of_vacuum;
103233     rc = sqlite3BtreeCommit(pTemp);
103234     if( rc!=SQLITE_OK ) goto end_of_vacuum;
103235 #ifndef SQLITE_OMIT_AUTOVACUUM
103236     sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
103237 #endif
103238   }
103239
103240   assert( rc==SQLITE_OK );
103241   rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
103242
103243 end_of_vacuum:
103244   /* Restore the original value of db->flags */
103245   db->flags = saved_flags;
103246   db->nChange = saved_nChange;
103247   db->nTotalChange = saved_nTotalChange;
103248   db->xTrace = saved_xTrace;
103249   sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
103250
103251   /* Currently there is an SQL level transaction open on the vacuum
103252   ** database. No locks are held on any other files (since the main file
103253   ** was committed at the btree level). So it safe to end the transaction
103254   ** by manually setting the autoCommit flag to true and detaching the
103255   ** vacuum database. The vacuum_db journal file is deleted when the pager
103256   ** is closed by the DETACH.
103257   */
103258   db->autoCommit = 1;
103259
103260   if( pDb ){
103261     sqlite3BtreeClose(pDb->pBt);
103262     pDb->pBt = 0;
103263     pDb->pSchema = 0;
103264   }
103265
103266   /* This both clears the schemas and reduces the size of the db->aDb[]
103267   ** array. */ 
103268   sqlite3ResetAllSchemasOfConnection(db);
103269
103270   return rc;
103271 }
103272
103273 #endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
103274
103275 /************** End of vacuum.c **********************************************/
103276 /************** Begin file vtab.c ********************************************/
103277 /*
103278 ** 2006 June 10
103279 **
103280 ** The author disclaims copyright to this source code.  In place of
103281 ** a legal notice, here is a blessing:
103282 **
103283 **    May you do good and not evil.
103284 **    May you find forgiveness for yourself and forgive others.
103285 **    May you share freely, never taking more than you give.
103286 **
103287 *************************************************************************
103288 ** This file contains code used to help implement virtual tables.
103289 */
103290 #ifndef SQLITE_OMIT_VIRTUALTABLE
103291
103292 /*
103293 ** Before a virtual table xCreate() or xConnect() method is invoked, the
103294 ** sqlite3.pVtabCtx member variable is set to point to an instance of
103295 ** this struct allocated on the stack. It is used by the implementation of 
103296 ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
103297 ** are invoked only from within xCreate and xConnect methods.
103298 */
103299 struct VtabCtx {
103300   VTable *pVTable;    /* The virtual table being constructed */
103301   Table *pTab;        /* The Table object to which the virtual table belongs */
103302 };
103303
103304 /*
103305 ** The actual function that does the work of creating a new module.
103306 ** This function implements the sqlite3_create_module() and
103307 ** sqlite3_create_module_v2() interfaces.
103308 */
103309 static int createModule(
103310   sqlite3 *db,                    /* Database in which module is registered */
103311   const char *zName,              /* Name assigned to this module */
103312   const sqlite3_module *pModule,  /* The definition of the module */
103313   void *pAux,                     /* Context pointer for xCreate/xConnect */
103314   void (*xDestroy)(void *)        /* Module destructor function */
103315 ){
103316   int rc = SQLITE_OK;
103317   int nName;
103318
103319   sqlite3_mutex_enter(db->mutex);
103320   nName = sqlite3Strlen30(zName);
103321   if( sqlite3HashFind(&db->aModule, zName, nName) ){
103322     rc = SQLITE_MISUSE_BKPT;
103323   }else{
103324     Module *pMod;
103325     pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
103326     if( pMod ){
103327       Module *pDel;
103328       char *zCopy = (char *)(&pMod[1]);
103329       memcpy(zCopy, zName, nName+1);
103330       pMod->zName = zCopy;
103331       pMod->pModule = pModule;
103332       pMod->pAux = pAux;
103333       pMod->xDestroy = xDestroy;
103334       pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,nName,(void*)pMod);
103335       assert( pDel==0 || pDel==pMod );
103336       if( pDel ){
103337         db->mallocFailed = 1;
103338         sqlite3DbFree(db, pDel);
103339       }
103340     }
103341   }
103342   rc = sqlite3ApiExit(db, rc);
103343   if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
103344
103345   sqlite3_mutex_leave(db->mutex);
103346   return rc;
103347 }
103348
103349
103350 /*
103351 ** External API function used to create a new virtual-table module.
103352 */
103353 SQLITE_API int sqlite3_create_module(
103354   sqlite3 *db,                    /* Database in which module is registered */
103355   const char *zName,              /* Name assigned to this module */
103356   const sqlite3_module *pModule,  /* The definition of the module */
103357   void *pAux                      /* Context pointer for xCreate/xConnect */
103358 ){
103359   return createModule(db, zName, pModule, pAux, 0);
103360 }
103361
103362 /*
103363 ** External API function used to create a new virtual-table module.
103364 */
103365 SQLITE_API int sqlite3_create_module_v2(
103366   sqlite3 *db,                    /* Database in which module is registered */
103367   const char *zName,              /* Name assigned to this module */
103368   const sqlite3_module *pModule,  /* The definition of the module */
103369   void *pAux,                     /* Context pointer for xCreate/xConnect */
103370   void (*xDestroy)(void *)        /* Module destructor function */
103371 ){
103372   return createModule(db, zName, pModule, pAux, xDestroy);
103373 }
103374
103375 /*
103376 ** Lock the virtual table so that it cannot be disconnected.
103377 ** Locks nest.  Every lock should have a corresponding unlock.
103378 ** If an unlock is omitted, resources leaks will occur.  
103379 **
103380 ** If a disconnect is attempted while a virtual table is locked,
103381 ** the disconnect is deferred until all locks have been removed.
103382 */
103383 SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
103384   pVTab->nRef++;
103385 }
103386
103387
103388 /*
103389 ** pTab is a pointer to a Table structure representing a virtual-table.
103390 ** Return a pointer to the VTable object used by connection db to access 
103391 ** this virtual-table, if one has been created, or NULL otherwise.
103392 */
103393 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
103394   VTable *pVtab;
103395   assert( IsVirtual(pTab) );
103396   for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
103397   return pVtab;
103398 }
103399
103400 /*
103401 ** Decrement the ref-count on a virtual table object. When the ref-count
103402 ** reaches zero, call the xDisconnect() method to delete the object.
103403 */
103404 SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
103405   sqlite3 *db = pVTab->db;
103406
103407   assert( db );
103408   assert( pVTab->nRef>0 );
103409   assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
103410
103411   pVTab->nRef--;
103412   if( pVTab->nRef==0 ){
103413     sqlite3_vtab *p = pVTab->pVtab;
103414     if( p ){
103415       p->pModule->xDisconnect(p);
103416     }
103417     sqlite3DbFree(db, pVTab);
103418   }
103419 }
103420
103421 /*
103422 ** Table p is a virtual table. This function moves all elements in the
103423 ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
103424 ** database connections to be disconnected at the next opportunity. 
103425 ** Except, if argument db is not NULL, then the entry associated with
103426 ** connection db is left in the p->pVTable list.
103427 */
103428 static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
103429   VTable *pRet = 0;
103430   VTable *pVTable = p->pVTable;
103431   p->pVTable = 0;
103432
103433   /* Assert that the mutex (if any) associated with the BtShared database 
103434   ** that contains table p is held by the caller. See header comments 
103435   ** above function sqlite3VtabUnlockList() for an explanation of why
103436   ** this makes it safe to access the sqlite3.pDisconnect list of any
103437   ** database connection that may have an entry in the p->pVTable list.
103438   */
103439   assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
103440
103441   while( pVTable ){
103442     sqlite3 *db2 = pVTable->db;
103443     VTable *pNext = pVTable->pNext;
103444     assert( db2 );
103445     if( db2==db ){
103446       pRet = pVTable;
103447       p->pVTable = pRet;
103448       pRet->pNext = 0;
103449     }else{
103450       pVTable->pNext = db2->pDisconnect;
103451       db2->pDisconnect = pVTable;
103452     }
103453     pVTable = pNext;
103454   }
103455
103456   assert( !db || pRet );
103457   return pRet;
103458 }
103459
103460 /*
103461 ** Table *p is a virtual table. This function removes the VTable object
103462 ** for table *p associated with database connection db from the linked
103463 ** list in p->pVTab. It also decrements the VTable ref count. This is
103464 ** used when closing database connection db to free all of its VTable
103465 ** objects without disturbing the rest of the Schema object (which may
103466 ** be being used by other shared-cache connections).
103467 */
103468 SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
103469   VTable **ppVTab;
103470
103471   assert( IsVirtual(p) );
103472   assert( sqlite3BtreeHoldsAllMutexes(db) );
103473   assert( sqlite3_mutex_held(db->mutex) );
103474
103475   for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
103476     if( (*ppVTab)->db==db  ){
103477       VTable *pVTab = *ppVTab;
103478       *ppVTab = pVTab->pNext;
103479       sqlite3VtabUnlock(pVTab);
103480       break;
103481     }
103482   }
103483 }
103484
103485
103486 /*
103487 ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
103488 **
103489 ** This function may only be called when the mutexes associated with all
103490 ** shared b-tree databases opened using connection db are held by the 
103491 ** caller. This is done to protect the sqlite3.pDisconnect list. The
103492 ** sqlite3.pDisconnect list is accessed only as follows:
103493 **
103494 **   1) By this function. In this case, all BtShared mutexes and the mutex
103495 **      associated with the database handle itself must be held.
103496 **
103497 **   2) By function vtabDisconnectAll(), when it adds a VTable entry to
103498 **      the sqlite3.pDisconnect list. In this case either the BtShared mutex
103499 **      associated with the database the virtual table is stored in is held
103500 **      or, if the virtual table is stored in a non-sharable database, then
103501 **      the database handle mutex is held.
103502 **
103503 ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously 
103504 ** by multiple threads. It is thread-safe.
103505 */
103506 SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
103507   VTable *p = db->pDisconnect;
103508   db->pDisconnect = 0;
103509
103510   assert( sqlite3BtreeHoldsAllMutexes(db) );
103511   assert( sqlite3_mutex_held(db->mutex) );
103512
103513   if( p ){
103514     sqlite3ExpirePreparedStatements(db);
103515     do {
103516       VTable *pNext = p->pNext;
103517       sqlite3VtabUnlock(p);
103518       p = pNext;
103519     }while( p );
103520   }
103521 }
103522
103523 /*
103524 ** Clear any and all virtual-table information from the Table record.
103525 ** This routine is called, for example, just before deleting the Table
103526 ** record.
103527 **
103528 ** Since it is a virtual-table, the Table structure contains a pointer
103529 ** to the head of a linked list of VTable structures. Each VTable 
103530 ** structure is associated with a single sqlite3* user of the schema.
103531 ** The reference count of the VTable structure associated with database 
103532 ** connection db is decremented immediately (which may lead to the 
103533 ** structure being xDisconnected and free). Any other VTable structures
103534 ** in the list are moved to the sqlite3.pDisconnect list of the associated 
103535 ** database connection.
103536 */
103537 SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
103538   if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
103539   if( p->azModuleArg ){
103540     int i;
103541     for(i=0; i<p->nModuleArg; i++){
103542       if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
103543     }
103544     sqlite3DbFree(db, p->azModuleArg);
103545   }
103546 }
103547
103548 /*
103549 ** Add a new module argument to pTable->azModuleArg[].
103550 ** The string is not copied - the pointer is stored.  The
103551 ** string will be freed automatically when the table is
103552 ** deleted.
103553 */
103554 static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
103555   int i = pTable->nModuleArg++;
103556   int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
103557   char **azModuleArg;
103558   azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
103559   if( azModuleArg==0 ){
103560     int j;
103561     for(j=0; j<i; j++){
103562       sqlite3DbFree(db, pTable->azModuleArg[j]);
103563     }
103564     sqlite3DbFree(db, zArg);
103565     sqlite3DbFree(db, pTable->azModuleArg);
103566     pTable->nModuleArg = 0;
103567   }else{
103568     azModuleArg[i] = zArg;
103569     azModuleArg[i+1] = 0;
103570   }
103571   pTable->azModuleArg = azModuleArg;
103572 }
103573
103574 /*
103575 ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
103576 ** statement.  The module name has been parsed, but the optional list
103577 ** of parameters that follow the module name are still pending.
103578 */
103579 SQLITE_PRIVATE void sqlite3VtabBeginParse(
103580   Parse *pParse,        /* Parsing context */
103581   Token *pName1,        /* Name of new table, or database name */
103582   Token *pName2,        /* Name of new table or NULL */
103583   Token *pModuleName,   /* Name of the module for the virtual table */
103584   int ifNotExists       /* No error if the table already exists */
103585 ){
103586   int iDb;              /* The database the table is being created in */
103587   Table *pTable;        /* The new virtual table */
103588   sqlite3 *db;          /* Database connection */
103589
103590   sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
103591   pTable = pParse->pNewTable;
103592   if( pTable==0 ) return;
103593   assert( 0==pTable->pIndex );
103594
103595   db = pParse->db;
103596   iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
103597   assert( iDb>=0 );
103598
103599   pTable->tabFlags |= TF_Virtual;
103600   pTable->nModuleArg = 0;
103601   addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
103602   addModuleArgument(db, pTable, 0);
103603   addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
103604   pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
103605
103606 #ifndef SQLITE_OMIT_AUTHORIZATION
103607   /* Creating a virtual table invokes the authorization callback twice.
103608   ** The first invocation, to obtain permission to INSERT a row into the
103609   ** sqlite_master table, has already been made by sqlite3StartTable().
103610   ** The second call, to obtain permission to create the table, is made now.
103611   */
103612   if( pTable->azModuleArg ){
103613     sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName, 
103614             pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
103615   }
103616 #endif
103617 }
103618
103619 /*
103620 ** This routine takes the module argument that has been accumulating
103621 ** in pParse->zArg[] and appends it to the list of arguments on the
103622 ** virtual table currently under construction in pParse->pTable.
103623 */
103624 static void addArgumentToVtab(Parse *pParse){
103625   if( pParse->sArg.z && pParse->pNewTable ){
103626     const char *z = (const char*)pParse->sArg.z;
103627     int n = pParse->sArg.n;
103628     sqlite3 *db = pParse->db;
103629     addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
103630   }
103631 }
103632
103633 /*
103634 ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
103635 ** has been completely parsed.
103636 */
103637 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
103638   Table *pTab = pParse->pNewTable;  /* The table being constructed */
103639   sqlite3 *db = pParse->db;         /* The database connection */
103640
103641   if( pTab==0 ) return;
103642   addArgumentToVtab(pParse);
103643   pParse->sArg.z = 0;
103644   if( pTab->nModuleArg<1 ) return;
103645   
103646   /* If the CREATE VIRTUAL TABLE statement is being entered for the
103647   ** first time (in other words if the virtual table is actually being
103648   ** created now instead of just being read out of sqlite_master) then
103649   ** do additional initialization work and store the statement text
103650   ** in the sqlite_master table.
103651   */
103652   if( !db->init.busy ){
103653     char *zStmt;
103654     char *zWhere;
103655     int iDb;
103656     Vdbe *v;
103657
103658     /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
103659     if( pEnd ){
103660       pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
103661     }
103662     zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
103663
103664     /* A slot for the record has already been allocated in the 
103665     ** SQLITE_MASTER table.  We just need to update that slot with all
103666     ** the information we've collected.  
103667     **
103668     ** The VM register number pParse->regRowid holds the rowid of an
103669     ** entry in the sqlite_master table tht was created for this vtab
103670     ** by sqlite3StartTable().
103671     */
103672     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
103673     sqlite3NestedParse(pParse,
103674       "UPDATE %Q.%s "
103675          "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
103676        "WHERE rowid=#%d",
103677       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
103678       pTab->zName,
103679       pTab->zName,
103680       zStmt,
103681       pParse->regRowid
103682     );
103683     sqlite3DbFree(db, zStmt);
103684     v = sqlite3GetVdbe(pParse);
103685     sqlite3ChangeCookie(pParse, iDb);
103686
103687     sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
103688     zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
103689     sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
103690     sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0, 
103691                          pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
103692   }
103693
103694   /* If we are rereading the sqlite_master table create the in-memory
103695   ** record of the table. The xConnect() method is not called until
103696   ** the first time the virtual table is used in an SQL statement. This
103697   ** allows a schema that contains virtual tables to be loaded before
103698   ** the required virtual table implementations are registered.  */
103699   else {
103700     Table *pOld;
103701     Schema *pSchema = pTab->pSchema;
103702     const char *zName = pTab->zName;
103703     int nName = sqlite3Strlen30(zName);
103704     assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
103705     pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
103706     if( pOld ){
103707       db->mallocFailed = 1;
103708       assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
103709       return;
103710     }
103711     pParse->pNewTable = 0;
103712   }
103713 }
103714
103715 /*
103716 ** The parser calls this routine when it sees the first token
103717 ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
103718 */
103719 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
103720   addArgumentToVtab(pParse);
103721   pParse->sArg.z = 0;
103722   pParse->sArg.n = 0;
103723 }
103724
103725 /*
103726 ** The parser calls this routine for each token after the first token
103727 ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
103728 */
103729 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
103730   Token *pArg = &pParse->sArg;
103731   if( pArg->z==0 ){
103732     pArg->z = p->z;
103733     pArg->n = p->n;
103734   }else{
103735     assert(pArg->z < p->z);
103736     pArg->n = (int)(&p->z[p->n] - pArg->z);
103737   }
103738 }
103739
103740 /*
103741 ** Invoke a virtual table constructor (either xCreate or xConnect). The
103742 ** pointer to the function to invoke is passed as the fourth parameter
103743 ** to this procedure.
103744 */
103745 static int vtabCallConstructor(
103746   sqlite3 *db, 
103747   Table *pTab,
103748   Module *pMod,
103749   int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
103750   char **pzErr
103751 ){
103752   VtabCtx sCtx, *pPriorCtx;
103753   VTable *pVTable;
103754   int rc;
103755   const char *const*azArg = (const char *const*)pTab->azModuleArg;
103756   int nArg = pTab->nModuleArg;
103757   char *zErr = 0;
103758   char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
103759   int iDb;
103760
103761   if( !zModuleName ){
103762     return SQLITE_NOMEM;
103763   }
103764
103765   pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
103766   if( !pVTable ){
103767     sqlite3DbFree(db, zModuleName);
103768     return SQLITE_NOMEM;
103769   }
103770   pVTable->db = db;
103771   pVTable->pMod = pMod;
103772
103773   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
103774   pTab->azModuleArg[1] = db->aDb[iDb].zName;
103775
103776   /* Invoke the virtual table constructor */
103777   assert( &db->pVtabCtx );
103778   assert( xConstruct );
103779   sCtx.pTab = pTab;
103780   sCtx.pVTable = pVTable;
103781   pPriorCtx = db->pVtabCtx;
103782   db->pVtabCtx = &sCtx;
103783   rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
103784   db->pVtabCtx = pPriorCtx;
103785   if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
103786
103787   if( SQLITE_OK!=rc ){
103788     if( zErr==0 ){
103789       *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
103790     }else {
103791       *pzErr = sqlite3MPrintf(db, "%s", zErr);
103792       sqlite3_free(zErr);
103793     }
103794     sqlite3DbFree(db, pVTable);
103795   }else if( ALWAYS(pVTable->pVtab) ){
103796     /* Justification of ALWAYS():  A correct vtab constructor must allocate
103797     ** the sqlite3_vtab object if successful.  */
103798     pVTable->pVtab->pModule = pMod->pModule;
103799     pVTable->nRef = 1;
103800     if( sCtx.pTab ){
103801       const char *zFormat = "vtable constructor did not declare schema: %s";
103802       *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
103803       sqlite3VtabUnlock(pVTable);
103804       rc = SQLITE_ERROR;
103805     }else{
103806       int iCol;
103807       /* If everything went according to plan, link the new VTable structure
103808       ** into the linked list headed by pTab->pVTable. Then loop through the 
103809       ** columns of the table to see if any of them contain the token "hidden".
103810       ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
103811       ** the type string.  */
103812       pVTable->pNext = pTab->pVTable;
103813       pTab->pVTable = pVTable;
103814
103815       for(iCol=0; iCol<pTab->nCol; iCol++){
103816         char *zType = pTab->aCol[iCol].zType;
103817         int nType;
103818         int i = 0;
103819         if( !zType ) continue;
103820         nType = sqlite3Strlen30(zType);
103821         if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
103822           for(i=0; i<nType; i++){
103823             if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
103824              && (zType[i+7]=='\0' || zType[i+7]==' ')
103825             ){
103826               i++;
103827               break;
103828             }
103829           }
103830         }
103831         if( i<nType ){
103832           int j;
103833           int nDel = 6 + (zType[i+6] ? 1 : 0);
103834           for(j=i; (j+nDel)<=nType; j++){
103835             zType[j] = zType[j+nDel];
103836           }
103837           if( zType[i]=='\0' && i>0 ){
103838             assert(zType[i-1]==' ');
103839             zType[i-1] = '\0';
103840           }
103841           pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
103842         }
103843       }
103844     }
103845   }
103846
103847   sqlite3DbFree(db, zModuleName);
103848   return rc;
103849 }
103850
103851 /*
103852 ** This function is invoked by the parser to call the xConnect() method
103853 ** of the virtual table pTab. If an error occurs, an error code is returned 
103854 ** and an error left in pParse.
103855 **
103856 ** This call is a no-op if table pTab is not a virtual table.
103857 */
103858 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
103859   sqlite3 *db = pParse->db;
103860   const char *zMod;
103861   Module *pMod;
103862   int rc;
103863
103864   assert( pTab );
103865   if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
103866     return SQLITE_OK;
103867   }
103868
103869   /* Locate the required virtual table module */
103870   zMod = pTab->azModuleArg[0];
103871   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
103872
103873   if( !pMod ){
103874     const char *zModule = pTab->azModuleArg[0];
103875     sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
103876     rc = SQLITE_ERROR;
103877   }else{
103878     char *zErr = 0;
103879     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
103880     if( rc!=SQLITE_OK ){
103881       sqlite3ErrorMsg(pParse, "%s", zErr);
103882     }
103883     sqlite3DbFree(db, zErr);
103884   }
103885
103886   return rc;
103887 }
103888 /*
103889 ** Grow the db->aVTrans[] array so that there is room for at least one
103890 ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
103891 */
103892 static int growVTrans(sqlite3 *db){
103893   const int ARRAY_INCR = 5;
103894
103895   /* Grow the sqlite3.aVTrans array if required */
103896   if( (db->nVTrans%ARRAY_INCR)==0 ){
103897     VTable **aVTrans;
103898     int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
103899     aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
103900     if( !aVTrans ){
103901       return SQLITE_NOMEM;
103902     }
103903     memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
103904     db->aVTrans = aVTrans;
103905   }
103906
103907   return SQLITE_OK;
103908 }
103909
103910 /*
103911 ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
103912 ** have already been reserved using growVTrans().
103913 */
103914 static void addToVTrans(sqlite3 *db, VTable *pVTab){
103915   /* Add pVtab to the end of sqlite3.aVTrans */
103916   db->aVTrans[db->nVTrans++] = pVTab;
103917   sqlite3VtabLock(pVTab);
103918 }
103919
103920 /*
103921 ** This function is invoked by the vdbe to call the xCreate method
103922 ** of the virtual table named zTab in database iDb. 
103923 **
103924 ** If an error occurs, *pzErr is set to point an an English language
103925 ** description of the error and an SQLITE_XXX error code is returned.
103926 ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
103927 */
103928 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
103929   int rc = SQLITE_OK;
103930   Table *pTab;
103931   Module *pMod;
103932   const char *zMod;
103933
103934   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
103935   assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
103936
103937   /* Locate the required virtual table module */
103938   zMod = pTab->azModuleArg[0];
103939   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
103940
103941   /* If the module has been registered and includes a Create method, 
103942   ** invoke it now. If the module has not been registered, return an 
103943   ** error. Otherwise, do nothing.
103944   */
103945   if( !pMod ){
103946     *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
103947     rc = SQLITE_ERROR;
103948   }else{
103949     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
103950   }
103951
103952   /* Justification of ALWAYS():  The xConstructor method is required to
103953   ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
103954   if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
103955     rc = growVTrans(db);
103956     if( rc==SQLITE_OK ){
103957       addToVTrans(db, sqlite3GetVTable(db, pTab));
103958     }
103959   }
103960
103961   return rc;
103962 }
103963
103964 /*
103965 ** This function is used to set the schema of a virtual table.  It is only
103966 ** valid to call this function from within the xCreate() or xConnect() of a
103967 ** virtual table module.
103968 */
103969 SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
103970   Parse *pParse;
103971
103972   int rc = SQLITE_OK;
103973   Table *pTab;
103974   char *zErr = 0;
103975
103976   sqlite3_mutex_enter(db->mutex);
103977   if( !db->pVtabCtx || !(pTab = db->pVtabCtx->pTab) ){
103978     sqlite3Error(db, SQLITE_MISUSE, 0);
103979     sqlite3_mutex_leave(db->mutex);
103980     return SQLITE_MISUSE_BKPT;
103981   }
103982   assert( (pTab->tabFlags & TF_Virtual)!=0 );
103983
103984   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
103985   if( pParse==0 ){
103986     rc = SQLITE_NOMEM;
103987   }else{
103988     pParse->declareVtab = 1;
103989     pParse->db = db;
103990     pParse->nQueryLoop = 1;
103991   
103992     if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr) 
103993      && pParse->pNewTable
103994      && !db->mallocFailed
103995      && !pParse->pNewTable->pSelect
103996      && (pParse->pNewTable->tabFlags & TF_Virtual)==0
103997     ){
103998       if( !pTab->aCol ){
103999         pTab->aCol = pParse->pNewTable->aCol;
104000         pTab->nCol = pParse->pNewTable->nCol;
104001         pParse->pNewTable->nCol = 0;
104002         pParse->pNewTable->aCol = 0;
104003       }
104004       db->pVtabCtx->pTab = 0;
104005     }else{
104006       sqlite3Error(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
104007       sqlite3DbFree(db, zErr);
104008       rc = SQLITE_ERROR;
104009     }
104010     pParse->declareVtab = 0;
104011   
104012     if( pParse->pVdbe ){
104013       sqlite3VdbeFinalize(pParse->pVdbe);
104014     }
104015     sqlite3DeleteTable(db, pParse->pNewTable);
104016     sqlite3StackFree(db, pParse);
104017   }
104018
104019   assert( (rc&0xff)==rc );
104020   rc = sqlite3ApiExit(db, rc);
104021   sqlite3_mutex_leave(db->mutex);
104022   return rc;
104023 }
104024
104025 /*
104026 ** This function is invoked by the vdbe to call the xDestroy method
104027 ** of the virtual table named zTab in database iDb. This occurs
104028 ** when a DROP TABLE is mentioned.
104029 **
104030 ** This call is a no-op if zTab is not a virtual table.
104031 */
104032 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
104033   int rc = SQLITE_OK;
104034   Table *pTab;
104035
104036   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
104037   if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
104038     VTable *p = vtabDisconnectAll(db, pTab);
104039
104040     assert( rc==SQLITE_OK );
104041     rc = p->pMod->pModule->xDestroy(p->pVtab);
104042
104043     /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
104044     if( rc==SQLITE_OK ){
104045       assert( pTab->pVTable==p && p->pNext==0 );
104046       p->pVtab = 0;
104047       pTab->pVTable = 0;
104048       sqlite3VtabUnlock(p);
104049     }
104050   }
104051
104052   return rc;
104053 }
104054
104055 /*
104056 ** This function invokes either the xRollback or xCommit method
104057 ** of each of the virtual tables in the sqlite3.aVTrans array. The method
104058 ** called is identified by the second argument, "offset", which is
104059 ** the offset of the method to call in the sqlite3_module structure.
104060 **
104061 ** The array is cleared after invoking the callbacks. 
104062 */
104063 static void callFinaliser(sqlite3 *db, int offset){
104064   int i;
104065   if( db->aVTrans ){
104066     for(i=0; i<db->nVTrans; i++){
104067       VTable *pVTab = db->aVTrans[i];
104068       sqlite3_vtab *p = pVTab->pVtab;
104069       if( p ){
104070         int (*x)(sqlite3_vtab *);
104071         x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
104072         if( x ) x(p);
104073       }
104074       pVTab->iSavepoint = 0;
104075       sqlite3VtabUnlock(pVTab);
104076     }
104077     sqlite3DbFree(db, db->aVTrans);
104078     db->nVTrans = 0;
104079     db->aVTrans = 0;
104080   }
104081 }
104082
104083 /*
104084 ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
104085 ** array. Return the error code for the first error that occurs, or
104086 ** SQLITE_OK if all xSync operations are successful.
104087 **
104088 ** Set *pzErrmsg to point to a buffer that should be released using 
104089 ** sqlite3DbFree() containing an error message, if one is available.
104090 */
104091 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **pzErrmsg){
104092   int i;
104093   int rc = SQLITE_OK;
104094   VTable **aVTrans = db->aVTrans;
104095
104096   db->aVTrans = 0;
104097   for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
104098     int (*x)(sqlite3_vtab *);
104099     sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
104100     if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
104101       rc = x(pVtab);
104102       sqlite3DbFree(db, *pzErrmsg);
104103       *pzErrmsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
104104       sqlite3_free(pVtab->zErrMsg);
104105     }
104106   }
104107   db->aVTrans = aVTrans;
104108   return rc;
104109 }
104110
104111 /*
104112 ** Invoke the xRollback method of all virtual tables in the 
104113 ** sqlite3.aVTrans array. Then clear the array itself.
104114 */
104115 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
104116   callFinaliser(db, offsetof(sqlite3_module,xRollback));
104117   return SQLITE_OK;
104118 }
104119
104120 /*
104121 ** Invoke the xCommit method of all virtual tables in the 
104122 ** sqlite3.aVTrans array. Then clear the array itself.
104123 */
104124 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
104125   callFinaliser(db, offsetof(sqlite3_module,xCommit));
104126   return SQLITE_OK;
104127 }
104128
104129 /*
104130 ** If the virtual table pVtab supports the transaction interface
104131 ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
104132 ** not currently open, invoke the xBegin method now.
104133 **
104134 ** If the xBegin call is successful, place the sqlite3_vtab pointer
104135 ** in the sqlite3.aVTrans array.
104136 */
104137 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
104138   int rc = SQLITE_OK;
104139   const sqlite3_module *pModule;
104140
104141   /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
104142   ** than zero, then this function is being called from within a
104143   ** virtual module xSync() callback. It is illegal to write to 
104144   ** virtual module tables in this case, so return SQLITE_LOCKED.
104145   */
104146   if( sqlite3VtabInSync(db) ){
104147     return SQLITE_LOCKED;
104148   }
104149   if( !pVTab ){
104150     return SQLITE_OK;
104151   } 
104152   pModule = pVTab->pVtab->pModule;
104153
104154   if( pModule->xBegin ){
104155     int i;
104156
104157     /* If pVtab is already in the aVTrans array, return early */
104158     for(i=0; i<db->nVTrans; i++){
104159       if( db->aVTrans[i]==pVTab ){
104160         return SQLITE_OK;
104161       }
104162     }
104163
104164     /* Invoke the xBegin method. If successful, add the vtab to the 
104165     ** sqlite3.aVTrans[] array. */
104166     rc = growVTrans(db);
104167     if( rc==SQLITE_OK ){
104168       rc = pModule->xBegin(pVTab->pVtab);
104169       if( rc==SQLITE_OK ){
104170         addToVTrans(db, pVTab);
104171       }
104172     }
104173   }
104174   return rc;
104175 }
104176
104177 /*
104178 ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
104179 ** virtual tables that currently have an open transaction. Pass iSavepoint
104180 ** as the second argument to the virtual table method invoked.
104181 **
104182 ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
104183 ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is 
104184 ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
104185 ** an open transaction is invoked.
104186 **
104187 ** If any virtual table method returns an error code other than SQLITE_OK, 
104188 ** processing is abandoned and the error returned to the caller of this
104189 ** function immediately. If all calls to virtual table methods are successful,
104190 ** SQLITE_OK is returned.
104191 */
104192 SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
104193   int rc = SQLITE_OK;
104194
104195   assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
104196   assert( iSavepoint>=0 );
104197   if( db->aVTrans ){
104198     int i;
104199     for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
104200       VTable *pVTab = db->aVTrans[i];
104201       const sqlite3_module *pMod = pVTab->pMod->pModule;
104202       if( pVTab->pVtab && pMod->iVersion>=2 ){
104203         int (*xMethod)(sqlite3_vtab *, int);
104204         switch( op ){
104205           case SAVEPOINT_BEGIN:
104206             xMethod = pMod->xSavepoint;
104207             pVTab->iSavepoint = iSavepoint+1;
104208             break;
104209           case SAVEPOINT_ROLLBACK:
104210             xMethod = pMod->xRollbackTo;
104211             break;
104212           default:
104213             xMethod = pMod->xRelease;
104214             break;
104215         }
104216         if( xMethod && pVTab->iSavepoint>iSavepoint ){
104217           rc = xMethod(pVTab->pVtab, iSavepoint);
104218         }
104219       }
104220     }
104221   }
104222   return rc;
104223 }
104224
104225 /*
104226 ** The first parameter (pDef) is a function implementation.  The
104227 ** second parameter (pExpr) is the first argument to this function.
104228 ** If pExpr is a column in a virtual table, then let the virtual
104229 ** table implementation have an opportunity to overload the function.
104230 **
104231 ** This routine is used to allow virtual table implementations to
104232 ** overload MATCH, LIKE, GLOB, and REGEXP operators.
104233 **
104234 ** Return either the pDef argument (indicating no change) or a 
104235 ** new FuncDef structure that is marked as ephemeral using the
104236 ** SQLITE_FUNC_EPHEM flag.
104237 */
104238 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
104239   sqlite3 *db,    /* Database connection for reporting malloc problems */
104240   FuncDef *pDef,  /* Function to possibly overload */
104241   int nArg,       /* Number of arguments to the function */
104242   Expr *pExpr     /* First argument to the function */
104243 ){
104244   Table *pTab;
104245   sqlite3_vtab *pVtab;
104246   sqlite3_module *pMod;
104247   void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
104248   void *pArg = 0;
104249   FuncDef *pNew;
104250   int rc = 0;
104251   char *zLowerName;
104252   unsigned char *z;
104253
104254
104255   /* Check to see the left operand is a column in a virtual table */
104256   if( NEVER(pExpr==0) ) return pDef;
104257   if( pExpr->op!=TK_COLUMN ) return pDef;
104258   pTab = pExpr->pTab;
104259   if( NEVER(pTab==0) ) return pDef;
104260   if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
104261   pVtab = sqlite3GetVTable(db, pTab)->pVtab;
104262   assert( pVtab!=0 );
104263   assert( pVtab->pModule!=0 );
104264   pMod = (sqlite3_module *)pVtab->pModule;
104265   if( pMod->xFindFunction==0 ) return pDef;
104266  
104267   /* Call the xFindFunction method on the virtual table implementation
104268   ** to see if the implementation wants to overload this function 
104269   */
104270   zLowerName = sqlite3DbStrDup(db, pDef->zName);
104271   if( zLowerName ){
104272     for(z=(unsigned char*)zLowerName; *z; z++){
104273       *z = sqlite3UpperToLower[*z];
104274     }
104275     rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
104276     sqlite3DbFree(db, zLowerName);
104277   }
104278   if( rc==0 ){
104279     return pDef;
104280   }
104281
104282   /* Create a new ephemeral function definition for the overloaded
104283   ** function */
104284   pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
104285                              + sqlite3Strlen30(pDef->zName) + 1);
104286   if( pNew==0 ){
104287     return pDef;
104288   }
104289   *pNew = *pDef;
104290   pNew->zName = (char *)&pNew[1];
104291   memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
104292   pNew->xFunc = xFunc;
104293   pNew->pUserData = pArg;
104294   pNew->flags |= SQLITE_FUNC_EPHEM;
104295   return pNew;
104296 }
104297
104298 /*
104299 ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
104300 ** array so that an OP_VBegin will get generated for it.  Add pTab to the
104301 ** array if it is missing.  If pTab is already in the array, this routine
104302 ** is a no-op.
104303 */
104304 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
104305   Parse *pToplevel = sqlite3ParseToplevel(pParse);
104306   int i, n;
104307   Table **apVtabLock;
104308
104309   assert( IsVirtual(pTab) );
104310   for(i=0; i<pToplevel->nVtabLock; i++){
104311     if( pTab==pToplevel->apVtabLock[i] ) return;
104312   }
104313   n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
104314   apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
104315   if( apVtabLock ){
104316     pToplevel->apVtabLock = apVtabLock;
104317     pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
104318   }else{
104319     pToplevel->db->mallocFailed = 1;
104320   }
104321 }
104322
104323 /*
104324 ** Return the ON CONFLICT resolution mode in effect for the virtual
104325 ** table update operation currently in progress.
104326 **
104327 ** The results of this routine are undefined unless it is called from
104328 ** within an xUpdate method.
104329 */
104330 SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
104331   static const unsigned char aMap[] = { 
104332     SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE 
104333   };
104334   assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
104335   assert( OE_Ignore==4 && OE_Replace==5 );
104336   assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
104337   return (int)aMap[db->vtabOnConflict-1];
104338 }
104339
104340 /*
104341 ** Call from within the xCreate() or xConnect() methods to provide 
104342 ** the SQLite core with additional information about the behavior
104343 ** of the virtual table being implemented.
104344 */
104345 SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
104346   va_list ap;
104347   int rc = SQLITE_OK;
104348
104349   sqlite3_mutex_enter(db->mutex);
104350
104351   va_start(ap, op);
104352   switch( op ){
104353     case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
104354       VtabCtx *p = db->pVtabCtx;
104355       if( !p ){
104356         rc = SQLITE_MISUSE_BKPT;
104357       }else{
104358         assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );
104359         p->pVTable->bConstraint = (u8)va_arg(ap, int);
104360       }
104361       break;
104362     }
104363     default:
104364       rc = SQLITE_MISUSE_BKPT;
104365       break;
104366   }
104367   va_end(ap);
104368
104369   if( rc!=SQLITE_OK ) sqlite3Error(db, rc, 0);
104370   sqlite3_mutex_leave(db->mutex);
104371   return rc;
104372 }
104373
104374 #endif /* SQLITE_OMIT_VIRTUALTABLE */
104375
104376 /************** End of vtab.c ************************************************/
104377 /************** Begin file where.c *******************************************/
104378 /*
104379 ** 2001 September 15
104380 **
104381 ** The author disclaims copyright to this source code.  In place of
104382 ** a legal notice, here is a blessing:
104383 **
104384 **    May you do good and not evil.
104385 **    May you find forgiveness for yourself and forgive others.
104386 **    May you share freely, never taking more than you give.
104387 **
104388 *************************************************************************
104389 ** This module contains C code that generates VDBE code used to process
104390 ** the WHERE clause of SQL statements.  This module is responsible for
104391 ** generating the code that loops through a table looking for applicable
104392 ** rows.  Indices are selected and used to speed the search when doing
104393 ** so is applicable.  Because this module is responsible for selecting
104394 ** indices, you might also think of this module as the "query optimizer".
104395 */
104396
104397
104398 /*
104399 ** Trace output macros
104400 */
104401 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
104402 /***/ int sqlite3WhereTrace = 0;
104403 #endif
104404 #if defined(SQLITE_DEBUG) \
104405     && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
104406 # define WHERETRACE(X)  if(sqlite3WhereTrace) sqlite3DebugPrintf X
104407 #else
104408 # define WHERETRACE(X)
104409 #endif
104410
104411 /* Forward reference
104412 */
104413 typedef struct WhereClause WhereClause;
104414 typedef struct WhereMaskSet WhereMaskSet;
104415 typedef struct WhereOrInfo WhereOrInfo;
104416 typedef struct WhereAndInfo WhereAndInfo;
104417 typedef struct WhereCost WhereCost;
104418
104419 /*
104420 ** The query generator uses an array of instances of this structure to
104421 ** help it analyze the subexpressions of the WHERE clause.  Each WHERE
104422 ** clause subexpression is separated from the others by AND operators,
104423 ** usually, or sometimes subexpressions separated by OR.
104424 **
104425 ** All WhereTerms are collected into a single WhereClause structure.  
104426 ** The following identity holds:
104427 **
104428 **        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
104429 **
104430 ** When a term is of the form:
104431 **
104432 **              X <op> <expr>
104433 **
104434 ** where X is a column name and <op> is one of certain operators,
104435 ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
104436 ** cursor number and column number for X.  WhereTerm.eOperator records
104437 ** the <op> using a bitmask encoding defined by WO_xxx below.  The
104438 ** use of a bitmask encoding for the operator allows us to search
104439 ** quickly for terms that match any of several different operators.
104440 **
104441 ** A WhereTerm might also be two or more subterms connected by OR:
104442 **
104443 **         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
104444 **
104445 ** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
104446 ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
104447 ** is collected about the
104448 **
104449 ** If a term in the WHERE clause does not match either of the two previous
104450 ** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
104451 ** to the original subexpression content and wtFlags is set up appropriately
104452 ** but no other fields in the WhereTerm object are meaningful.
104453 **
104454 ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
104455 ** but they do so indirectly.  A single WhereMaskSet structure translates
104456 ** cursor number into bits and the translated bit is stored in the prereq
104457 ** fields.  The translation is used in order to maximize the number of
104458 ** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
104459 ** spread out over the non-negative integers.  For example, the cursor
104460 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
104461 ** translates these sparse cursor numbers into consecutive integers
104462 ** beginning with 0 in order to make the best possible use of the available
104463 ** bits in the Bitmask.  So, in the example above, the cursor numbers
104464 ** would be mapped into integers 0 through 7.
104465 **
104466 ** The number of terms in a join is limited by the number of bits
104467 ** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
104468 ** is only able to process joins with 64 or fewer tables.
104469 */
104470 typedef struct WhereTerm WhereTerm;
104471 struct WhereTerm {
104472   Expr *pExpr;            /* Pointer to the subexpression that is this term */
104473   int iParent;            /* Disable pWC->a[iParent] when this term disabled */
104474   int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
104475   union {
104476     int leftColumn;         /* Column number of X in "X <op> <expr>" */
104477     WhereOrInfo *pOrInfo;   /* Extra information if (eOperator & WO_OR)!=0 */
104478     WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
104479   } u;
104480   u16 eOperator;          /* A WO_xx value describing <op> */
104481   u8 wtFlags;             /* TERM_xxx bit flags.  See below */
104482   u8 nChild;              /* Number of children that must disable us */
104483   WhereClause *pWC;       /* The clause this term is part of */
104484   Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
104485   Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
104486 };
104487
104488 /*
104489 ** Allowed values of WhereTerm.wtFlags
104490 */
104491 #define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
104492 #define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
104493 #define TERM_CODED      0x04   /* This term is already coded */
104494 #define TERM_COPIED     0x08   /* Has a child */
104495 #define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
104496 #define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
104497 #define TERM_OR_OK      0x40   /* Used during OR-clause processing */
104498 #ifdef SQLITE_ENABLE_STAT3
104499 #  define TERM_VNULL    0x80   /* Manufactured x>NULL or x<=NULL term */
104500 #else
104501 #  define TERM_VNULL    0x00   /* Disabled if not using stat3 */
104502 #endif
104503
104504 /*
104505 ** An instance of the following structure holds all information about a
104506 ** WHERE clause.  Mostly this is a container for one or more WhereTerms.
104507 **
104508 ** Explanation of pOuter:  For a WHERE clause of the form
104509 **
104510 **           a AND ((b AND c) OR (d AND e)) AND f
104511 **
104512 ** There are separate WhereClause objects for the whole clause and for
104513 ** the subclauses "(b AND c)" and "(d AND e)".  The pOuter field of the
104514 ** subclauses points to the WhereClause object for the whole clause.
104515 */
104516 struct WhereClause {
104517   Parse *pParse;           /* The parser context */
104518   WhereMaskSet *pMaskSet;  /* Mapping of table cursor numbers to bitmasks */
104519   WhereClause *pOuter;     /* Outer conjunction */
104520   u8 op;                   /* Split operator.  TK_AND or TK_OR */
104521   u16 wctrlFlags;          /* Might include WHERE_AND_ONLY */
104522   int nTerm;               /* Number of terms */
104523   int nSlot;               /* Number of entries in a[] */
104524   WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
104525 #if defined(SQLITE_SMALL_STACK)
104526   WhereTerm aStatic[1];    /* Initial static space for a[] */
104527 #else
104528   WhereTerm aStatic[8];    /* Initial static space for a[] */
104529 #endif
104530 };
104531
104532 /*
104533 ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
104534 ** a dynamically allocated instance of the following structure.
104535 */
104536 struct WhereOrInfo {
104537   WhereClause wc;          /* Decomposition into subterms */
104538   Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
104539 };
104540
104541 /*
104542 ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
104543 ** a dynamically allocated instance of the following structure.
104544 */
104545 struct WhereAndInfo {
104546   WhereClause wc;          /* The subexpression broken out */
104547 };
104548
104549 /*
104550 ** An instance of the following structure keeps track of a mapping
104551 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
104552 **
104553 ** The VDBE cursor numbers are small integers contained in 
104554 ** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE 
104555 ** clause, the cursor numbers might not begin with 0 and they might
104556 ** contain gaps in the numbering sequence.  But we want to make maximum
104557 ** use of the bits in our bitmasks.  This structure provides a mapping
104558 ** from the sparse cursor numbers into consecutive integers beginning
104559 ** with 0.
104560 **
104561 ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
104562 ** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
104563 **
104564 ** For example, if the WHERE clause expression used these VDBE
104565 ** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
104566 ** would map those cursor numbers into bits 0 through 5.
104567 **
104568 ** Note that the mapping is not necessarily ordered.  In the example
104569 ** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
104570 ** 57->5, 73->4.  Or one of 719 other combinations might be used. It
104571 ** does not really matter.  What is important is that sparse cursor
104572 ** numbers all get mapped into bit numbers that begin with 0 and contain
104573 ** no gaps.
104574 */
104575 struct WhereMaskSet {
104576   int n;                        /* Number of assigned cursor values */
104577   int ix[BMS];                  /* Cursor assigned to each bit */
104578 };
104579
104580 /*
104581 ** A WhereCost object records a lookup strategy and the estimated
104582 ** cost of pursuing that strategy.
104583 */
104584 struct WhereCost {
104585   WherePlan plan;    /* The lookup strategy */
104586   double rCost;      /* Overall cost of pursuing this search strategy */
104587   Bitmask used;      /* Bitmask of cursors used by this plan */
104588 };
104589
104590 /*
104591 ** Bitmasks for the operators that indices are able to exploit.  An
104592 ** OR-ed combination of these values can be used when searching for
104593 ** terms in the where clause.
104594 */
104595 #define WO_IN     0x001
104596 #define WO_EQ     0x002
104597 #define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
104598 #define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
104599 #define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
104600 #define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
104601 #define WO_MATCH  0x040
104602 #define WO_ISNULL 0x080
104603 #define WO_OR     0x100       /* Two or more OR-connected terms */
104604 #define WO_AND    0x200       /* Two or more AND-connected terms */
104605 #define WO_EQUIV  0x400       /* Of the form A==B, both columns */
104606 #define WO_NOOP   0x800       /* This term does not restrict search space */
104607
104608 #define WO_ALL    0xfff       /* Mask of all possible WO_* values */
104609 #define WO_SINGLE 0x0ff       /* Mask of all non-compound WO_* values */
104610
104611 /*
104612 ** Value for wsFlags returned by bestIndex() and stored in
104613 ** WhereLevel.wsFlags.  These flags determine which search
104614 ** strategies are appropriate.
104615 **
104616 ** The least significant 12 bits is reserved as a mask for WO_ values above.
104617 ** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
104618 ** But if the table is the right table of a left join, WhereLevel.wsFlags
104619 ** is set to WO_IN|WO_EQ.  The WhereLevel.wsFlags field can then be used as
104620 ** the "op" parameter to findTerm when we are resolving equality constraints.
104621 ** ISNULL constraints will then not be used on the right table of a left
104622 ** join.  Tickets #2177 and #2189.
104623 */
104624 #define WHERE_ROWID_EQ     0x00001000  /* rowid=EXPR or rowid IN (...) */
104625 #define WHERE_ROWID_RANGE  0x00002000  /* rowid<EXPR and/or rowid>EXPR */
104626 #define WHERE_COLUMN_EQ    0x00010000  /* x=EXPR or x IN (...) or x IS NULL */
104627 #define WHERE_COLUMN_RANGE 0x00020000  /* x<EXPR and/or x>EXPR */
104628 #define WHERE_COLUMN_IN    0x00040000  /* x IN (...) */
104629 #define WHERE_COLUMN_NULL  0x00080000  /* x IS NULL */
104630 #define WHERE_INDEXED      0x000f0000  /* Anything that uses an index */
104631 #define WHERE_NOT_FULLSCAN 0x100f3000  /* Does not do a full table scan */
104632 #define WHERE_IN_ABLE      0x080f1000  /* Able to support an IN operator */
104633 #define WHERE_TOP_LIMIT    0x00100000  /* x<EXPR or x<=EXPR constraint */
104634 #define WHERE_BTM_LIMIT    0x00200000  /* x>EXPR or x>=EXPR constraint */
104635 #define WHERE_BOTH_LIMIT   0x00300000  /* Both x>EXPR and x<EXPR */
104636 #define WHERE_IDX_ONLY     0x00400000  /* Use index only - omit table */
104637 #define WHERE_ORDERED      0x00800000  /* Output will appear in correct order */
104638 #define WHERE_REVERSE      0x01000000  /* Scan in reverse order */
104639 #define WHERE_UNIQUE       0x02000000  /* Selects no more than one row */
104640 #define WHERE_ALL_UNIQUE   0x04000000  /* This and all prior have one row */
104641 #define WHERE_OB_UNIQUE    0x00004000  /* Values in ORDER BY columns are 
104642                                        ** different for every output row */
104643 #define WHERE_VIRTUALTABLE 0x08000000  /* Use virtual-table processing */
104644 #define WHERE_MULTI_OR     0x10000000  /* OR using multiple indices */
104645 #define WHERE_TEMP_INDEX   0x20000000  /* Uses an ephemeral index */
104646 #define WHERE_DISTINCT     0x40000000  /* Correct order for DISTINCT */
104647 #define WHERE_COVER_SCAN   0x80000000  /* Full scan of a covering index */
104648
104649 /*
104650 ** This module contains many separate subroutines that work together to
104651 ** find the best indices to use for accessing a particular table in a query.
104652 ** An instance of the following structure holds context information about the
104653 ** index search so that it can be more easily passed between the various
104654 ** routines.
104655 */
104656 typedef struct WhereBestIdx WhereBestIdx;
104657 struct WhereBestIdx {
104658   Parse *pParse;                  /* Parser context */
104659   WhereClause *pWC;               /* The WHERE clause */
104660   struct SrcList_item *pSrc;      /* The FROM clause term to search */
104661   Bitmask notReady;               /* Mask of cursors not available */
104662   Bitmask notValid;               /* Cursors not available for any purpose */
104663   ExprList *pOrderBy;             /* The ORDER BY clause */
104664   ExprList *pDistinct;            /* The select-list if query is DISTINCT */
104665   sqlite3_index_info **ppIdxInfo; /* Index information passed to xBestIndex */
104666   int i, n;                       /* Which loop is being coded; # of loops */
104667   WhereLevel *aLevel;             /* Info about outer loops */
104668   WhereCost cost;                 /* Lowest cost query plan */
104669 };
104670
104671 /*
104672 ** Return TRUE if the probe cost is less than the baseline cost
104673 */
104674 static int compareCost(const WhereCost *pProbe, const WhereCost *pBaseline){
104675   if( pProbe->rCost<pBaseline->rCost ) return 1;
104676   if( pProbe->rCost>pBaseline->rCost ) return 0;
104677   if( pProbe->plan.nOBSat>pBaseline->plan.nOBSat ) return 1;
104678   if( pProbe->plan.nRow<pBaseline->plan.nRow ) return 1;
104679   return 0;
104680 }
104681
104682 /*
104683 ** Initialize a preallocated WhereClause structure.
104684 */
104685 static void whereClauseInit(
104686   WhereClause *pWC,        /* The WhereClause to be initialized */
104687   Parse *pParse,           /* The parsing context */
104688   WhereMaskSet *pMaskSet,  /* Mapping from table cursor numbers to bitmasks */
104689   u16 wctrlFlags           /* Might include WHERE_AND_ONLY */
104690 ){
104691   pWC->pParse = pParse;
104692   pWC->pMaskSet = pMaskSet;
104693   pWC->pOuter = 0;
104694   pWC->nTerm = 0;
104695   pWC->nSlot = ArraySize(pWC->aStatic);
104696   pWC->a = pWC->aStatic;
104697   pWC->wctrlFlags = wctrlFlags;
104698 }
104699
104700 /* Forward reference */
104701 static void whereClauseClear(WhereClause*);
104702
104703 /*
104704 ** Deallocate all memory associated with a WhereOrInfo object.
104705 */
104706 static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
104707   whereClauseClear(&p->wc);
104708   sqlite3DbFree(db, p);
104709 }
104710
104711 /*
104712 ** Deallocate all memory associated with a WhereAndInfo object.
104713 */
104714 static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
104715   whereClauseClear(&p->wc);
104716   sqlite3DbFree(db, p);
104717 }
104718
104719 /*
104720 ** Deallocate a WhereClause structure.  The WhereClause structure
104721 ** itself is not freed.  This routine is the inverse of whereClauseInit().
104722 */
104723 static void whereClauseClear(WhereClause *pWC){
104724   int i;
104725   WhereTerm *a;
104726   sqlite3 *db = pWC->pParse->db;
104727   for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
104728     if( a->wtFlags & TERM_DYNAMIC ){
104729       sqlite3ExprDelete(db, a->pExpr);
104730     }
104731     if( a->wtFlags & TERM_ORINFO ){
104732       whereOrInfoDelete(db, a->u.pOrInfo);
104733     }else if( a->wtFlags & TERM_ANDINFO ){
104734       whereAndInfoDelete(db, a->u.pAndInfo);
104735     }
104736   }
104737   if( pWC->a!=pWC->aStatic ){
104738     sqlite3DbFree(db, pWC->a);
104739   }
104740 }
104741
104742 /*
104743 ** Add a single new WhereTerm entry to the WhereClause object pWC.
104744 ** The new WhereTerm object is constructed from Expr p and with wtFlags.
104745 ** The index in pWC->a[] of the new WhereTerm is returned on success.
104746 ** 0 is returned if the new WhereTerm could not be added due to a memory
104747 ** allocation error.  The memory allocation failure will be recorded in
104748 ** the db->mallocFailed flag so that higher-level functions can detect it.
104749 **
104750 ** This routine will increase the size of the pWC->a[] array as necessary.
104751 **
104752 ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
104753 ** for freeing the expression p is assumed by the WhereClause object pWC.
104754 ** This is true even if this routine fails to allocate a new WhereTerm.
104755 **
104756 ** WARNING:  This routine might reallocate the space used to store
104757 ** WhereTerms.  All pointers to WhereTerms should be invalidated after
104758 ** calling this routine.  Such pointers may be reinitialized by referencing
104759 ** the pWC->a[] array.
104760 */
104761 static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
104762   WhereTerm *pTerm;
104763   int idx;
104764   testcase( wtFlags & TERM_VIRTUAL );  /* EV: R-00211-15100 */
104765   if( pWC->nTerm>=pWC->nSlot ){
104766     WhereTerm *pOld = pWC->a;
104767     sqlite3 *db = pWC->pParse->db;
104768     pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
104769     if( pWC->a==0 ){
104770       if( wtFlags & TERM_DYNAMIC ){
104771         sqlite3ExprDelete(db, p);
104772       }
104773       pWC->a = pOld;
104774       return 0;
104775     }
104776     memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
104777     if( pOld!=pWC->aStatic ){
104778       sqlite3DbFree(db, pOld);
104779     }
104780     pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
104781   }
104782   pTerm = &pWC->a[idx = pWC->nTerm++];
104783   pTerm->pExpr = sqlite3ExprSkipCollate(p);
104784   pTerm->wtFlags = wtFlags;
104785   pTerm->pWC = pWC;
104786   pTerm->iParent = -1;
104787   return idx;
104788 }
104789
104790 /*
104791 ** This routine identifies subexpressions in the WHERE clause where
104792 ** each subexpression is separated by the AND operator or some other
104793 ** operator specified in the op parameter.  The WhereClause structure
104794 ** is filled with pointers to subexpressions.  For example:
104795 **
104796 **    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
104797 **           \________/     \_______________/     \________________/
104798 **            slot[0]            slot[1]               slot[2]
104799 **
104800 ** The original WHERE clause in pExpr is unaltered.  All this routine
104801 ** does is make slot[] entries point to substructure within pExpr.
104802 **
104803 ** In the previous sentence and in the diagram, "slot[]" refers to
104804 ** the WhereClause.a[] array.  The slot[] array grows as needed to contain
104805 ** all terms of the WHERE clause.
104806 */
104807 static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
104808   pWC->op = (u8)op;
104809   if( pExpr==0 ) return;
104810   if( pExpr->op!=op ){
104811     whereClauseInsert(pWC, pExpr, 0);
104812   }else{
104813     whereSplit(pWC, pExpr->pLeft, op);
104814     whereSplit(pWC, pExpr->pRight, op);
104815   }
104816 }
104817
104818 /*
104819 ** Initialize an expression mask set (a WhereMaskSet object)
104820 */
104821 #define initMaskSet(P)  memset(P, 0, sizeof(*P))
104822
104823 /*
104824 ** Return the bitmask for the given cursor number.  Return 0 if
104825 ** iCursor is not in the set.
104826 */
104827 static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
104828   int i;
104829   assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
104830   for(i=0; i<pMaskSet->n; i++){
104831     if( pMaskSet->ix[i]==iCursor ){
104832       return ((Bitmask)1)<<i;
104833     }
104834   }
104835   return 0;
104836 }
104837
104838 /*
104839 ** Create a new mask for cursor iCursor.
104840 **
104841 ** There is one cursor per table in the FROM clause.  The number of
104842 ** tables in the FROM clause is limited by a test early in the
104843 ** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
104844 ** array will never overflow.
104845 */
104846 static void createMask(WhereMaskSet *pMaskSet, int iCursor){
104847   assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
104848   pMaskSet->ix[pMaskSet->n++] = iCursor;
104849 }
104850
104851 /*
104852 ** This routine walks (recursively) an expression tree and generates
104853 ** a bitmask indicating which tables are used in that expression
104854 ** tree.
104855 **
104856 ** In order for this routine to work, the calling function must have
104857 ** previously invoked sqlite3ResolveExprNames() on the expression.  See
104858 ** the header comment on that routine for additional information.
104859 ** The sqlite3ResolveExprNames() routines looks for column names and
104860 ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
104861 ** the VDBE cursor number of the table.  This routine just has to
104862 ** translate the cursor numbers into bitmask values and OR all
104863 ** the bitmasks together.
104864 */
104865 static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
104866 static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
104867 static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
104868   Bitmask mask = 0;
104869   if( p==0 ) return 0;
104870   if( p->op==TK_COLUMN ){
104871     mask = getMask(pMaskSet, p->iTable);
104872     return mask;
104873   }
104874   mask = exprTableUsage(pMaskSet, p->pRight);
104875   mask |= exprTableUsage(pMaskSet, p->pLeft);
104876   if( ExprHasProperty(p, EP_xIsSelect) ){
104877     mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
104878   }else{
104879     mask |= exprListTableUsage(pMaskSet, p->x.pList);
104880   }
104881   return mask;
104882 }
104883 static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
104884   int i;
104885   Bitmask mask = 0;
104886   if( pList ){
104887     for(i=0; i<pList->nExpr; i++){
104888       mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
104889     }
104890   }
104891   return mask;
104892 }
104893 static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
104894   Bitmask mask = 0;
104895   while( pS ){
104896     SrcList *pSrc = pS->pSrc;
104897     mask |= exprListTableUsage(pMaskSet, pS->pEList);
104898     mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
104899     mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
104900     mask |= exprTableUsage(pMaskSet, pS->pWhere);
104901     mask |= exprTableUsage(pMaskSet, pS->pHaving);
104902     if( ALWAYS(pSrc!=0) ){
104903       int i;
104904       for(i=0; i<pSrc->nSrc; i++){
104905         mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect);
104906         mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn);
104907       }
104908     }
104909     pS = pS->pPrior;
104910   }
104911   return mask;
104912 }
104913
104914 /*
104915 ** Return TRUE if the given operator is one of the operators that is
104916 ** allowed for an indexable WHERE clause term.  The allowed operators are
104917 ** "=", "<", ">", "<=", ">=", and "IN".
104918 **
104919 ** IMPLEMENTATION-OF: R-59926-26393 To be usable by an index a term must be
104920 ** of one of the following forms: column = expression column > expression
104921 ** column >= expression column < expression column <= expression
104922 ** expression = column expression > column expression >= column
104923 ** expression < column expression <= column column IN
104924 ** (expression-list) column IN (subquery) column IS NULL
104925 */
104926 static int allowedOp(int op){
104927   assert( TK_GT>TK_EQ && TK_GT<TK_GE );
104928   assert( TK_LT>TK_EQ && TK_LT<TK_GE );
104929   assert( TK_LE>TK_EQ && TK_LE<TK_GE );
104930   assert( TK_GE==TK_EQ+4 );
104931   return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
104932 }
104933
104934 /*
104935 ** Swap two objects of type TYPE.
104936 */
104937 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
104938
104939 /*
104940 ** Commute a comparison operator.  Expressions of the form "X op Y"
104941 ** are converted into "Y op X".
104942 **
104943 ** If left/right precedence rules come into play when determining the
104944 ** collating
104945 ** side of the comparison, it remains associated with the same side after
104946 ** the commutation. So "Y collate NOCASE op X" becomes 
104947 ** "X op Y". This is because any collation sequence on
104948 ** the left hand side of a comparison overrides any collation sequence 
104949 ** attached to the right. For the same reason the EP_Collate flag
104950 ** is not commuted.
104951 */
104952 static void exprCommute(Parse *pParse, Expr *pExpr){
104953   u16 expRight = (pExpr->pRight->flags & EP_Collate);
104954   u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
104955   assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
104956   if( expRight==expLeft ){
104957     /* Either X and Y both have COLLATE operator or neither do */
104958     if( expRight ){
104959       /* Both X and Y have COLLATE operators.  Make sure X is always
104960       ** used by clearing the EP_Collate flag from Y. */
104961       pExpr->pRight->flags &= ~EP_Collate;
104962     }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
104963       /* Neither X nor Y have COLLATE operators, but X has a non-default
104964       ** collating sequence.  So add the EP_Collate marker on X to cause
104965       ** it to be searched first. */
104966       pExpr->pLeft->flags |= EP_Collate;
104967     }
104968   }
104969   SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
104970   if( pExpr->op>=TK_GT ){
104971     assert( TK_LT==TK_GT+2 );
104972     assert( TK_GE==TK_LE+2 );
104973     assert( TK_GT>TK_EQ );
104974     assert( TK_GT<TK_LE );
104975     assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
104976     pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
104977   }
104978 }
104979
104980 /*
104981 ** Translate from TK_xx operator to WO_xx bitmask.
104982 */
104983 static u16 operatorMask(int op){
104984   u16 c;
104985   assert( allowedOp(op) );
104986   if( op==TK_IN ){
104987     c = WO_IN;
104988   }else if( op==TK_ISNULL ){
104989     c = WO_ISNULL;
104990   }else{
104991     assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
104992     c = (u16)(WO_EQ<<(op-TK_EQ));
104993   }
104994   assert( op!=TK_ISNULL || c==WO_ISNULL );
104995   assert( op!=TK_IN || c==WO_IN );
104996   assert( op!=TK_EQ || c==WO_EQ );
104997   assert( op!=TK_LT || c==WO_LT );
104998   assert( op!=TK_LE || c==WO_LE );
104999   assert( op!=TK_GT || c==WO_GT );
105000   assert( op!=TK_GE || c==WO_GE );
105001   return c;
105002 }
105003
105004 /*
105005 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
105006 ** where X is a reference to the iColumn of table iCur and <op> is one of
105007 ** the WO_xx operator codes specified by the op parameter.
105008 ** Return a pointer to the term.  Return 0 if not found.
105009 **
105010 ** The term returned might by Y=<expr> if there is another constraint in
105011 ** the WHERE clause that specifies that X=Y.  Any such constraints will be
105012 ** identified by the WO_EQUIV bit in the pTerm->eOperator field.  The
105013 ** aEquiv[] array holds X and all its equivalents, with each SQL variable
105014 ** taking up two slots in aEquiv[].  The first slot is for the cursor number
105015 ** and the second is for the column number.  There are 22 slots in aEquiv[]
105016 ** so that means we can look for X plus up to 10 other equivalent values.
105017 ** Hence a search for X will return <expr> if X=A1 and A1=A2 and A2=A3
105018 ** and ... and A9=A10 and A10=<expr>.
105019 **
105020 ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
105021 ** then try for the one with no dependencies on <expr> - in other words where
105022 ** <expr> is a constant expression of some kind.  Only return entries of
105023 ** the form "X <op> Y" where Y is a column in another table if no terms of
105024 ** the form "X <op> <const-expr>" exist.   If no terms with a constant RHS
105025 ** exist, try to return a term that does not use WO_EQUIV.
105026 */
105027 static WhereTerm *findTerm(
105028   WhereClause *pWC,     /* The WHERE clause to be searched */
105029   int iCur,             /* Cursor number of LHS */
105030   int iColumn,          /* Column number of LHS */
105031   Bitmask notReady,     /* RHS must not overlap with this mask */
105032   u32 op,               /* Mask of WO_xx values describing operator */
105033   Index *pIdx           /* Must be compatible with this index, if not NULL */
105034 ){
105035   WhereTerm *pTerm;            /* Term being examined as possible result */
105036   WhereTerm *pResult = 0;      /* The answer to return */
105037   WhereClause *pWCOrig = pWC;  /* Original pWC value */
105038   int j, k;                    /* Loop counters */
105039   Expr *pX;                /* Pointer to an expression */
105040   Parse *pParse;           /* Parsing context */
105041   int iOrigCol = iColumn;  /* Original value of iColumn */
105042   int nEquiv = 2;          /* Number of entires in aEquiv[] */
105043   int iEquiv = 2;          /* Number of entries of aEquiv[] processed so far */
105044   int aEquiv[22];          /* iCur,iColumn and up to 10 other equivalents */
105045
105046   assert( iCur>=0 );
105047   aEquiv[0] = iCur;
105048   aEquiv[1] = iColumn;
105049   for(;;){
105050     for(pWC=pWCOrig; pWC; pWC=pWC->pOuter){
105051       for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
105052         if( pTerm->leftCursor==iCur
105053           && pTerm->u.leftColumn==iColumn
105054         ){
105055           if( (pTerm->prereqRight & notReady)==0
105056            && (pTerm->eOperator & op & WO_ALL)!=0
105057           ){
105058             if( iOrigCol>=0 && pIdx && (pTerm->eOperator & WO_ISNULL)==0 ){
105059               CollSeq *pColl;
105060               char idxaff;
105061       
105062               pX = pTerm->pExpr;
105063               pParse = pWC->pParse;
105064               idxaff = pIdx->pTable->aCol[iOrigCol].affinity;
105065               if( !sqlite3IndexAffinityOk(pX, idxaff) ){
105066                 continue;
105067               }
105068       
105069               /* Figure out the collation sequence required from an index for
105070               ** it to be useful for optimising expression pX. Store this
105071               ** value in variable pColl.
105072               */
105073               assert(pX->pLeft);
105074               pColl = sqlite3BinaryCompareCollSeq(pParse,pX->pLeft,pX->pRight);
105075               if( pColl==0 ) pColl = pParse->db->pDfltColl;
105076       
105077               for(j=0; pIdx->aiColumn[j]!=iOrigCol; j++){
105078                 if( NEVER(j>=pIdx->nColumn) ) return 0;
105079               }
105080               if( sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ){
105081                 continue;
105082               }
105083             }
105084             if( pTerm->prereqRight==0 && (pTerm->eOperator&WO_EQ)!=0 ){
105085               pResult = pTerm;
105086               goto findTerm_success;
105087             }else if( pResult==0 ){
105088               pResult = pTerm;
105089             }
105090           }
105091           if( (pTerm->eOperator & WO_EQUIV)!=0
105092            && nEquiv<ArraySize(aEquiv)
105093           ){
105094             pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight);
105095             assert( pX->op==TK_COLUMN );
105096             for(j=0; j<nEquiv; j+=2){
105097               if( aEquiv[j]==pX->iTable && aEquiv[j+1]==pX->iColumn ) break;
105098             }
105099             if( j==nEquiv ){
105100               aEquiv[j] = pX->iTable;
105101               aEquiv[j+1] = pX->iColumn;
105102               nEquiv += 2;
105103             }
105104           }
105105         }
105106       }
105107     }
105108     if( iEquiv>=nEquiv ) break;
105109     iCur = aEquiv[iEquiv++];
105110     iColumn = aEquiv[iEquiv++];
105111   }
105112 findTerm_success:
105113   return pResult;
105114 }
105115
105116 /* Forward reference */
105117 static void exprAnalyze(SrcList*, WhereClause*, int);
105118
105119 /*
105120 ** Call exprAnalyze on all terms in a WHERE clause.  
105121 **
105122 **
105123 */
105124 static void exprAnalyzeAll(
105125   SrcList *pTabList,       /* the FROM clause */
105126   WhereClause *pWC         /* the WHERE clause to be analyzed */
105127 ){
105128   int i;
105129   for(i=pWC->nTerm-1; i>=0; i--){
105130     exprAnalyze(pTabList, pWC, i);
105131   }
105132 }
105133
105134 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
105135 /*
105136 ** Check to see if the given expression is a LIKE or GLOB operator that
105137 ** can be optimized using inequality constraints.  Return TRUE if it is
105138 ** so and false if not.
105139 **
105140 ** In order for the operator to be optimizible, the RHS must be a string
105141 ** literal that does not begin with a wildcard.  
105142 */
105143 static int isLikeOrGlob(
105144   Parse *pParse,    /* Parsing and code generating context */
105145   Expr *pExpr,      /* Test this expression */
105146   Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
105147   int *pisComplete, /* True if the only wildcard is % in the last character */
105148   int *pnoCase      /* True if uppercase is equivalent to lowercase */
105149 ){
105150   const char *z = 0;         /* String on RHS of LIKE operator */
105151   Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
105152   ExprList *pList;           /* List of operands to the LIKE operator */
105153   int c;                     /* One character in z[] */
105154   int cnt;                   /* Number of non-wildcard prefix characters */
105155   char wc[3];                /* Wildcard characters */
105156   sqlite3 *db = pParse->db;  /* Database connection */
105157   sqlite3_value *pVal = 0;
105158   int op;                    /* Opcode of pRight */
105159
105160   if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
105161     return 0;
105162   }
105163 #ifdef SQLITE_EBCDIC
105164   if( *pnoCase ) return 0;
105165 #endif
105166   pList = pExpr->x.pList;
105167   pLeft = pList->a[1].pExpr;
105168   if( pLeft->op!=TK_COLUMN 
105169    || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT 
105170    || IsVirtual(pLeft->pTab)
105171   ){
105172     /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
105173     ** be the name of an indexed column with TEXT affinity. */
105174     return 0;
105175   }
105176   assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
105177
105178   pRight = pList->a[0].pExpr;
105179   op = pRight->op;
105180   if( op==TK_REGISTER ){
105181     op = pRight->op2;
105182   }
105183   if( op==TK_VARIABLE ){
105184     Vdbe *pReprepare = pParse->pReprepare;
105185     int iCol = pRight->iColumn;
105186     pVal = sqlite3VdbeGetValue(pReprepare, iCol, SQLITE_AFF_NONE);
105187     if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
105188       z = (char *)sqlite3_value_text(pVal);
105189     }
105190     sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
105191     assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
105192   }else if( op==TK_STRING ){
105193     z = pRight->u.zToken;
105194   }
105195   if( z ){
105196     cnt = 0;
105197     while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
105198       cnt++;
105199     }
105200     if( cnt!=0 && 255!=(u8)z[cnt-1] ){
105201       Expr *pPrefix;
105202       *pisComplete = c==wc[0] && z[cnt+1]==0;
105203       pPrefix = sqlite3Expr(db, TK_STRING, z);
105204       if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
105205       *ppPrefix = pPrefix;
105206       if( op==TK_VARIABLE ){
105207         Vdbe *v = pParse->pVdbe;
105208         sqlite3VdbeSetVarmask(v, pRight->iColumn);
105209         if( *pisComplete && pRight->u.zToken[1] ){
105210           /* If the rhs of the LIKE expression is a variable, and the current
105211           ** value of the variable means there is no need to invoke the LIKE
105212           ** function, then no OP_Variable will be added to the program.
105213           ** This causes problems for the sqlite3_bind_parameter_name()
105214           ** API. To workaround them, add a dummy OP_Variable here.
105215           */ 
105216           int r1 = sqlite3GetTempReg(pParse);
105217           sqlite3ExprCodeTarget(pParse, pRight, r1);
105218           sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
105219           sqlite3ReleaseTempReg(pParse, r1);
105220         }
105221       }
105222     }else{
105223       z = 0;
105224     }
105225   }
105226
105227   sqlite3ValueFree(pVal);
105228   return (z!=0);
105229 }
105230 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
105231
105232
105233 #ifndef SQLITE_OMIT_VIRTUALTABLE
105234 /*
105235 ** Check to see if the given expression is of the form
105236 **
105237 **         column MATCH expr
105238 **
105239 ** If it is then return TRUE.  If not, return FALSE.
105240 */
105241 static int isMatchOfColumn(
105242   Expr *pExpr      /* Test this expression */
105243 ){
105244   ExprList *pList;
105245
105246   if( pExpr->op!=TK_FUNCTION ){
105247     return 0;
105248   }
105249   if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
105250     return 0;
105251   }
105252   pList = pExpr->x.pList;
105253   if( pList->nExpr!=2 ){
105254     return 0;
105255   }
105256   if( pList->a[1].pExpr->op != TK_COLUMN ){
105257     return 0;
105258   }
105259   return 1;
105260 }
105261 #endif /* SQLITE_OMIT_VIRTUALTABLE */
105262
105263 /*
105264 ** If the pBase expression originated in the ON or USING clause of
105265 ** a join, then transfer the appropriate markings over to derived.
105266 */
105267 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
105268   pDerived->flags |= pBase->flags & EP_FromJoin;
105269   pDerived->iRightJoinTable = pBase->iRightJoinTable;
105270 }
105271
105272 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
105273 /*
105274 ** Analyze a term that consists of two or more OR-connected
105275 ** subterms.  So in:
105276 **
105277 **     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
105278 **                          ^^^^^^^^^^^^^^^^^^^^
105279 **
105280 ** This routine analyzes terms such as the middle term in the above example.
105281 ** A WhereOrTerm object is computed and attached to the term under
105282 ** analysis, regardless of the outcome of the analysis.  Hence:
105283 **
105284 **     WhereTerm.wtFlags   |=  TERM_ORINFO
105285 **     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
105286 **
105287 ** The term being analyzed must have two or more of OR-connected subterms.
105288 ** A single subterm might be a set of AND-connected sub-subterms.
105289 ** Examples of terms under analysis:
105290 **
105291 **     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
105292 **     (B)     x=expr1 OR expr2=x OR x=expr3
105293 **     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
105294 **     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
105295 **     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
105296 **
105297 ** CASE 1:
105298 **
105299 ** If all subterms are of the form T.C=expr for some single column of C and
105300 ** a single table T (as shown in example B above) then create a new virtual
105301 ** term that is an equivalent IN expression.  In other words, if the term
105302 ** being analyzed is:
105303 **
105304 **      x = expr1  OR  expr2 = x  OR  x = expr3
105305 **
105306 ** then create a new virtual term like this:
105307 **
105308 **      x IN (expr1,expr2,expr3)
105309 **
105310 ** CASE 2:
105311 **
105312 ** If all subterms are indexable by a single table T, then set
105313 **
105314 **     WhereTerm.eOperator              =  WO_OR
105315 **     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
105316 **
105317 ** A subterm is "indexable" if it is of the form
105318 ** "T.C <op> <expr>" where C is any column of table T and 
105319 ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
105320 ** A subterm is also indexable if it is an AND of two or more
105321 ** subsubterms at least one of which is indexable.  Indexable AND 
105322 ** subterms have their eOperator set to WO_AND and they have
105323 ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
105324 **
105325 ** From another point of view, "indexable" means that the subterm could
105326 ** potentially be used with an index if an appropriate index exists.
105327 ** This analysis does not consider whether or not the index exists; that
105328 ** is something the bestIndex() routine will determine.  This analysis
105329 ** only looks at whether subterms appropriate for indexing exist.
105330 **
105331 ** All examples A through E above all satisfy case 2.  But if a term
105332 ** also statisfies case 1 (such as B) we know that the optimizer will
105333 ** always prefer case 1, so in that case we pretend that case 2 is not
105334 ** satisfied.
105335 **
105336 ** It might be the case that multiple tables are indexable.  For example,
105337 ** (E) above is indexable on tables P, Q, and R.
105338 **
105339 ** Terms that satisfy case 2 are candidates for lookup by using
105340 ** separate indices to find rowids for each subterm and composing
105341 ** the union of all rowids using a RowSet object.  This is similar
105342 ** to "bitmap indices" in other database engines.
105343 **
105344 ** OTHERWISE:
105345 **
105346 ** If neither case 1 nor case 2 apply, then leave the eOperator set to
105347 ** zero.  This term is not useful for search.
105348 */
105349 static void exprAnalyzeOrTerm(
105350   SrcList *pSrc,            /* the FROM clause */
105351   WhereClause *pWC,         /* the complete WHERE clause */
105352   int idxTerm               /* Index of the OR-term to be analyzed */
105353 ){
105354   Parse *pParse = pWC->pParse;            /* Parser context */
105355   sqlite3 *db = pParse->db;               /* Database connection */
105356   WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
105357   Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
105358   WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */
105359   int i;                                  /* Loop counters */
105360   WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
105361   WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
105362   WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
105363   Bitmask chngToIN;         /* Tables that might satisfy case 1 */
105364   Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
105365
105366   /*
105367   ** Break the OR clause into its separate subterms.  The subterms are
105368   ** stored in a WhereClause structure containing within the WhereOrInfo
105369   ** object that is attached to the original OR clause term.
105370   */
105371   assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
105372   assert( pExpr->op==TK_OR );
105373   pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
105374   if( pOrInfo==0 ) return;
105375   pTerm->wtFlags |= TERM_ORINFO;
105376   pOrWc = &pOrInfo->wc;
105377   whereClauseInit(pOrWc, pWC->pParse, pMaskSet, pWC->wctrlFlags);
105378   whereSplit(pOrWc, pExpr, TK_OR);
105379   exprAnalyzeAll(pSrc, pOrWc);
105380   if( db->mallocFailed ) return;
105381   assert( pOrWc->nTerm>=2 );
105382
105383   /*
105384   ** Compute the set of tables that might satisfy cases 1 or 2.
105385   */
105386   indexable = ~(Bitmask)0;
105387   chngToIN = ~(Bitmask)0;
105388   for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
105389     if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
105390       WhereAndInfo *pAndInfo;
105391       assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
105392       chngToIN = 0;
105393       pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
105394       if( pAndInfo ){
105395         WhereClause *pAndWC;
105396         WhereTerm *pAndTerm;
105397         int j;
105398         Bitmask b = 0;
105399         pOrTerm->u.pAndInfo = pAndInfo;
105400         pOrTerm->wtFlags |= TERM_ANDINFO;
105401         pOrTerm->eOperator = WO_AND;
105402         pAndWC = &pAndInfo->wc;
105403         whereClauseInit(pAndWC, pWC->pParse, pMaskSet, pWC->wctrlFlags);
105404         whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
105405         exprAnalyzeAll(pSrc, pAndWC);
105406         pAndWC->pOuter = pWC;
105407         testcase( db->mallocFailed );
105408         if( !db->mallocFailed ){
105409           for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
105410             assert( pAndTerm->pExpr );
105411             if( allowedOp(pAndTerm->pExpr->op) ){
105412               b |= getMask(pMaskSet, pAndTerm->leftCursor);
105413             }
105414           }
105415         }
105416         indexable &= b;
105417       }
105418     }else if( pOrTerm->wtFlags & TERM_COPIED ){
105419       /* Skip this term for now.  We revisit it when we process the
105420       ** corresponding TERM_VIRTUAL term */
105421     }else{
105422       Bitmask b;
105423       b = getMask(pMaskSet, pOrTerm->leftCursor);
105424       if( pOrTerm->wtFlags & TERM_VIRTUAL ){
105425         WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
105426         b |= getMask(pMaskSet, pOther->leftCursor);
105427       }
105428       indexable &= b;
105429       if( (pOrTerm->eOperator & WO_EQ)==0 ){
105430         chngToIN = 0;
105431       }else{
105432         chngToIN &= b;
105433       }
105434     }
105435   }
105436
105437   /*
105438   ** Record the set of tables that satisfy case 2.  The set might be
105439   ** empty.
105440   */
105441   pOrInfo->indexable = indexable;
105442   pTerm->eOperator = indexable==0 ? 0 : WO_OR;
105443
105444   /*
105445   ** chngToIN holds a set of tables that *might* satisfy case 1.  But
105446   ** we have to do some additional checking to see if case 1 really
105447   ** is satisfied.
105448   **
105449   ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
105450   ** that there is no possibility of transforming the OR clause into an
105451   ** IN operator because one or more terms in the OR clause contain
105452   ** something other than == on a column in the single table.  The 1-bit
105453   ** case means that every term of the OR clause is of the form
105454   ** "table.column=expr" for some single table.  The one bit that is set
105455   ** will correspond to the common table.  We still need to check to make
105456   ** sure the same column is used on all terms.  The 2-bit case is when
105457   ** the all terms are of the form "table1.column=table2.column".  It
105458   ** might be possible to form an IN operator with either table1.column
105459   ** or table2.column as the LHS if either is common to every term of
105460   ** the OR clause.
105461   **
105462   ** Note that terms of the form "table.column1=table.column2" (the
105463   ** same table on both sizes of the ==) cannot be optimized.
105464   */
105465   if( chngToIN ){
105466     int okToChngToIN = 0;     /* True if the conversion to IN is valid */
105467     int iColumn = -1;         /* Column index on lhs of IN operator */
105468     int iCursor = -1;         /* Table cursor common to all terms */
105469     int j = 0;                /* Loop counter */
105470
105471     /* Search for a table and column that appears on one side or the
105472     ** other of the == operator in every subterm.  That table and column
105473     ** will be recorded in iCursor and iColumn.  There might not be any
105474     ** such table and column.  Set okToChngToIN if an appropriate table
105475     ** and column is found but leave okToChngToIN false if not found.
105476     */
105477     for(j=0; j<2 && !okToChngToIN; j++){
105478       pOrTerm = pOrWc->a;
105479       for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
105480         assert( pOrTerm->eOperator & WO_EQ );
105481         pOrTerm->wtFlags &= ~TERM_OR_OK;
105482         if( pOrTerm->leftCursor==iCursor ){
105483           /* This is the 2-bit case and we are on the second iteration and
105484           ** current term is from the first iteration.  So skip this term. */
105485           assert( j==1 );
105486           continue;
105487         }
105488         if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ){
105489           /* This term must be of the form t1.a==t2.b where t2 is in the
105490           ** chngToIN set but t1 is not.  This term will be either preceeded
105491           ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term 
105492           ** and use its inversion. */
105493           testcase( pOrTerm->wtFlags & TERM_COPIED );
105494           testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
105495           assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
105496           continue;
105497         }
105498         iColumn = pOrTerm->u.leftColumn;
105499         iCursor = pOrTerm->leftCursor;
105500         break;
105501       }
105502       if( i<0 ){
105503         /* No candidate table+column was found.  This can only occur
105504         ** on the second iteration */
105505         assert( j==1 );
105506         assert( IsPowerOfTwo(chngToIN) );
105507         assert( chngToIN==getMask(pMaskSet, iCursor) );
105508         break;
105509       }
105510       testcase( j==1 );
105511
105512       /* We have found a candidate table and column.  Check to see if that
105513       ** table and column is common to every term in the OR clause */
105514       okToChngToIN = 1;
105515       for(; i>=0 && okToChngToIN; i--, pOrTerm++){
105516         assert( pOrTerm->eOperator & WO_EQ );
105517         if( pOrTerm->leftCursor!=iCursor ){
105518           pOrTerm->wtFlags &= ~TERM_OR_OK;
105519         }else if( pOrTerm->u.leftColumn!=iColumn ){
105520           okToChngToIN = 0;
105521         }else{
105522           int affLeft, affRight;
105523           /* If the right-hand side is also a column, then the affinities
105524           ** of both right and left sides must be such that no type
105525           ** conversions are required on the right.  (Ticket #2249)
105526           */
105527           affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
105528           affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
105529           if( affRight!=0 && affRight!=affLeft ){
105530             okToChngToIN = 0;
105531           }else{
105532             pOrTerm->wtFlags |= TERM_OR_OK;
105533           }
105534         }
105535       }
105536     }
105537
105538     /* At this point, okToChngToIN is true if original pTerm satisfies
105539     ** case 1.  In that case, construct a new virtual term that is 
105540     ** pTerm converted into an IN operator.
105541     **
105542     ** EV: R-00211-15100
105543     */
105544     if( okToChngToIN ){
105545       Expr *pDup;            /* A transient duplicate expression */
105546       ExprList *pList = 0;   /* The RHS of the IN operator */
105547       Expr *pLeft = 0;       /* The LHS of the IN operator */
105548       Expr *pNew;            /* The complete IN operator */
105549
105550       for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
105551         if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
105552         assert( pOrTerm->eOperator & WO_EQ );
105553         assert( pOrTerm->leftCursor==iCursor );
105554         assert( pOrTerm->u.leftColumn==iColumn );
105555         pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
105556         pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup);
105557         pLeft = pOrTerm->pExpr->pLeft;
105558       }
105559       assert( pLeft!=0 );
105560       pDup = sqlite3ExprDup(db, pLeft, 0);
105561       pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
105562       if( pNew ){
105563         int idxNew;
105564         transferJoinMarkings(pNew, pExpr);
105565         assert( !ExprHasProperty(pNew, EP_xIsSelect) );
105566         pNew->x.pList = pList;
105567         idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
105568         testcase( idxNew==0 );
105569         exprAnalyze(pSrc, pWC, idxNew);
105570         pTerm = &pWC->a[idxTerm];
105571         pWC->a[idxNew].iParent = idxTerm;
105572         pTerm->nChild = 1;
105573       }else{
105574         sqlite3ExprListDelete(db, pList);
105575       }
105576       pTerm->eOperator = WO_NOOP;  /* case 1 trumps case 2 */
105577     }
105578   }
105579 }
105580 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
105581
105582 /*
105583 ** The input to this routine is an WhereTerm structure with only the
105584 ** "pExpr" field filled in.  The job of this routine is to analyze the
105585 ** subexpression and populate all the other fields of the WhereTerm
105586 ** structure.
105587 **
105588 ** If the expression is of the form "<expr> <op> X" it gets commuted
105589 ** to the standard form of "X <op> <expr>".
105590 **
105591 ** If the expression is of the form "X <op> Y" where both X and Y are
105592 ** columns, then the original expression is unchanged and a new virtual
105593 ** term of the form "Y <op> X" is added to the WHERE clause and
105594 ** analyzed separately.  The original term is marked with TERM_COPIED
105595 ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
105596 ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
105597 ** is a commuted copy of a prior term.)  The original term has nChild=1
105598 ** and the copy has idxParent set to the index of the original term.
105599 */
105600 static void exprAnalyze(
105601   SrcList *pSrc,            /* the FROM clause */
105602   WhereClause *pWC,         /* the WHERE clause */
105603   int idxTerm               /* Index of the term to be analyzed */
105604 ){
105605   WhereTerm *pTerm;                /* The term to be analyzed */
105606   WhereMaskSet *pMaskSet;          /* Set of table index masks */
105607   Expr *pExpr;                     /* The expression to be analyzed */
105608   Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
105609   Bitmask prereqAll;               /* Prerequesites of pExpr */
105610   Bitmask extraRight = 0;          /* Extra dependencies on LEFT JOIN */
105611   Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
105612   int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
105613   int noCase = 0;                  /* LIKE/GLOB distinguishes case */
105614   int op;                          /* Top-level operator.  pExpr->op */
105615   Parse *pParse = pWC->pParse;     /* Parsing context */
105616   sqlite3 *db = pParse->db;        /* Database connection */
105617
105618   if( db->mallocFailed ){
105619     return;
105620   }
105621   pTerm = &pWC->a[idxTerm];
105622   pMaskSet = pWC->pMaskSet;
105623   pExpr = pTerm->pExpr;
105624   assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
105625   prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
105626   op = pExpr->op;
105627   if( op==TK_IN ){
105628     assert( pExpr->pRight==0 );
105629     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
105630       pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
105631     }else{
105632       pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
105633     }
105634   }else if( op==TK_ISNULL ){
105635     pTerm->prereqRight = 0;
105636   }else{
105637     pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
105638   }
105639   prereqAll = exprTableUsage(pMaskSet, pExpr);
105640   if( ExprHasProperty(pExpr, EP_FromJoin) ){
105641     Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
105642     prereqAll |= x;
105643     extraRight = x-1;  /* ON clause terms may not be used with an index
105644                        ** on left table of a LEFT JOIN.  Ticket #3015 */
105645   }
105646   pTerm->prereqAll = prereqAll;
105647   pTerm->leftCursor = -1;
105648   pTerm->iParent = -1;
105649   pTerm->eOperator = 0;
105650   if( allowedOp(op) ){
105651     Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
105652     Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
105653     u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
105654     if( pLeft->op==TK_COLUMN ){
105655       pTerm->leftCursor = pLeft->iTable;
105656       pTerm->u.leftColumn = pLeft->iColumn;
105657       pTerm->eOperator = operatorMask(op) & opMask;
105658     }
105659     if( pRight && pRight->op==TK_COLUMN ){
105660       WhereTerm *pNew;
105661       Expr *pDup;
105662       u16 eExtraOp = 0;        /* Extra bits for pNew->eOperator */
105663       if( pTerm->leftCursor>=0 ){
105664         int idxNew;
105665         pDup = sqlite3ExprDup(db, pExpr, 0);
105666         if( db->mallocFailed ){
105667           sqlite3ExprDelete(db, pDup);
105668           return;
105669         }
105670         idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
105671         if( idxNew==0 ) return;
105672         pNew = &pWC->a[idxNew];
105673         pNew->iParent = idxTerm;
105674         pTerm = &pWC->a[idxTerm];
105675         pTerm->nChild = 1;
105676         pTerm->wtFlags |= TERM_COPIED;
105677         if( pExpr->op==TK_EQ
105678          && !ExprHasProperty(pExpr, EP_FromJoin)
105679          && OptimizationEnabled(db, SQLITE_Transitive)
105680         ){
105681           pTerm->eOperator |= WO_EQUIV;
105682           eExtraOp = WO_EQUIV;
105683         }
105684       }else{
105685         pDup = pExpr;
105686         pNew = pTerm;
105687       }
105688       exprCommute(pParse, pDup);
105689       pLeft = sqlite3ExprSkipCollate(pDup->pLeft);
105690       pNew->leftCursor = pLeft->iTable;
105691       pNew->u.leftColumn = pLeft->iColumn;
105692       testcase( (prereqLeft | extraRight) != prereqLeft );
105693       pNew->prereqRight = prereqLeft | extraRight;
105694       pNew->prereqAll = prereqAll;
105695       pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
105696     }
105697   }
105698
105699 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
105700   /* If a term is the BETWEEN operator, create two new virtual terms
105701   ** that define the range that the BETWEEN implements.  For example:
105702   **
105703   **      a BETWEEN b AND c
105704   **
105705   ** is converted into:
105706   **
105707   **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
105708   **
105709   ** The two new terms are added onto the end of the WhereClause object.
105710   ** The new terms are "dynamic" and are children of the original BETWEEN
105711   ** term.  That means that if the BETWEEN term is coded, the children are
105712   ** skipped.  Or, if the children are satisfied by an index, the original
105713   ** BETWEEN term is skipped.
105714   */
105715   else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
105716     ExprList *pList = pExpr->x.pList;
105717     int i;
105718     static const u8 ops[] = {TK_GE, TK_LE};
105719     assert( pList!=0 );
105720     assert( pList->nExpr==2 );
105721     for(i=0; i<2; i++){
105722       Expr *pNewExpr;
105723       int idxNew;
105724       pNewExpr = sqlite3PExpr(pParse, ops[i], 
105725                              sqlite3ExprDup(db, pExpr->pLeft, 0),
105726                              sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
105727       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
105728       testcase( idxNew==0 );
105729       exprAnalyze(pSrc, pWC, idxNew);
105730       pTerm = &pWC->a[idxTerm];
105731       pWC->a[idxNew].iParent = idxTerm;
105732     }
105733     pTerm->nChild = 2;
105734   }
105735 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
105736
105737 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
105738   /* Analyze a term that is composed of two or more subterms connected by
105739   ** an OR operator.
105740   */
105741   else if( pExpr->op==TK_OR ){
105742     assert( pWC->op==TK_AND );
105743     exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
105744     pTerm = &pWC->a[idxTerm];
105745   }
105746 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
105747
105748 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
105749   /* Add constraints to reduce the search space on a LIKE or GLOB
105750   ** operator.
105751   **
105752   ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
105753   **
105754   **          x>='abc' AND x<'abd' AND x LIKE 'abc%'
105755   **
105756   ** The last character of the prefix "abc" is incremented to form the
105757   ** termination condition "abd".
105758   */
105759   if( pWC->op==TK_AND 
105760    && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
105761   ){
105762     Expr *pLeft;       /* LHS of LIKE/GLOB operator */
105763     Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
105764     Expr *pNewExpr1;
105765     Expr *pNewExpr2;
105766     int idxNew1;
105767     int idxNew2;
105768     Token sCollSeqName;  /* Name of collating sequence */
105769
105770     pLeft = pExpr->x.pList->a[1].pExpr;
105771     pStr2 = sqlite3ExprDup(db, pStr1, 0);
105772     if( !db->mallocFailed ){
105773       u8 c, *pC;       /* Last character before the first wildcard */
105774       pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
105775       c = *pC;
105776       if( noCase ){
105777         /* The point is to increment the last character before the first
105778         ** wildcard.  But if we increment '@', that will push it into the
105779         ** alphabetic range where case conversions will mess up the 
105780         ** inequality.  To avoid this, make sure to also run the full
105781         ** LIKE on all candidate expressions by clearing the isComplete flag
105782         */
105783         if( c=='A'-1 ) isComplete = 0;   /* EV: R-64339-08207 */
105784
105785
105786         c = sqlite3UpperToLower[c];
105787       }
105788       *pC = c + 1;
105789     }
105790     sCollSeqName.z = noCase ? "NOCASE" : "BINARY";
105791     sCollSeqName.n = 6;
105792     pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
105793     pNewExpr1 = sqlite3PExpr(pParse, TK_GE, 
105794            sqlite3ExprAddCollateToken(pParse,pNewExpr1,&sCollSeqName),
105795            pStr1, 0);
105796     idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
105797     testcase( idxNew1==0 );
105798     exprAnalyze(pSrc, pWC, idxNew1);
105799     pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
105800     pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
105801            sqlite3ExprAddCollateToken(pParse,pNewExpr2,&sCollSeqName),
105802            pStr2, 0);
105803     idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
105804     testcase( idxNew2==0 );
105805     exprAnalyze(pSrc, pWC, idxNew2);
105806     pTerm = &pWC->a[idxTerm];
105807     if( isComplete ){
105808       pWC->a[idxNew1].iParent = idxTerm;
105809       pWC->a[idxNew2].iParent = idxTerm;
105810       pTerm->nChild = 2;
105811     }
105812   }
105813 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
105814
105815 #ifndef SQLITE_OMIT_VIRTUALTABLE
105816   /* Add a WO_MATCH auxiliary term to the constraint set if the
105817   ** current expression is of the form:  column MATCH expr.
105818   ** This information is used by the xBestIndex methods of
105819   ** virtual tables.  The native query optimizer does not attempt
105820   ** to do anything with MATCH functions.
105821   */
105822   if( isMatchOfColumn(pExpr) ){
105823     int idxNew;
105824     Expr *pRight, *pLeft;
105825     WhereTerm *pNewTerm;
105826     Bitmask prereqColumn, prereqExpr;
105827
105828     pRight = pExpr->x.pList->a[0].pExpr;
105829     pLeft = pExpr->x.pList->a[1].pExpr;
105830     prereqExpr = exprTableUsage(pMaskSet, pRight);
105831     prereqColumn = exprTableUsage(pMaskSet, pLeft);
105832     if( (prereqExpr & prereqColumn)==0 ){
105833       Expr *pNewExpr;
105834       pNewExpr = sqlite3PExpr(pParse, TK_MATCH, 
105835                               0, sqlite3ExprDup(db, pRight, 0), 0);
105836       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
105837       testcase( idxNew==0 );
105838       pNewTerm = &pWC->a[idxNew];
105839       pNewTerm->prereqRight = prereqExpr;
105840       pNewTerm->leftCursor = pLeft->iTable;
105841       pNewTerm->u.leftColumn = pLeft->iColumn;
105842       pNewTerm->eOperator = WO_MATCH;
105843       pNewTerm->iParent = idxTerm;
105844       pTerm = &pWC->a[idxTerm];
105845       pTerm->nChild = 1;
105846       pTerm->wtFlags |= TERM_COPIED;
105847       pNewTerm->prereqAll = pTerm->prereqAll;
105848     }
105849   }
105850 #endif /* SQLITE_OMIT_VIRTUALTABLE */
105851
105852 #ifdef SQLITE_ENABLE_STAT3
105853   /* When sqlite_stat3 histogram data is available an operator of the
105854   ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
105855   ** as "x>NULL" if x is not an INTEGER PRIMARY KEY.  So construct a
105856   ** virtual term of that form.
105857   **
105858   ** Note that the virtual term must be tagged with TERM_VNULL.  This
105859   ** TERM_VNULL tag will suppress the not-null check at the beginning
105860   ** of the loop.  Without the TERM_VNULL flag, the not-null check at
105861   ** the start of the loop will prevent any results from being returned.
105862   */
105863   if( pExpr->op==TK_NOTNULL
105864    && pExpr->pLeft->op==TK_COLUMN
105865    && pExpr->pLeft->iColumn>=0
105866   ){
105867     Expr *pNewExpr;
105868     Expr *pLeft = pExpr->pLeft;
105869     int idxNew;
105870     WhereTerm *pNewTerm;
105871
105872     pNewExpr = sqlite3PExpr(pParse, TK_GT,
105873                             sqlite3ExprDup(db, pLeft, 0),
105874                             sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
105875
105876     idxNew = whereClauseInsert(pWC, pNewExpr,
105877                               TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
105878     if( idxNew ){
105879       pNewTerm = &pWC->a[idxNew];
105880       pNewTerm->prereqRight = 0;
105881       pNewTerm->leftCursor = pLeft->iTable;
105882       pNewTerm->u.leftColumn = pLeft->iColumn;
105883       pNewTerm->eOperator = WO_GT;
105884       pNewTerm->iParent = idxTerm;
105885       pTerm = &pWC->a[idxTerm];
105886       pTerm->nChild = 1;
105887       pTerm->wtFlags |= TERM_COPIED;
105888       pNewTerm->prereqAll = pTerm->prereqAll;
105889     }
105890   }
105891 #endif /* SQLITE_ENABLE_STAT */
105892
105893   /* Prevent ON clause terms of a LEFT JOIN from being used to drive
105894   ** an index for tables to the left of the join.
105895   */
105896   pTerm->prereqRight |= extraRight;
105897 }
105898
105899 /*
105900 ** This function searches the expression list passed as the second argument
105901 ** for an expression of type TK_COLUMN that refers to the same column and
105902 ** uses the same collation sequence as the iCol'th column of index pIdx.
105903 ** Argument iBase is the cursor number used for the table that pIdx refers
105904 ** to.
105905 **
105906 ** If such an expression is found, its index in pList->a[] is returned. If
105907 ** no expression is found, -1 is returned.
105908 */
105909 static int findIndexCol(
105910   Parse *pParse,                  /* Parse context */
105911   ExprList *pList,                /* Expression list to search */
105912   int iBase,                      /* Cursor for table associated with pIdx */
105913   Index *pIdx,                    /* Index to match column of */
105914   int iCol                        /* Column of index to match */
105915 ){
105916   int i;
105917   const char *zColl = pIdx->azColl[iCol];
105918
105919   for(i=0; i<pList->nExpr; i++){
105920     Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
105921     if( p->op==TK_COLUMN
105922      && p->iColumn==pIdx->aiColumn[iCol]
105923      && p->iTable==iBase
105924     ){
105925       CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
105926       if( ALWAYS(pColl) && 0==sqlite3StrICmp(pColl->zName, zColl) ){
105927         return i;
105928       }
105929     }
105930   }
105931
105932   return -1;
105933 }
105934
105935 /*
105936 ** This routine determines if pIdx can be used to assist in processing a
105937 ** DISTINCT qualifier. In other words, it tests whether or not using this
105938 ** index for the outer loop guarantees that rows with equal values for
105939 ** all expressions in the pDistinct list are delivered grouped together.
105940 **
105941 ** For example, the query 
105942 **
105943 **   SELECT DISTINCT a, b, c FROM tbl WHERE a = ?
105944 **
105945 ** can benefit from any index on columns "b" and "c".
105946 */
105947 static int isDistinctIndex(
105948   Parse *pParse,                  /* Parsing context */
105949   WhereClause *pWC,               /* The WHERE clause */
105950   Index *pIdx,                    /* The index being considered */
105951   int base,                       /* Cursor number for the table pIdx is on */
105952   ExprList *pDistinct,            /* The DISTINCT expressions */
105953   int nEqCol                      /* Number of index columns with == */
105954 ){
105955   Bitmask mask = 0;               /* Mask of unaccounted for pDistinct exprs */
105956   int i;                          /* Iterator variable */
105957
105958   assert( pDistinct!=0 );
105959   if( pIdx->zName==0 || pDistinct->nExpr>=BMS ) return 0;
105960   testcase( pDistinct->nExpr==BMS-1 );
105961
105962   /* Loop through all the expressions in the distinct list. If any of them
105963   ** are not simple column references, return early. Otherwise, test if the
105964   ** WHERE clause contains a "col=X" clause. If it does, the expression
105965   ** can be ignored. If it does not, and the column does not belong to the
105966   ** same table as index pIdx, return early. Finally, if there is no
105967   ** matching "col=X" expression and the column is on the same table as pIdx,
105968   ** set the corresponding bit in variable mask.
105969   */
105970   for(i=0; i<pDistinct->nExpr; i++){
105971     WhereTerm *pTerm;
105972     Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
105973     if( p->op!=TK_COLUMN ) return 0;
105974     pTerm = findTerm(pWC, p->iTable, p->iColumn, ~(Bitmask)0, WO_EQ, 0);
105975     if( pTerm ){
105976       Expr *pX = pTerm->pExpr;
105977       CollSeq *p1 = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
105978       CollSeq *p2 = sqlite3ExprCollSeq(pParse, p);
105979       if( p1==p2 ) continue;
105980     }
105981     if( p->iTable!=base ) return 0;
105982     mask |= (((Bitmask)1) << i);
105983   }
105984
105985   for(i=nEqCol; mask && i<pIdx->nColumn; i++){
105986     int iExpr = findIndexCol(pParse, pDistinct, base, pIdx, i);
105987     if( iExpr<0 ) break;
105988     mask &= ~(((Bitmask)1) << iExpr);
105989   }
105990
105991   return (mask==0);
105992 }
105993
105994
105995 /*
105996 ** Return true if the DISTINCT expression-list passed as the third argument
105997 ** is redundant. A DISTINCT list is redundant if the database contains a
105998 ** UNIQUE index that guarantees that the result of the query will be distinct
105999 ** anyway.
106000 */
106001 static int isDistinctRedundant(
106002   Parse *pParse,
106003   SrcList *pTabList,
106004   WhereClause *pWC,
106005   ExprList *pDistinct
106006 ){
106007   Table *pTab;
106008   Index *pIdx;
106009   int i;                          
106010   int iBase;
106011
106012   /* If there is more than one table or sub-select in the FROM clause of
106013   ** this query, then it will not be possible to show that the DISTINCT 
106014   ** clause is redundant. */
106015   if( pTabList->nSrc!=1 ) return 0;
106016   iBase = pTabList->a[0].iCursor;
106017   pTab = pTabList->a[0].pTab;
106018
106019   /* If any of the expressions is an IPK column on table iBase, then return 
106020   ** true. Note: The (p->iTable==iBase) part of this test may be false if the
106021   ** current SELECT is a correlated sub-query.
106022   */
106023   for(i=0; i<pDistinct->nExpr; i++){
106024     Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
106025     if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
106026   }
106027
106028   /* Loop through all indices on the table, checking each to see if it makes
106029   ** the DISTINCT qualifier redundant. It does so if:
106030   **
106031   **   1. The index is itself UNIQUE, and
106032   **
106033   **   2. All of the columns in the index are either part of the pDistinct
106034   **      list, or else the WHERE clause contains a term of the form "col=X",
106035   **      where X is a constant value. The collation sequences of the
106036   **      comparison and select-list expressions must match those of the index.
106037   **
106038   **   3. All of those index columns for which the WHERE clause does not
106039   **      contain a "col=X" term are subject to a NOT NULL constraint.
106040   */
106041   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
106042     if( pIdx->onError==OE_None ) continue;
106043     for(i=0; i<pIdx->nColumn; i++){
106044       int iCol = pIdx->aiColumn[i];
106045       if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){
106046         int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i);
106047         if( iIdxCol<0 || pTab->aCol[pIdx->aiColumn[i]].notNull==0 ){
106048           break;
106049         }
106050       }
106051     }
106052     if( i==pIdx->nColumn ){
106053       /* This index implies that the DISTINCT qualifier is redundant. */
106054       return 1;
106055     }
106056   }
106057
106058   return 0;
106059 }
106060
106061 /*
106062 ** Prepare a crude estimate of the logarithm of the input value.
106063 ** The results need not be exact.  This is only used for estimating
106064 ** the total cost of performing operations with O(logN) or O(NlogN)
106065 ** complexity.  Because N is just a guess, it is no great tragedy if
106066 ** logN is a little off.
106067 */
106068 static double estLog(double N){
106069   double logN = 1;
106070   double x = 10;
106071   while( N>x ){
106072     logN += 1;
106073     x *= 10;
106074   }
106075   return logN;
106076 }
106077
106078 /*
106079 ** Two routines for printing the content of an sqlite3_index_info
106080 ** structure.  Used for testing and debugging only.  If neither
106081 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
106082 ** are no-ops.
106083 */
106084 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
106085 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
106086   int i;
106087   if( !sqlite3WhereTrace ) return;
106088   for(i=0; i<p->nConstraint; i++){
106089     sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
106090        i,
106091        p->aConstraint[i].iColumn,
106092        p->aConstraint[i].iTermOffset,
106093        p->aConstraint[i].op,
106094        p->aConstraint[i].usable);
106095   }
106096   for(i=0; i<p->nOrderBy; i++){
106097     sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
106098        i,
106099        p->aOrderBy[i].iColumn,
106100        p->aOrderBy[i].desc);
106101   }
106102 }
106103 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
106104   int i;
106105   if( !sqlite3WhereTrace ) return;
106106   for(i=0; i<p->nConstraint; i++){
106107     sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
106108        i,
106109        p->aConstraintUsage[i].argvIndex,
106110        p->aConstraintUsage[i].omit);
106111   }
106112   sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
106113   sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
106114   sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
106115   sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
106116 }
106117 #else
106118 #define TRACE_IDX_INPUTS(A)
106119 #define TRACE_IDX_OUTPUTS(A)
106120 #endif
106121
106122 /* 
106123 ** Required because bestIndex() is called by bestOrClauseIndex() 
106124 */
106125 static void bestIndex(WhereBestIdx*);
106126
106127 /*
106128 ** This routine attempts to find an scanning strategy that can be used 
106129 ** to optimize an 'OR' expression that is part of a WHERE clause. 
106130 **
106131 ** The table associated with FROM clause term pSrc may be either a
106132 ** regular B-Tree table or a virtual table.
106133 */
106134 static void bestOrClauseIndex(WhereBestIdx *p){
106135 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
106136   WhereClause *pWC = p->pWC;           /* The WHERE clause */
106137   struct SrcList_item *pSrc = p->pSrc; /* The FROM clause term to search */
106138   const int iCur = pSrc->iCursor;      /* The cursor of the table  */
106139   const Bitmask maskSrc = getMask(pWC->pMaskSet, iCur);  /* Bitmask for pSrc */
106140   WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm];        /* End of pWC->a[] */
106141   WhereTerm *pTerm;                    /* A single term of the WHERE clause */
106142
106143   /* The OR-clause optimization is disallowed if the INDEXED BY or
106144   ** NOT INDEXED clauses are used or if the WHERE_AND_ONLY bit is set. */
106145   if( pSrc->notIndexed || pSrc->pIndex!=0 ){
106146     return;
106147   }
106148   if( pWC->wctrlFlags & WHERE_AND_ONLY ){
106149     return;
106150   }
106151
106152   /* Search the WHERE clause terms for a usable WO_OR term. */
106153   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
106154     if( (pTerm->eOperator & WO_OR)!=0
106155      && ((pTerm->prereqAll & ~maskSrc) & p->notReady)==0
106156      && (pTerm->u.pOrInfo->indexable & maskSrc)!=0 
106157     ){
106158       WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
106159       WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
106160       WhereTerm *pOrTerm;
106161       int flags = WHERE_MULTI_OR;
106162       double rTotal = 0;
106163       double nRow = 0;
106164       Bitmask used = 0;
106165       WhereBestIdx sBOI;
106166
106167       sBOI = *p;
106168       sBOI.pOrderBy = 0;
106169       sBOI.pDistinct = 0;
106170       sBOI.ppIdxInfo = 0;
106171       for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
106172         WHERETRACE(("... Multi-index OR testing for term %d of %d....\n", 
106173           (pOrTerm - pOrWC->a), (pTerm - pWC->a)
106174         ));
106175         if( (pOrTerm->eOperator& WO_AND)!=0 ){
106176           sBOI.pWC = &pOrTerm->u.pAndInfo->wc;
106177           bestIndex(&sBOI);
106178         }else if( pOrTerm->leftCursor==iCur ){
106179           WhereClause tempWC;
106180           tempWC.pParse = pWC->pParse;
106181           tempWC.pMaskSet = pWC->pMaskSet;
106182           tempWC.pOuter = pWC;
106183           tempWC.op = TK_AND;
106184           tempWC.a = pOrTerm;
106185           tempWC.wctrlFlags = 0;
106186           tempWC.nTerm = 1;
106187           sBOI.pWC = &tempWC;
106188           bestIndex(&sBOI);
106189         }else{
106190           continue;
106191         }
106192         rTotal += sBOI.cost.rCost;
106193         nRow += sBOI.cost.plan.nRow;
106194         used |= sBOI.cost.used;
106195         if( rTotal>=p->cost.rCost ) break;
106196       }
106197
106198       /* If there is an ORDER BY clause, increase the scan cost to account 
106199       ** for the cost of the sort. */
106200       if( p->pOrderBy!=0 ){
106201         WHERETRACE(("... sorting increases OR cost %.9g to %.9g\n",
106202                     rTotal, rTotal+nRow*estLog(nRow)));
106203         rTotal += nRow*estLog(nRow);
106204       }
106205
106206       /* If the cost of scanning using this OR term for optimization is
106207       ** less than the current cost stored in pCost, replace the contents
106208       ** of pCost. */
106209       WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n", rTotal, nRow));
106210       if( rTotal<p->cost.rCost ){
106211         p->cost.rCost = rTotal;
106212         p->cost.used = used;
106213         p->cost.plan.nRow = nRow;
106214         p->cost.plan.nOBSat = p->i ? p->aLevel[p->i-1].plan.nOBSat : 0;
106215         p->cost.plan.wsFlags = flags;
106216         p->cost.plan.u.pTerm = pTerm;
106217       }
106218     }
106219   }
106220 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
106221 }
106222
106223 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
106224 /*
106225 ** Return TRUE if the WHERE clause term pTerm is of a form where it
106226 ** could be used with an index to access pSrc, assuming an appropriate
106227 ** index existed.
106228 */
106229 static int termCanDriveIndex(
106230   WhereTerm *pTerm,              /* WHERE clause term to check */
106231   struct SrcList_item *pSrc,     /* Table we are trying to access */
106232   Bitmask notReady               /* Tables in outer loops of the join */
106233 ){
106234   char aff;
106235   if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
106236   if( (pTerm->eOperator & WO_EQ)==0 ) return 0;
106237   if( (pTerm->prereqRight & notReady)!=0 ) return 0;
106238   aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
106239   if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
106240   return 1;
106241 }
106242 #endif
106243
106244 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
106245 /*
106246 ** If the query plan for pSrc specified in pCost is a full table scan
106247 ** and indexing is allows (if there is no NOT INDEXED clause) and it
106248 ** possible to construct a transient index that would perform better
106249 ** than a full table scan even when the cost of constructing the index
106250 ** is taken into account, then alter the query plan to use the
106251 ** transient index.
106252 */
106253 static void bestAutomaticIndex(WhereBestIdx *p){
106254   Parse *pParse = p->pParse;            /* The parsing context */
106255   WhereClause *pWC = p->pWC;            /* The WHERE clause */
106256   struct SrcList_item *pSrc = p->pSrc;  /* The FROM clause term to search */
106257   double nTableRow;                     /* Rows in the input table */
106258   double logN;                          /* log(nTableRow) */
106259   double costTempIdx;         /* per-query cost of the transient index */
106260   WhereTerm *pTerm;           /* A single term of the WHERE clause */
106261   WhereTerm *pWCEnd;          /* End of pWC->a[] */
106262   Table *pTable;              /* Table tht might be indexed */
106263
106264   if( pParse->nQueryLoop<=(double)1 ){
106265     /* There is no point in building an automatic index for a single scan */
106266     return;
106267   }
106268   if( (pParse->db->flags & SQLITE_AutoIndex)==0 ){
106269     /* Automatic indices are disabled at run-time */
106270     return;
106271   }
106272   if( (p->cost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0
106273    && (p->cost.plan.wsFlags & WHERE_COVER_SCAN)==0
106274   ){
106275     /* We already have some kind of index in use for this query. */
106276     return;
106277   }
106278   if( pSrc->viaCoroutine ){
106279     /* Cannot index a co-routine */
106280     return;
106281   }
106282   if( pSrc->notIndexed ){
106283     /* The NOT INDEXED clause appears in the SQL. */
106284     return;
106285   }
106286   if( pSrc->isCorrelated ){
106287     /* The source is a correlated sub-query. No point in indexing it. */
106288     return;
106289   }
106290
106291   assert( pParse->nQueryLoop >= (double)1 );
106292   pTable = pSrc->pTab;
106293   nTableRow = pTable->nRowEst;
106294   logN = estLog(nTableRow);
106295   costTempIdx = 2*logN*(nTableRow/pParse->nQueryLoop + 1);
106296   if( costTempIdx>=p->cost.rCost ){
106297     /* The cost of creating the transient table would be greater than
106298     ** doing the full table scan */
106299     return;
106300   }
106301
106302   /* Search for any equality comparison term */
106303   pWCEnd = &pWC->a[pWC->nTerm];
106304   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
106305     if( termCanDriveIndex(pTerm, pSrc, p->notReady) ){
106306       WHERETRACE(("auto-index reduces cost from %.1f to %.1f\n",
106307                     p->cost.rCost, costTempIdx));
106308       p->cost.rCost = costTempIdx;
106309       p->cost.plan.nRow = logN + 1;
106310       p->cost.plan.wsFlags = WHERE_TEMP_INDEX;
106311       p->cost.used = pTerm->prereqRight;
106312       break;
106313     }
106314   }
106315 }
106316 #else
106317 # define bestAutomaticIndex(A)  /* no-op */
106318 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
106319
106320
106321 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
106322 /*
106323 ** Generate code to construct the Index object for an automatic index
106324 ** and to set up the WhereLevel object pLevel so that the code generator
106325 ** makes use of the automatic index.
106326 */
106327 static void constructAutomaticIndex(
106328   Parse *pParse,              /* The parsing context */
106329   WhereClause *pWC,           /* The WHERE clause */
106330   struct SrcList_item *pSrc,  /* The FROM clause term to get the next index */
106331   Bitmask notReady,           /* Mask of cursors that are not available */
106332   WhereLevel *pLevel          /* Write new index here */
106333 ){
106334   int nColumn;                /* Number of columns in the constructed index */
106335   WhereTerm *pTerm;           /* A single term of the WHERE clause */
106336   WhereTerm *pWCEnd;          /* End of pWC->a[] */
106337   int nByte;                  /* Byte of memory needed for pIdx */
106338   Index *pIdx;                /* Object describing the transient index */
106339   Vdbe *v;                    /* Prepared statement under construction */
106340   int addrInit;               /* Address of the initialization bypass jump */
106341   Table *pTable;              /* The table being indexed */
106342   KeyInfo *pKeyinfo;          /* Key information for the index */   
106343   int addrTop;                /* Top of the index fill loop */
106344   int regRecord;              /* Register holding an index record */
106345   int n;                      /* Column counter */
106346   int i;                      /* Loop counter */
106347   int mxBitCol;               /* Maximum column in pSrc->colUsed */
106348   CollSeq *pColl;             /* Collating sequence to on a column */
106349   Bitmask idxCols;            /* Bitmap of columns used for indexing */
106350   Bitmask extraCols;          /* Bitmap of additional columns */
106351
106352   /* Generate code to skip over the creation and initialization of the
106353   ** transient index on 2nd and subsequent iterations of the loop. */
106354   v = pParse->pVdbe;
106355   assert( v!=0 );
106356   addrInit = sqlite3CodeOnce(pParse);
106357
106358   /* Count the number of columns that will be added to the index
106359   ** and used to match WHERE clause constraints */
106360   nColumn = 0;
106361   pTable = pSrc->pTab;
106362   pWCEnd = &pWC->a[pWC->nTerm];
106363   idxCols = 0;
106364   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
106365     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
106366       int iCol = pTerm->u.leftColumn;
106367       Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
106368       testcase( iCol==BMS );
106369       testcase( iCol==BMS-1 );
106370       if( (idxCols & cMask)==0 ){
106371         nColumn++;
106372         idxCols |= cMask;
106373       }
106374     }
106375   }
106376   assert( nColumn>0 );
106377   pLevel->plan.nEq = nColumn;
106378
106379   /* Count the number of additional columns needed to create a
106380   ** covering index.  A "covering index" is an index that contains all
106381   ** columns that are needed by the query.  With a covering index, the
106382   ** original table never needs to be accessed.  Automatic indices must
106383   ** be a covering index because the index will not be updated if the
106384   ** original table changes and the index and table cannot both be used
106385   ** if they go out of sync.
106386   */
106387   extraCols = pSrc->colUsed & (~idxCols | (((Bitmask)1)<<(BMS-1)));
106388   mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
106389   testcase( pTable->nCol==BMS-1 );
106390   testcase( pTable->nCol==BMS-2 );
106391   for(i=0; i<mxBitCol; i++){
106392     if( extraCols & (((Bitmask)1)<<i) ) nColumn++;
106393   }
106394   if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
106395     nColumn += pTable->nCol - BMS + 1;
106396   }
106397   pLevel->plan.wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WO_EQ;
106398
106399   /* Construct the Index object to describe this index */
106400   nByte = sizeof(Index);
106401   nByte += nColumn*sizeof(int);     /* Index.aiColumn */
106402   nByte += nColumn*sizeof(char*);   /* Index.azColl */
106403   nByte += nColumn;                 /* Index.aSortOrder */
106404   pIdx = sqlite3DbMallocZero(pParse->db, nByte);
106405   if( pIdx==0 ) return;
106406   pLevel->plan.u.pIdx = pIdx;
106407   pIdx->azColl = (char**)&pIdx[1];
106408   pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
106409   pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
106410   pIdx->zName = "auto-index";
106411   pIdx->nColumn = nColumn;
106412   pIdx->pTable = pTable;
106413   n = 0;
106414   idxCols = 0;
106415   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
106416     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
106417       int iCol = pTerm->u.leftColumn;
106418       Bitmask cMask = iCol>=BMS ? ((Bitmask)1)<<(BMS-1) : ((Bitmask)1)<<iCol;
106419       if( (idxCols & cMask)==0 ){
106420         Expr *pX = pTerm->pExpr;
106421         idxCols |= cMask;
106422         pIdx->aiColumn[n] = pTerm->u.leftColumn;
106423         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
106424         pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
106425         n++;
106426       }
106427     }
106428   }
106429   assert( (u32)n==pLevel->plan.nEq );
106430
106431   /* Add additional columns needed to make the automatic index into
106432   ** a covering index */
106433   for(i=0; i<mxBitCol; i++){
106434     if( extraCols & (((Bitmask)1)<<i) ){
106435       pIdx->aiColumn[n] = i;
106436       pIdx->azColl[n] = "BINARY";
106437       n++;
106438     }
106439   }
106440   if( pSrc->colUsed & (((Bitmask)1)<<(BMS-1)) ){
106441     for(i=BMS-1; i<pTable->nCol; i++){
106442       pIdx->aiColumn[n] = i;
106443       pIdx->azColl[n] = "BINARY";
106444       n++;
106445     }
106446   }
106447   assert( n==nColumn );
106448
106449   /* Create the automatic index */
106450   pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);
106451   assert( pLevel->iIdxCur>=0 );
106452   sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
106453                     (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
106454   VdbeComment((v, "for %s", pTable->zName));
106455
106456   /* Fill the automatic index with content */
106457   addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
106458   regRecord = sqlite3GetTempReg(pParse);
106459   sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1);
106460   sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
106461   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
106462   sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
106463   sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
106464   sqlite3VdbeJumpHere(v, addrTop);
106465   sqlite3ReleaseTempReg(pParse, regRecord);
106466   
106467   /* Jump here when skipping the initialization */
106468   sqlite3VdbeJumpHere(v, addrInit);
106469 }
106470 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
106471
106472 #ifndef SQLITE_OMIT_VIRTUALTABLE
106473 /*
106474 ** Allocate and populate an sqlite3_index_info structure. It is the 
106475 ** responsibility of the caller to eventually release the structure
106476 ** by passing the pointer returned by this function to sqlite3_free().
106477 */
106478 static sqlite3_index_info *allocateIndexInfo(WhereBestIdx *p){
106479   Parse *pParse = p->pParse; 
106480   WhereClause *pWC = p->pWC;
106481   struct SrcList_item *pSrc = p->pSrc;
106482   ExprList *pOrderBy = p->pOrderBy;
106483   int i, j;
106484   int nTerm;
106485   struct sqlite3_index_constraint *pIdxCons;
106486   struct sqlite3_index_orderby *pIdxOrderBy;
106487   struct sqlite3_index_constraint_usage *pUsage;
106488   WhereTerm *pTerm;
106489   int nOrderBy;
106490   sqlite3_index_info *pIdxInfo;
106491
106492   WHERETRACE(("Recomputing index info for %s...\n", pSrc->pTab->zName));
106493
106494   /* Count the number of possible WHERE clause constraints referring
106495   ** to this virtual table */
106496   for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
106497     if( pTerm->leftCursor != pSrc->iCursor ) continue;
106498     assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
106499     testcase( pTerm->eOperator & WO_IN );
106500     testcase( pTerm->eOperator & WO_ISNULL );
106501     if( pTerm->eOperator & (WO_ISNULL) ) continue;
106502     if( pTerm->wtFlags & TERM_VNULL ) continue;
106503     nTerm++;
106504   }
106505
106506   /* If the ORDER BY clause contains only columns in the current 
106507   ** virtual table then allocate space for the aOrderBy part of
106508   ** the sqlite3_index_info structure.
106509   */
106510   nOrderBy = 0;
106511   if( pOrderBy ){
106512     int n = pOrderBy->nExpr;
106513     for(i=0; i<n; i++){
106514       Expr *pExpr = pOrderBy->a[i].pExpr;
106515       if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
106516     }
106517     if( i==n){
106518       nOrderBy = n;
106519     }
106520   }
106521
106522   /* Allocate the sqlite3_index_info structure
106523   */
106524   pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
106525                            + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
106526                            + sizeof(*pIdxOrderBy)*nOrderBy );
106527   if( pIdxInfo==0 ){
106528     sqlite3ErrorMsg(pParse, "out of memory");
106529     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
106530     return 0;
106531   }
106532
106533   /* Initialize the structure.  The sqlite3_index_info structure contains
106534   ** many fields that are declared "const" to prevent xBestIndex from
106535   ** changing them.  We have to do some funky casting in order to
106536   ** initialize those fields.
106537   */
106538   pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
106539   pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
106540   pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
106541   *(int*)&pIdxInfo->nConstraint = nTerm;
106542   *(int*)&pIdxInfo->nOrderBy = nOrderBy;
106543   *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
106544   *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
106545   *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
106546                                                                    pUsage;
106547
106548   for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
106549     u8 op;
106550     if( pTerm->leftCursor != pSrc->iCursor ) continue;
106551     assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
106552     testcase( pTerm->eOperator & WO_IN );
106553     testcase( pTerm->eOperator & WO_ISNULL );
106554     if( pTerm->eOperator & (WO_ISNULL) ) continue;
106555     if( pTerm->wtFlags & TERM_VNULL ) continue;
106556     pIdxCons[j].iColumn = pTerm->u.leftColumn;
106557     pIdxCons[j].iTermOffset = i;
106558     op = (u8)pTerm->eOperator & WO_ALL;
106559     if( op==WO_IN ) op = WO_EQ;
106560     pIdxCons[j].op = op;
106561     /* The direct assignment in the previous line is possible only because
106562     ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
106563     ** following asserts verify this fact. */
106564     assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
106565     assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
106566     assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
106567     assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
106568     assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
106569     assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
106570     assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
106571     j++;
106572   }
106573   for(i=0; i<nOrderBy; i++){
106574     Expr *pExpr = pOrderBy->a[i].pExpr;
106575     pIdxOrderBy[i].iColumn = pExpr->iColumn;
106576     pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
106577   }
106578
106579   return pIdxInfo;
106580 }
106581
106582 /*
106583 ** The table object reference passed as the second argument to this function
106584 ** must represent a virtual table. This function invokes the xBestIndex()
106585 ** method of the virtual table with the sqlite3_index_info pointer passed
106586 ** as the argument.
106587 **
106588 ** If an error occurs, pParse is populated with an error message and a
106589 ** non-zero value is returned. Otherwise, 0 is returned and the output
106590 ** part of the sqlite3_index_info structure is left populated.
106591 **
106592 ** Whether or not an error is returned, it is the responsibility of the
106593 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
106594 ** that this is required.
106595 */
106596 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
106597   sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
106598   int i;
106599   int rc;
106600
106601   WHERETRACE(("xBestIndex for %s\n", pTab->zName));
106602   TRACE_IDX_INPUTS(p);
106603   rc = pVtab->pModule->xBestIndex(pVtab, p);
106604   TRACE_IDX_OUTPUTS(p);
106605
106606   if( rc!=SQLITE_OK ){
106607     if( rc==SQLITE_NOMEM ){
106608       pParse->db->mallocFailed = 1;
106609     }else if( !pVtab->zErrMsg ){
106610       sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
106611     }else{
106612       sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
106613     }
106614   }
106615   sqlite3_free(pVtab->zErrMsg);
106616   pVtab->zErrMsg = 0;
106617
106618   for(i=0; i<p->nConstraint; i++){
106619     if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
106620       sqlite3ErrorMsg(pParse, 
106621           "table %s: xBestIndex returned an invalid plan", pTab->zName);
106622     }
106623   }
106624
106625   return pParse->nErr;
106626 }
106627
106628
106629 /*
106630 ** Compute the best index for a virtual table.
106631 **
106632 ** The best index is computed by the xBestIndex method of the virtual
106633 ** table module.  This routine is really just a wrapper that sets up
106634 ** the sqlite3_index_info structure that is used to communicate with
106635 ** xBestIndex.
106636 **
106637 ** In a join, this routine might be called multiple times for the
106638 ** same virtual table.  The sqlite3_index_info structure is created
106639 ** and initialized on the first invocation and reused on all subsequent
106640 ** invocations.  The sqlite3_index_info structure is also used when
106641 ** code is generated to access the virtual table.  The whereInfoDelete() 
106642 ** routine takes care of freeing the sqlite3_index_info structure after
106643 ** everybody has finished with it.
106644 */
106645 static void bestVirtualIndex(WhereBestIdx *p){
106646   Parse *pParse = p->pParse;      /* The parsing context */
106647   WhereClause *pWC = p->pWC;      /* The WHERE clause */
106648   struct SrcList_item *pSrc = p->pSrc; /* The FROM clause term to search */
106649   Table *pTab = pSrc->pTab;
106650   sqlite3_index_info *pIdxInfo;
106651   struct sqlite3_index_constraint *pIdxCons;
106652   struct sqlite3_index_constraint_usage *pUsage;
106653   WhereTerm *pTerm;
106654   int i, j;
106655   int nOrderBy;
106656   int bAllowIN;                   /* Allow IN optimizations */
106657   double rCost;
106658
106659   /* Make sure wsFlags is initialized to some sane value. Otherwise, if the 
106660   ** malloc in allocateIndexInfo() fails and this function returns leaving
106661   ** wsFlags in an uninitialized state, the caller may behave unpredictably.
106662   */
106663   memset(&p->cost, 0, sizeof(p->cost));
106664   p->cost.plan.wsFlags = WHERE_VIRTUALTABLE;
106665
106666   /* If the sqlite3_index_info structure has not been previously
106667   ** allocated and initialized, then allocate and initialize it now.
106668   */
106669   pIdxInfo = *p->ppIdxInfo;
106670   if( pIdxInfo==0 ){
106671     *p->ppIdxInfo = pIdxInfo = allocateIndexInfo(p);
106672   }
106673   if( pIdxInfo==0 ){
106674     return;
106675   }
106676
106677   /* At this point, the sqlite3_index_info structure that pIdxInfo points
106678   ** to will have been initialized, either during the current invocation or
106679   ** during some prior invocation.  Now we just have to customize the
106680   ** details of pIdxInfo for the current invocation and pass it to
106681   ** xBestIndex.
106682   */
106683
106684   /* The module name must be defined. Also, by this point there must
106685   ** be a pointer to an sqlite3_vtab structure. Otherwise
106686   ** sqlite3ViewGetColumnNames() would have picked up the error. 
106687   */
106688   assert( pTab->azModuleArg && pTab->azModuleArg[0] );
106689   assert( sqlite3GetVTable(pParse->db, pTab) );
106690
106691   /* Try once or twice.  On the first attempt, allow IN optimizations.
106692   ** If an IN optimization is accepted by the virtual table xBestIndex
106693   ** method, but the  pInfo->aConstrainUsage.omit flag is not set, then
106694   ** the query will not work because it might allow duplicate rows in
106695   ** output.  In that case, run the xBestIndex method a second time
106696   ** without the IN constraints.  Usually this loop only runs once.
106697   ** The loop will exit using a "break" statement.
106698   */
106699   for(bAllowIN=1; 1; bAllowIN--){
106700     assert( bAllowIN==0 || bAllowIN==1 );
106701
106702     /* Set the aConstraint[].usable fields and initialize all 
106703     ** output variables to zero.
106704     **
106705     ** aConstraint[].usable is true for constraints where the right-hand
106706     ** side contains only references to tables to the left of the current
106707     ** table.  In other words, if the constraint is of the form:
106708     **
106709     **           column = expr
106710     **
106711     ** and we are evaluating a join, then the constraint on column is 
106712     ** only valid if all tables referenced in expr occur to the left
106713     ** of the table containing column.
106714     **
106715     ** The aConstraints[] array contains entries for all constraints
106716     ** on the current table.  That way we only have to compute it once
106717     ** even though we might try to pick the best index multiple times.
106718     ** For each attempt at picking an index, the order of tables in the
106719     ** join might be different so we have to recompute the usable flag
106720     ** each time.
106721     */
106722     pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
106723     pUsage = pIdxInfo->aConstraintUsage;
106724     for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
106725       j = pIdxCons->iTermOffset;
106726       pTerm = &pWC->a[j];
106727       if( (pTerm->prereqRight&p->notReady)==0
106728        && (bAllowIN || (pTerm->eOperator & WO_IN)==0)
106729       ){
106730         pIdxCons->usable = 1;
106731       }else{
106732         pIdxCons->usable = 0;
106733       }
106734     }
106735     memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
106736     if( pIdxInfo->needToFreeIdxStr ){
106737       sqlite3_free(pIdxInfo->idxStr);
106738     }
106739     pIdxInfo->idxStr = 0;
106740     pIdxInfo->idxNum = 0;
106741     pIdxInfo->needToFreeIdxStr = 0;
106742     pIdxInfo->orderByConsumed = 0;
106743     /* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */
106744     pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((double)2);
106745     nOrderBy = pIdxInfo->nOrderBy;
106746     if( !p->pOrderBy ){
106747       pIdxInfo->nOrderBy = 0;
106748     }
106749   
106750     if( vtabBestIndex(pParse, pTab, pIdxInfo) ){
106751       return;
106752     }
106753   
106754     pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
106755     for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
106756       if( pUsage[i].argvIndex>0 ){
106757         j = pIdxCons->iTermOffset;
106758         pTerm = &pWC->a[j];
106759         p->cost.used |= pTerm->prereqRight;
106760         if( (pTerm->eOperator & WO_IN)!=0 ){
106761           if( pUsage[i].omit==0 ){
106762             /* Do not attempt to use an IN constraint if the virtual table
106763             ** says that the equivalent EQ constraint cannot be safely omitted.
106764             ** If we do attempt to use such a constraint, some rows might be
106765             ** repeated in the output. */
106766             break;
106767           }
106768           /* A virtual table that is constrained by an IN clause may not
106769           ** consume the ORDER BY clause because (1) the order of IN terms
106770           ** is not necessarily related to the order of output terms and
106771           ** (2) Multiple outputs from a single IN value will not merge
106772           ** together.  */
106773           pIdxInfo->orderByConsumed = 0;
106774         }
106775       }
106776     }
106777     if( i>=pIdxInfo->nConstraint ) break;
106778   }
106779
106780   /* The orderByConsumed signal is only valid if all outer loops collectively
106781   ** generate just a single row of output.
106782   */
106783   if( pIdxInfo->orderByConsumed ){
106784     for(i=0; i<p->i; i++){
106785       if( (p->aLevel[i].plan.wsFlags & WHERE_UNIQUE)==0 ){
106786         pIdxInfo->orderByConsumed = 0;
106787       }
106788     }
106789   }
106790   
106791   /* If there is an ORDER BY clause, and the selected virtual table index
106792   ** does not satisfy it, increase the cost of the scan accordingly. This
106793   ** matches the processing for non-virtual tables in bestBtreeIndex().
106794   */
106795   rCost = pIdxInfo->estimatedCost;
106796   if( p->pOrderBy && pIdxInfo->orderByConsumed==0 ){
106797     rCost += estLog(rCost)*rCost;
106798   }
106799
106800   /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
106801   ** inital value of lowestCost in this loop. If it is, then the
106802   ** (cost<lowestCost) test below will never be true.
106803   ** 
106804   ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT 
106805   ** is defined.
106806   */
106807   if( (SQLITE_BIG_DBL/((double)2))<rCost ){
106808     p->cost.rCost = (SQLITE_BIG_DBL/((double)2));
106809   }else{
106810     p->cost.rCost = rCost;
106811   }
106812   p->cost.plan.u.pVtabIdx = pIdxInfo;
106813   if( pIdxInfo->orderByConsumed ){
106814     p->cost.plan.wsFlags |= WHERE_ORDERED;
106815     p->cost.plan.nOBSat = nOrderBy;
106816   }else{
106817     p->cost.plan.nOBSat = p->i ? p->aLevel[p->i-1].plan.nOBSat : 0;
106818   }
106819   p->cost.plan.nEq = 0;
106820   pIdxInfo->nOrderBy = nOrderBy;
106821
106822   /* Try to find a more efficient access pattern by using multiple indexes
106823   ** to optimize an OR expression within the WHERE clause. 
106824   */
106825   bestOrClauseIndex(p);
106826 }
106827 #endif /* SQLITE_OMIT_VIRTUALTABLE */
106828
106829 #ifdef SQLITE_ENABLE_STAT3
106830 /*
106831 ** Estimate the location of a particular key among all keys in an
106832 ** index.  Store the results in aStat as follows:
106833 **
106834 **    aStat[0]      Est. number of rows less than pVal
106835 **    aStat[1]      Est. number of rows equal to pVal
106836 **
106837 ** Return SQLITE_OK on success.
106838 */
106839 static int whereKeyStats(
106840   Parse *pParse,              /* Database connection */
106841   Index *pIdx,                /* Index to consider domain of */
106842   sqlite3_value *pVal,        /* Value to consider */
106843   int roundUp,                /* Round up if true.  Round down if false */
106844   tRowcnt *aStat              /* OUT: stats written here */
106845 ){
106846   tRowcnt n;
106847   IndexSample *aSample;
106848   int i, eType;
106849   int isEq = 0;
106850   i64 v;
106851   double r, rS;
106852
106853   assert( roundUp==0 || roundUp==1 );
106854   assert( pIdx->nSample>0 );
106855   if( pVal==0 ) return SQLITE_ERROR;
106856   n = pIdx->aiRowEst[0];
106857   aSample = pIdx->aSample;
106858   eType = sqlite3_value_type(pVal);
106859
106860   if( eType==SQLITE_INTEGER ){
106861     v = sqlite3_value_int64(pVal);
106862     r = (i64)v;
106863     for(i=0; i<pIdx->nSample; i++){
106864       if( aSample[i].eType==SQLITE_NULL ) continue;
106865       if( aSample[i].eType>=SQLITE_TEXT ) break;
106866       if( aSample[i].eType==SQLITE_INTEGER ){
106867         if( aSample[i].u.i>=v ){
106868           isEq = aSample[i].u.i==v;
106869           break;
106870         }
106871       }else{
106872         assert( aSample[i].eType==SQLITE_FLOAT );
106873         if( aSample[i].u.r>=r ){
106874           isEq = aSample[i].u.r==r;
106875           break;
106876         }
106877       }
106878     }
106879   }else if( eType==SQLITE_FLOAT ){
106880     r = sqlite3_value_double(pVal);
106881     for(i=0; i<pIdx->nSample; i++){
106882       if( aSample[i].eType==SQLITE_NULL ) continue;
106883       if( aSample[i].eType>=SQLITE_TEXT ) break;
106884       if( aSample[i].eType==SQLITE_FLOAT ){
106885         rS = aSample[i].u.r;
106886       }else{
106887         rS = aSample[i].u.i;
106888       }
106889       if( rS>=r ){
106890         isEq = rS==r;
106891         break;
106892       }
106893     }
106894   }else if( eType==SQLITE_NULL ){
106895     i = 0;
106896     if( aSample[0].eType==SQLITE_NULL ) isEq = 1;
106897   }else{
106898     assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
106899     for(i=0; i<pIdx->nSample; i++){
106900       if( aSample[i].eType==SQLITE_TEXT || aSample[i].eType==SQLITE_BLOB ){
106901         break;
106902       }
106903     }
106904     if( i<pIdx->nSample ){      
106905       sqlite3 *db = pParse->db;
106906       CollSeq *pColl;
106907       const u8 *z;
106908       if( eType==SQLITE_BLOB ){
106909         z = (const u8 *)sqlite3_value_blob(pVal);
106910         pColl = db->pDfltColl;
106911         assert( pColl->enc==SQLITE_UTF8 );
106912       }else{
106913         pColl = sqlite3GetCollSeq(pParse, SQLITE_UTF8, 0, *pIdx->azColl);
106914         if( pColl==0 ){
106915           return SQLITE_ERROR;
106916         }
106917         z = (const u8 *)sqlite3ValueText(pVal, pColl->enc);
106918         if( !z ){
106919           return SQLITE_NOMEM;
106920         }
106921         assert( z && pColl && pColl->xCmp );
106922       }
106923       n = sqlite3ValueBytes(pVal, pColl->enc);
106924   
106925       for(; i<pIdx->nSample; i++){
106926         int c;
106927         int eSampletype = aSample[i].eType;
106928         if( eSampletype<eType ) continue;
106929         if( eSampletype!=eType ) break;
106930 #ifndef SQLITE_OMIT_UTF16
106931         if( pColl->enc!=SQLITE_UTF8 ){
106932           int nSample;
106933           char *zSample = sqlite3Utf8to16(
106934               db, pColl->enc, aSample[i].u.z, aSample[i].nByte, &nSample
106935           );
106936           if( !zSample ){
106937             assert( db->mallocFailed );
106938             return SQLITE_NOMEM;
106939           }
106940           c = pColl->xCmp(pColl->pUser, nSample, zSample, n, z);
106941           sqlite3DbFree(db, zSample);
106942         }else
106943 #endif
106944         {
106945           c = pColl->xCmp(pColl->pUser, aSample[i].nByte, aSample[i].u.z, n, z);
106946         }
106947         if( c>=0 ){
106948           if( c==0 ) isEq = 1;
106949           break;
106950         }
106951       }
106952     }
106953   }
106954
106955   /* At this point, aSample[i] is the first sample that is greater than
106956   ** or equal to pVal.  Or if i==pIdx->nSample, then all samples are less
106957   ** than pVal.  If aSample[i]==pVal, then isEq==1.
106958   */
106959   if( isEq ){
106960     assert( i<pIdx->nSample );
106961     aStat[0] = aSample[i].nLt;
106962     aStat[1] = aSample[i].nEq;
106963   }else{
106964     tRowcnt iLower, iUpper, iGap;
106965     if( i==0 ){
106966       iLower = 0;
106967       iUpper = aSample[0].nLt;
106968     }else{
106969       iUpper = i>=pIdx->nSample ? n : aSample[i].nLt;
106970       iLower = aSample[i-1].nEq + aSample[i-1].nLt;
106971     }
106972     aStat[1] = pIdx->avgEq;
106973     if( iLower>=iUpper ){
106974       iGap = 0;
106975     }else{
106976       iGap = iUpper - iLower;
106977     }
106978     if( roundUp ){
106979       iGap = (iGap*2)/3;
106980     }else{
106981       iGap = iGap/3;
106982     }
106983     aStat[0] = iLower + iGap;
106984   }
106985   return SQLITE_OK;
106986 }
106987 #endif /* SQLITE_ENABLE_STAT3 */
106988
106989 /*
106990 ** If expression pExpr represents a literal value, set *pp to point to
106991 ** an sqlite3_value structure containing the same value, with affinity
106992 ** aff applied to it, before returning. It is the responsibility of the 
106993 ** caller to eventually release this structure by passing it to 
106994 ** sqlite3ValueFree().
106995 **
106996 ** If the current parse is a recompile (sqlite3Reprepare()) and pExpr
106997 ** is an SQL variable that currently has a non-NULL value bound to it,
106998 ** create an sqlite3_value structure containing this value, again with
106999 ** affinity aff applied to it, instead.
107000 **
107001 ** If neither of the above apply, set *pp to NULL.
107002 **
107003 ** If an error occurs, return an error code. Otherwise, SQLITE_OK.
107004 */
107005 #ifdef SQLITE_ENABLE_STAT3
107006 static int valueFromExpr(
107007   Parse *pParse, 
107008   Expr *pExpr, 
107009   u8 aff, 
107010   sqlite3_value **pp
107011 ){
107012   if( pExpr->op==TK_VARIABLE
107013    || (pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
107014   ){
107015     int iVar = pExpr->iColumn;
107016     sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
107017     *pp = sqlite3VdbeGetValue(pParse->pReprepare, iVar, aff);
107018     return SQLITE_OK;
107019   }
107020   return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp);
107021 }
107022 #endif
107023
107024 /*
107025 ** This function is used to estimate the number of rows that will be visited
107026 ** by scanning an index for a range of values. The range may have an upper
107027 ** bound, a lower bound, or both. The WHERE clause terms that set the upper
107028 ** and lower bounds are represented by pLower and pUpper respectively. For
107029 ** example, assuming that index p is on t1(a):
107030 **
107031 **   ... FROM t1 WHERE a > ? AND a < ? ...
107032 **                    |_____|   |_____|
107033 **                       |         |
107034 **                     pLower    pUpper
107035 **
107036 ** If either of the upper or lower bound is not present, then NULL is passed in
107037 ** place of the corresponding WhereTerm.
107038 **
107039 ** The nEq parameter is passed the index of the index column subject to the
107040 ** range constraint. Or, equivalently, the number of equality constraints
107041 ** optimized by the proposed index scan. For example, assuming index p is
107042 ** on t1(a, b), and the SQL query is:
107043 **
107044 **   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
107045 **
107046 ** then nEq should be passed the value 1 (as the range restricted column,
107047 ** b, is the second left-most column of the index). Or, if the query is:
107048 **
107049 **   ... FROM t1 WHERE a > ? AND a < ? ...
107050 **
107051 ** then nEq should be passed 0.
107052 **
107053 ** The returned value is an integer divisor to reduce the estimated
107054 ** search space.  A return value of 1 means that range constraints are
107055 ** no help at all.  A return value of 2 means range constraints are
107056 ** expected to reduce the search space by half.  And so forth...
107057 **
107058 ** In the absence of sqlite_stat3 ANALYZE data, each range inequality
107059 ** reduces the search space by a factor of 4.  Hence a single constraint (x>?)
107060 ** results in a return of 4 and a range constraint (x>? AND x<?) results
107061 ** in a return of 16.
107062 */
107063 static int whereRangeScanEst(
107064   Parse *pParse,       /* Parsing & code generating context */
107065   Index *p,            /* The index containing the range-compared column; "x" */
107066   int nEq,             /* index into p->aCol[] of the range-compared column */
107067   WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
107068   WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
107069   double *pRangeDiv   /* OUT: Reduce search space by this divisor */
107070 ){
107071   int rc = SQLITE_OK;
107072
107073 #ifdef SQLITE_ENABLE_STAT3
107074
107075   if( nEq==0 && p->nSample ){
107076     sqlite3_value *pRangeVal;
107077     tRowcnt iLower = 0;
107078     tRowcnt iUpper = p->aiRowEst[0];
107079     tRowcnt a[2];
107080     u8 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
107081
107082     if( pLower ){
107083       Expr *pExpr = pLower->pExpr->pRight;
107084       rc = valueFromExpr(pParse, pExpr, aff, &pRangeVal);
107085       assert( (pLower->eOperator & (WO_GT|WO_GE))!=0 );
107086       if( rc==SQLITE_OK
107087        && whereKeyStats(pParse, p, pRangeVal, 0, a)==SQLITE_OK
107088       ){
107089         iLower = a[0];
107090         if( (pLower->eOperator & WO_GT)!=0 ) iLower += a[1];
107091       }
107092       sqlite3ValueFree(pRangeVal);
107093     }
107094     if( rc==SQLITE_OK && pUpper ){
107095       Expr *pExpr = pUpper->pExpr->pRight;
107096       rc = valueFromExpr(pParse, pExpr, aff, &pRangeVal);
107097       assert( (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
107098       if( rc==SQLITE_OK
107099        && whereKeyStats(pParse, p, pRangeVal, 1, a)==SQLITE_OK
107100       ){
107101         iUpper = a[0];
107102         if( (pUpper->eOperator & WO_LE)!=0 ) iUpper += a[1];
107103       }
107104       sqlite3ValueFree(pRangeVal);
107105     }
107106     if( rc==SQLITE_OK ){
107107       if( iUpper<=iLower ){
107108         *pRangeDiv = (double)p->aiRowEst[0];
107109       }else{
107110         *pRangeDiv = (double)p->aiRowEst[0]/(double)(iUpper - iLower);
107111       }
107112       WHERETRACE(("range scan regions: %u..%u  div=%g\n",
107113                   (u32)iLower, (u32)iUpper, *pRangeDiv));
107114       return SQLITE_OK;
107115     }
107116   }
107117 #else
107118   UNUSED_PARAMETER(pParse);
107119   UNUSED_PARAMETER(p);
107120   UNUSED_PARAMETER(nEq);
107121 #endif
107122   assert( pLower || pUpper );
107123   *pRangeDiv = (double)1;
107124   if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ) *pRangeDiv *= (double)4;
107125   if( pUpper ) *pRangeDiv *= (double)4;
107126   return rc;
107127 }
107128
107129 #ifdef SQLITE_ENABLE_STAT3
107130 /*
107131 ** Estimate the number of rows that will be returned based on
107132 ** an equality constraint x=VALUE and where that VALUE occurs in
107133 ** the histogram data.  This only works when x is the left-most
107134 ** column of an index and sqlite_stat3 histogram data is available
107135 ** for that index.  When pExpr==NULL that means the constraint is
107136 ** "x IS NULL" instead of "x=VALUE".
107137 **
107138 ** Write the estimated row count into *pnRow and return SQLITE_OK. 
107139 ** If unable to make an estimate, leave *pnRow unchanged and return
107140 ** non-zero.
107141 **
107142 ** This routine can fail if it is unable to load a collating sequence
107143 ** required for string comparison, or if unable to allocate memory
107144 ** for a UTF conversion required for comparison.  The error is stored
107145 ** in the pParse structure.
107146 */
107147 static int whereEqualScanEst(
107148   Parse *pParse,       /* Parsing & code generating context */
107149   Index *p,            /* The index whose left-most column is pTerm */
107150   Expr *pExpr,         /* Expression for VALUE in the x=VALUE constraint */
107151   double *pnRow        /* Write the revised row estimate here */
107152 ){
107153   sqlite3_value *pRhs = 0;  /* VALUE on right-hand side of pTerm */
107154   u8 aff;                   /* Column affinity */
107155   int rc;                   /* Subfunction return code */
107156   tRowcnt a[2];             /* Statistics */
107157
107158   assert( p->aSample!=0 );
107159   assert( p->nSample>0 );
107160   aff = p->pTable->aCol[p->aiColumn[0]].affinity;
107161   if( pExpr ){
107162     rc = valueFromExpr(pParse, pExpr, aff, &pRhs);
107163     if( rc ) goto whereEqualScanEst_cancel;
107164   }else{
107165     pRhs = sqlite3ValueNew(pParse->db);
107166   }
107167   if( pRhs==0 ) return SQLITE_NOTFOUND;
107168   rc = whereKeyStats(pParse, p, pRhs, 0, a);
107169   if( rc==SQLITE_OK ){
107170     WHERETRACE(("equality scan regions: %d\n", (int)a[1]));
107171     *pnRow = a[1];
107172   }
107173 whereEqualScanEst_cancel:
107174   sqlite3ValueFree(pRhs);
107175   return rc;
107176 }
107177 #endif /* defined(SQLITE_ENABLE_STAT3) */
107178
107179 #ifdef SQLITE_ENABLE_STAT3
107180 /*
107181 ** Estimate the number of rows that will be returned based on
107182 ** an IN constraint where the right-hand side of the IN operator
107183 ** is a list of values.  Example:
107184 **
107185 **        WHERE x IN (1,2,3,4)
107186 **
107187 ** Write the estimated row count into *pnRow and return SQLITE_OK. 
107188 ** If unable to make an estimate, leave *pnRow unchanged and return
107189 ** non-zero.
107190 **
107191 ** This routine can fail if it is unable to load a collating sequence
107192 ** required for string comparison, or if unable to allocate memory
107193 ** for a UTF conversion required for comparison.  The error is stored
107194 ** in the pParse structure.
107195 */
107196 static int whereInScanEst(
107197   Parse *pParse,       /* Parsing & code generating context */
107198   Index *p,            /* The index whose left-most column is pTerm */
107199   ExprList *pList,     /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
107200   double *pnRow        /* Write the revised row estimate here */
107201 ){
107202   int rc = SQLITE_OK;         /* Subfunction return code */
107203   double nEst;                /* Number of rows for a single term */
107204   double nRowEst = (double)0; /* New estimate of the number of rows */
107205   int i;                      /* Loop counter */
107206
107207   assert( p->aSample!=0 );
107208   for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
107209     nEst = p->aiRowEst[0];
107210     rc = whereEqualScanEst(pParse, p, pList->a[i].pExpr, &nEst);
107211     nRowEst += nEst;
107212   }
107213   if( rc==SQLITE_OK ){
107214     if( nRowEst > p->aiRowEst[0] ) nRowEst = p->aiRowEst[0];
107215     *pnRow = nRowEst;
107216     WHERETRACE(("IN row estimate: est=%g\n", nRowEst));
107217   }
107218   return rc;
107219 }
107220 #endif /* defined(SQLITE_ENABLE_STAT3) */
107221
107222 /*
107223 ** Check to see if column iCol of the table with cursor iTab will appear
107224 ** in sorted order according to the current query plan.
107225 **
107226 ** Return values:
107227 **
107228 **    0   iCol is not ordered
107229 **    1   iCol has only a single value
107230 **    2   iCol is in ASC order
107231 **    3   iCol is in DESC order
107232 */
107233 static int isOrderedColumn(
107234   WhereBestIdx *p,
107235   int iTab,
107236   int iCol
107237 ){
107238   int i, j;
107239   WhereLevel *pLevel = &p->aLevel[p->i-1];
107240   Index *pIdx;
107241   u8 sortOrder;
107242   for(i=p->i-1; i>=0; i--, pLevel--){
107243     if( pLevel->iTabCur!=iTab ) continue;
107244     if( (pLevel->plan.wsFlags & WHERE_ALL_UNIQUE)!=0 ){
107245       return 1;
107246     }
107247     assert( (pLevel->plan.wsFlags & WHERE_ORDERED)!=0 );
107248     if( (pIdx = pLevel->plan.u.pIdx)!=0 ){
107249       if( iCol<0 ){
107250         sortOrder = 0;
107251         testcase( (pLevel->plan.wsFlags & WHERE_REVERSE)!=0 );
107252       }else{
107253         int n = pIdx->nColumn;
107254         for(j=0; j<n; j++){
107255           if( iCol==pIdx->aiColumn[j] ) break;
107256         }
107257         if( j>=n ) return 0;
107258         sortOrder = pIdx->aSortOrder[j];
107259         testcase( (pLevel->plan.wsFlags & WHERE_REVERSE)!=0 );
107260       }
107261     }else{
107262       if( iCol!=(-1) ) return 0;
107263       sortOrder = 0;
107264       testcase( (pLevel->plan.wsFlags & WHERE_REVERSE)!=0 );
107265     }
107266     if( (pLevel->plan.wsFlags & WHERE_REVERSE)!=0 ){
107267       assert( sortOrder==0 || sortOrder==1 );
107268       testcase( sortOrder==1 );
107269       sortOrder = 1 - sortOrder;
107270     }
107271     return sortOrder+2;
107272   }
107273   return 0;
107274 }
107275
107276 /*
107277 ** This routine decides if pIdx can be used to satisfy the ORDER BY
107278 ** clause, either in whole or in part.  The return value is the 
107279 ** cumulative number of terms in the ORDER BY clause that are satisfied
107280 ** by the index pIdx and other indices in outer loops.
107281 **
107282 ** The table being queried has a cursor number of "base".  pIdx is the
107283 ** index that is postulated for use to access the table.
107284 **
107285 ** The *pbRev value is set to 0 order 1 depending on whether or not
107286 ** pIdx should be run in the forward order or in reverse order.
107287 */
107288 static int isSortingIndex(
107289   WhereBestIdx *p,    /* Best index search context */
107290   Index *pIdx,        /* The index we are testing */
107291   int base,           /* Cursor number for the table to be sorted */
107292   int *pbRev,         /* Set to 1 for reverse-order scan of pIdx */
107293   int *pbObUnique     /* ORDER BY column values will different in every row */
107294 ){
107295   int i;                        /* Number of pIdx terms used */
107296   int j;                        /* Number of ORDER BY terms satisfied */
107297   int sortOrder = 2;            /* 0: forward.  1: backward.  2: unknown */
107298   int nTerm;                    /* Number of ORDER BY terms */
107299   struct ExprList_item *pOBItem;/* A term of the ORDER BY clause */
107300   Table *pTab = pIdx->pTable;   /* Table that owns index pIdx */
107301   ExprList *pOrderBy;           /* The ORDER BY clause */
107302   Parse *pParse = p->pParse;    /* Parser context */
107303   sqlite3 *db = pParse->db;     /* Database connection */
107304   int nPriorSat;                /* ORDER BY terms satisfied by outer loops */
107305   int seenRowid = 0;            /* True if an ORDER BY rowid term is seen */
107306   int uniqueNotNull;            /* pIdx is UNIQUE with all terms are NOT NULL */
107307   int outerObUnique;            /* Outer loops generate different values in
107308                                 ** every row for the ORDER BY columns */
107309
107310   if( p->i==0 ){
107311     nPriorSat = 0;
107312     outerObUnique = 1;
107313   }else{
107314     u32 wsFlags = p->aLevel[p->i-1].plan.wsFlags;
107315     nPriorSat = p->aLevel[p->i-1].plan.nOBSat;
107316     if( (wsFlags & WHERE_ORDERED)==0 ){
107317       /* This loop cannot be ordered unless the next outer loop is
107318       ** also ordered */
107319       return nPriorSat;
107320     }
107321     if( OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ){
107322       /* Only look at the outer-most loop if the OrderByIdxJoin
107323       ** optimization is disabled */
107324       return nPriorSat;
107325     }
107326     testcase( wsFlags & WHERE_OB_UNIQUE );
107327     testcase( wsFlags & WHERE_ALL_UNIQUE );
107328     outerObUnique = (wsFlags & (WHERE_OB_UNIQUE|WHERE_ALL_UNIQUE))!=0;
107329   }
107330   pOrderBy = p->pOrderBy;
107331   assert( pOrderBy!=0 );
107332   if( pIdx->bUnordered ){
107333     /* Hash indices (indicated by the "unordered" tag on sqlite_stat1) cannot
107334     ** be used for sorting */
107335     return nPriorSat;
107336   }
107337   nTerm = pOrderBy->nExpr;
107338   uniqueNotNull = pIdx->onError!=OE_None;
107339   assert( nTerm>0 );
107340
107341   /* Argument pIdx must either point to a 'real' named index structure, 
107342   ** or an index structure allocated on the stack by bestBtreeIndex() to
107343   ** represent the rowid index that is part of every table.  */
107344   assert( pIdx->zName || (pIdx->nColumn==1 && pIdx->aiColumn[0]==-1) );
107345
107346   /* Match terms of the ORDER BY clause against columns of
107347   ** the index.
107348   **
107349   ** Note that indices have pIdx->nColumn regular columns plus
107350   ** one additional column containing the rowid.  The rowid column
107351   ** of the index is also allowed to match against the ORDER BY
107352   ** clause.
107353   */
107354   j = nPriorSat;
107355   for(i=0,pOBItem=&pOrderBy->a[j]; j<nTerm && i<=pIdx->nColumn; i++){
107356     Expr *pOBExpr;          /* The expression of the ORDER BY pOBItem */
107357     CollSeq *pColl;         /* The collating sequence of pOBExpr */
107358     int termSortOrder;      /* Sort order for this term */
107359     int iColumn;            /* The i-th column of the index.  -1 for rowid */
107360     int iSortOrder;         /* 1 for DESC, 0 for ASC on the i-th index term */
107361     int isEq;               /* Subject to an == or IS NULL constraint */
107362     int isMatch;            /* ORDER BY term matches the index term */
107363     const char *zColl;      /* Name of collating sequence for i-th index term */
107364     WhereTerm *pConstraint; /* A constraint in the WHERE clause */
107365
107366     /* If the next term of the ORDER BY clause refers to anything other than
107367     ** a column in the "base" table, then this index will not be of any
107368     ** further use in handling the ORDER BY. */
107369     pOBExpr = sqlite3ExprSkipCollate(pOBItem->pExpr);
107370     if( pOBExpr->op!=TK_COLUMN || pOBExpr->iTable!=base ){
107371       break;
107372     }
107373
107374     /* Find column number and collating sequence for the next entry
107375     ** in the index */
107376     if( pIdx->zName && i<pIdx->nColumn ){
107377       iColumn = pIdx->aiColumn[i];
107378       if( iColumn==pIdx->pTable->iPKey ){
107379         iColumn = -1;
107380       }
107381       iSortOrder = pIdx->aSortOrder[i];
107382       zColl = pIdx->azColl[i];
107383       assert( zColl!=0 );
107384     }else{
107385       iColumn = -1;
107386       iSortOrder = 0;
107387       zColl = 0;
107388     }
107389
107390     /* Check to see if the column number and collating sequence of the
107391     ** index match the column number and collating sequence of the ORDER BY
107392     ** clause entry.  Set isMatch to 1 if they both match. */
107393     if( pOBExpr->iColumn==iColumn ){
107394       if( zColl ){
107395         pColl = sqlite3ExprCollSeq(pParse, pOBItem->pExpr);
107396         if( !pColl ) pColl = db->pDfltColl;
107397         isMatch = sqlite3StrICmp(pColl->zName, zColl)==0;
107398       }else{
107399         isMatch = 1;
107400       }
107401     }else{
107402       isMatch = 0;
107403     }
107404
107405     /* termSortOrder is 0 or 1 for whether or not the access loop should
107406     ** run forward or backwards (respectively) in order to satisfy this 
107407     ** term of the ORDER BY clause. */
107408     assert( pOBItem->sortOrder==0 || pOBItem->sortOrder==1 );
107409     assert( iSortOrder==0 || iSortOrder==1 );
107410     termSortOrder = iSortOrder ^ pOBItem->sortOrder;
107411
107412     /* If X is the column in the index and ORDER BY clause, check to see
107413     ** if there are any X= or X IS NULL constraints in the WHERE clause. */
107414     pConstraint = findTerm(p->pWC, base, iColumn, p->notReady,
107415                            WO_EQ|WO_ISNULL|WO_IN, pIdx);
107416     if( pConstraint==0 ){
107417       isEq = 0;
107418     }else if( (pConstraint->eOperator & WO_IN)!=0 ){
107419       isEq = 0;
107420     }else if( (pConstraint->eOperator & WO_ISNULL)!=0 ){
107421       uniqueNotNull = 0;
107422       isEq = 1;  /* "X IS NULL" means X has only a single value */
107423     }else if( pConstraint->prereqRight==0 ){
107424       isEq = 1;  /* Constraint "X=constant" means X has only a single value */
107425     }else{
107426       Expr *pRight = pConstraint->pExpr->pRight;
107427       if( pRight->op==TK_COLUMN ){
107428         WHERETRACE(("       .. isOrderedColumn(tab=%d,col=%d)",
107429                     pRight->iTable, pRight->iColumn));
107430         isEq = isOrderedColumn(p, pRight->iTable, pRight->iColumn);
107431         WHERETRACE((" -> isEq=%d\n", isEq));
107432
107433         /* If the constraint is of the form X=Y where Y is an ordered value
107434         ** in an outer loop, then make sure the sort order of Y matches the
107435         ** sort order required for X. */
107436         if( isMatch && isEq>=2 && isEq!=pOBItem->sortOrder+2 ){
107437           testcase( isEq==2 );
107438           testcase( isEq==3 );
107439           break;
107440         }
107441       }else{
107442         isEq = 0;  /* "X=expr" places no ordering constraints on X */
107443       }
107444     }
107445     if( !isMatch ){
107446       if( isEq==0 ){
107447         break;
107448       }else{
107449         continue;
107450       }
107451     }else if( isEq!=1 ){
107452       if( sortOrder==2 ){
107453         sortOrder = termSortOrder;
107454       }else if( termSortOrder!=sortOrder ){
107455         break;
107456       }
107457     }
107458     j++;
107459     pOBItem++;
107460     if( iColumn<0 ){
107461       seenRowid = 1;
107462       break;
107463     }else if( pTab->aCol[iColumn].notNull==0 && isEq!=1 ){
107464       testcase( isEq==0 );
107465       testcase( isEq==2 );
107466       testcase( isEq==3 );
107467       uniqueNotNull = 0;
107468     }
107469   }
107470   if( seenRowid ){
107471     uniqueNotNull = 1;
107472   }else if( uniqueNotNull==0 || i<pIdx->nColumn ){
107473     uniqueNotNull = 0;
107474   }
107475
107476   /* If we have not found at least one ORDER BY term that matches the
107477   ** index, then show no progress. */
107478   if( pOBItem==&pOrderBy->a[nPriorSat] ) return nPriorSat;
107479
107480   /* Either the outer queries must generate rows where there are no two
107481   ** rows with the same values in all ORDER BY columns, or else this
107482   ** loop must generate just a single row of output.  Example:  Suppose
107483   ** the outer loops generate A=1 and A=1, and this loop generates B=3
107484   ** and B=4.  Then without the following test, ORDER BY A,B would 
107485   ** generate the wrong order output: 1,3 1,4 1,3 1,4
107486   */
107487   if( outerObUnique==0 && uniqueNotNull==0 ) return nPriorSat;
107488   *pbObUnique = uniqueNotNull;
107489
107490   /* Return the necessary scan order back to the caller */
107491   *pbRev = sortOrder & 1;
107492
107493   /* If there was an "ORDER BY rowid" term that matched, or it is only
107494   ** possible for a single row from this table to match, then skip over
107495   ** any additional ORDER BY terms dealing with this table.
107496   */
107497   if( uniqueNotNull ){
107498     /* Advance j over additional ORDER BY terms associated with base */
107499     WhereMaskSet *pMS = p->pWC->pMaskSet;
107500     Bitmask m = ~getMask(pMS, base);
107501     while( j<nTerm && (exprTableUsage(pMS, pOrderBy->a[j].pExpr)&m)==0 ){
107502       j++;
107503     }
107504   }
107505   return j;
107506 }
107507
107508 /*
107509 ** Find the best query plan for accessing a particular table.  Write the
107510 ** best query plan and its cost into the p->cost.
107511 **
107512 ** The lowest cost plan wins.  The cost is an estimate of the amount of
107513 ** CPU and disk I/O needed to process the requested result.
107514 ** Factors that influence cost include:
107515 **
107516 **    *  The estimated number of rows that will be retrieved.  (The
107517 **       fewer the better.)
107518 **
107519 **    *  Whether or not sorting must occur.
107520 **
107521 **    *  Whether or not there must be separate lookups in the
107522 **       index and in the main table.
107523 **
107524 ** If there was an INDEXED BY clause (pSrc->pIndex) attached to the table in
107525 ** the SQL statement, then this function only considers plans using the 
107526 ** named index. If no such plan is found, then the returned cost is
107527 ** SQLITE_BIG_DBL. If a plan is found that uses the named index, 
107528 ** then the cost is calculated in the usual way.
107529 **
107530 ** If a NOT INDEXED clause was attached to the table 
107531 ** in the SELECT statement, then no indexes are considered. However, the 
107532 ** selected plan may still take advantage of the built-in rowid primary key
107533 ** index.
107534 */
107535 static void bestBtreeIndex(WhereBestIdx *p){
107536   Parse *pParse = p->pParse;  /* The parsing context */
107537   WhereClause *pWC = p->pWC;  /* The WHERE clause */
107538   struct SrcList_item *pSrc = p->pSrc; /* The FROM clause term to search */
107539   int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
107540   Index *pProbe;              /* An index we are evaluating */
107541   Index *pIdx;                /* Copy of pProbe, or zero for IPK index */
107542   int eqTermMask;             /* Current mask of valid equality operators */
107543   int idxEqTermMask;          /* Index mask of valid equality operators */
107544   Index sPk;                  /* A fake index object for the primary key */
107545   tRowcnt aiRowEstPk[2];      /* The aiRowEst[] value for the sPk index */
107546   int aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
107547   int wsFlagMask;             /* Allowed flags in p->cost.plan.wsFlag */
107548   int nPriorSat;              /* ORDER BY terms satisfied by outer loops */
107549   int nOrderBy;               /* Number of ORDER BY terms */
107550   char bSortInit;             /* Initializer for bSort in inner loop */
107551   char bDistInit;             /* Initializer for bDist in inner loop */
107552
107553
107554   /* Initialize the cost to a worst-case value */
107555   memset(&p->cost, 0, sizeof(p->cost));
107556   p->cost.rCost = SQLITE_BIG_DBL;
107557
107558   /* If the pSrc table is the right table of a LEFT JOIN then we may not
107559   ** use an index to satisfy IS NULL constraints on that table.  This is
107560   ** because columns might end up being NULL if the table does not match -
107561   ** a circumstance which the index cannot help us discover.  Ticket #2177.
107562   */
107563   if( pSrc->jointype & JT_LEFT ){
107564     idxEqTermMask = WO_EQ|WO_IN;
107565   }else{
107566     idxEqTermMask = WO_EQ|WO_IN|WO_ISNULL;
107567   }
107568
107569   if( pSrc->pIndex ){
107570     /* An INDEXED BY clause specifies a particular index to use */
107571     pIdx = pProbe = pSrc->pIndex;
107572     wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
107573     eqTermMask = idxEqTermMask;
107574   }else{
107575     /* There is no INDEXED BY clause.  Create a fake Index object in local
107576     ** variable sPk to represent the rowid primary key index.  Make this
107577     ** fake index the first in a chain of Index objects with all of the real
107578     ** indices to follow */
107579     Index *pFirst;                  /* First of real indices on the table */
107580     memset(&sPk, 0, sizeof(Index));
107581     sPk.nColumn = 1;
107582     sPk.aiColumn = &aiColumnPk;
107583     sPk.aiRowEst = aiRowEstPk;
107584     sPk.onError = OE_Replace;
107585     sPk.pTable = pSrc->pTab;
107586     aiRowEstPk[0] = pSrc->pTab->nRowEst;
107587     aiRowEstPk[1] = 1;
107588     pFirst = pSrc->pTab->pIndex;
107589     if( pSrc->notIndexed==0 ){
107590       /* The real indices of the table are only considered if the
107591       ** NOT INDEXED qualifier is omitted from the FROM clause */
107592       sPk.pNext = pFirst;
107593     }
107594     pProbe = &sPk;
107595     wsFlagMask = ~(
107596         WHERE_COLUMN_IN|WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_RANGE
107597     );
107598     eqTermMask = WO_EQ|WO_IN;
107599     pIdx = 0;
107600   }
107601
107602   nOrderBy = p->pOrderBy ? p->pOrderBy->nExpr : 0;
107603   if( p->i ){
107604     nPriorSat = p->aLevel[p->i-1].plan.nOBSat;
107605     bSortInit = nPriorSat<nOrderBy;
107606     bDistInit = 0;
107607   }else{
107608     nPriorSat = 0;
107609     bSortInit = nOrderBy>0;
107610     bDistInit = p->pDistinct!=0;
107611   }
107612
107613   /* Loop over all indices looking for the best one to use
107614   */
107615   for(; pProbe; pIdx=pProbe=pProbe->pNext){
107616     const tRowcnt * const aiRowEst = pProbe->aiRowEst;
107617     WhereCost pc;               /* Cost of using pProbe */
107618     double log10N = (double)1;  /* base-10 logarithm of nRow (inexact) */
107619
107620     /* The following variables are populated based on the properties of
107621     ** index being evaluated. They are then used to determine the expected
107622     ** cost and number of rows returned.
107623     **
107624     **  pc.plan.nEq: 
107625     **    Number of equality terms that can be implemented using the index.
107626     **    In other words, the number of initial fields in the index that
107627     **    are used in == or IN or NOT NULL constraints of the WHERE clause.
107628     **
107629     **  nInMul:  
107630     **    The "in-multiplier". This is an estimate of how many seek operations 
107631     **    SQLite must perform on the index in question. For example, if the 
107632     **    WHERE clause is:
107633     **
107634     **      WHERE a IN (1, 2, 3) AND b IN (4, 5, 6)
107635     **
107636     **    SQLite must perform 9 lookups on an index on (a, b), so nInMul is 
107637     **    set to 9. Given the same schema and either of the following WHERE 
107638     **    clauses:
107639     **
107640     **      WHERE a =  1
107641     **      WHERE a >= 2
107642     **
107643     **    nInMul is set to 1.
107644     **
107645     **    If there exists a WHERE term of the form "x IN (SELECT ...)", then 
107646     **    the sub-select is assumed to return 25 rows for the purposes of 
107647     **    determining nInMul.
107648     **
107649     **  bInEst:  
107650     **    Set to true if there was at least one "x IN (SELECT ...)" term used 
107651     **    in determining the value of nInMul.  Note that the RHS of the
107652     **    IN operator must be a SELECT, not a value list, for this variable
107653     **    to be true.
107654     **
107655     **  rangeDiv:
107656     **    An estimate of a divisor by which to reduce the search space due
107657     **    to inequality constraints.  In the absence of sqlite_stat3 ANALYZE
107658     **    data, a single inequality reduces the search space to 1/4rd its
107659     **    original size (rangeDiv==4).  Two inequalities reduce the search
107660     **    space to 1/16th of its original size (rangeDiv==16).
107661     **
107662     **  bSort:   
107663     **    Boolean. True if there is an ORDER BY clause that will require an 
107664     **    external sort (i.e. scanning the index being evaluated will not 
107665     **    correctly order records).
107666     **
107667     **  bDist:
107668     **    Boolean. True if there is a DISTINCT clause that will require an 
107669     **    external btree.
107670     **
107671     **  bLookup: 
107672     **    Boolean. True if a table lookup is required for each index entry
107673     **    visited.  In other words, true if this is not a covering index.
107674     **    This is always false for the rowid primary key index of a table.
107675     **    For other indexes, it is true unless all the columns of the table
107676     **    used by the SELECT statement are present in the index (such an
107677     **    index is sometimes described as a covering index).
107678     **    For example, given the index on (a, b), the second of the following 
107679     **    two queries requires table b-tree lookups in order to find the value
107680     **    of column c, but the first does not because columns a and b are
107681     **    both available in the index.
107682     **
107683     **             SELECT a, b    FROM tbl WHERE a = 1;
107684     **             SELECT a, b, c FROM tbl WHERE a = 1;
107685     */
107686     int bInEst = 0;               /* True if "x IN (SELECT...)" seen */
107687     int nInMul = 1;               /* Number of distinct equalities to lookup */
107688     double rangeDiv = (double)1;  /* Estimated reduction in search space */
107689     int nBound = 0;               /* Number of range constraints seen */
107690     char bSort = bSortInit;       /* True if external sort required */
107691     char bDist = bDistInit;       /* True if index cannot help with DISTINCT */
107692     char bLookup = 0;             /* True if not a covering index */
107693     WhereTerm *pTerm;             /* A single term of the WHERE clause */
107694 #ifdef SQLITE_ENABLE_STAT3
107695     WhereTerm *pFirstTerm = 0;    /* First term matching the index */
107696 #endif
107697
107698     WHERETRACE((
107699       "   %s(%s):\n",
107700       pSrc->pTab->zName, (pIdx ? pIdx->zName : "ipk")
107701     ));
107702     memset(&pc, 0, sizeof(pc));
107703     pc.plan.nOBSat = nPriorSat;
107704
107705     /* Determine the values of pc.plan.nEq and nInMul */
107706     for(pc.plan.nEq=0; pc.plan.nEq<pProbe->nColumn; pc.plan.nEq++){
107707       int j = pProbe->aiColumn[pc.plan.nEq];
107708       pTerm = findTerm(pWC, iCur, j, p->notReady, eqTermMask, pIdx);
107709       if( pTerm==0 ) break;
107710       pc.plan.wsFlags |= (WHERE_COLUMN_EQ|WHERE_ROWID_EQ);
107711       testcase( pTerm->pWC!=pWC );
107712       if( pTerm->eOperator & WO_IN ){
107713         Expr *pExpr = pTerm->pExpr;
107714         pc.plan.wsFlags |= WHERE_COLUMN_IN;
107715         if( ExprHasProperty(pExpr, EP_xIsSelect) ){
107716           /* "x IN (SELECT ...)":  Assume the SELECT returns 25 rows */
107717           nInMul *= 25;
107718           bInEst = 1;
107719         }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
107720           /* "x IN (value, value, ...)" */
107721           nInMul *= pExpr->x.pList->nExpr;
107722         }
107723       }else if( pTerm->eOperator & WO_ISNULL ){
107724         pc.plan.wsFlags |= WHERE_COLUMN_NULL;
107725       }
107726 #ifdef SQLITE_ENABLE_STAT3
107727       if( pc.plan.nEq==0 && pProbe->aSample ) pFirstTerm = pTerm;
107728 #endif
107729       pc.used |= pTerm->prereqRight;
107730     }
107731  
107732     /* If the index being considered is UNIQUE, and there is an equality 
107733     ** constraint for all columns in the index, then this search will find
107734     ** at most a single row. In this case set the WHERE_UNIQUE flag to 
107735     ** indicate this to the caller.
107736     **
107737     ** Otherwise, if the search may find more than one row, test to see if
107738     ** there is a range constraint on indexed column (pc.plan.nEq+1) that
107739     ** can be optimized using the index. 
107740     */
107741     if( pc.plan.nEq==pProbe->nColumn && pProbe->onError!=OE_None ){
107742       testcase( pc.plan.wsFlags & WHERE_COLUMN_IN );
107743       testcase( pc.plan.wsFlags & WHERE_COLUMN_NULL );
107744       if( (pc.plan.wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 ){
107745         pc.plan.wsFlags |= WHERE_UNIQUE;
107746         if( p->i==0 || (p->aLevel[p->i-1].plan.wsFlags & WHERE_ALL_UNIQUE)!=0 ){
107747           pc.plan.wsFlags |= WHERE_ALL_UNIQUE;
107748         }
107749       }
107750     }else if( pProbe->bUnordered==0 ){
107751       int j;
107752       j = (pc.plan.nEq==pProbe->nColumn ? -1 : pProbe->aiColumn[pc.plan.nEq]);
107753       if( findTerm(pWC, iCur, j, p->notReady, WO_LT|WO_LE|WO_GT|WO_GE, pIdx) ){
107754         WhereTerm *pTop, *pBtm;
107755         pTop = findTerm(pWC, iCur, j, p->notReady, WO_LT|WO_LE, pIdx);
107756         pBtm = findTerm(pWC, iCur, j, p->notReady, WO_GT|WO_GE, pIdx);
107757         whereRangeScanEst(pParse, pProbe, pc.plan.nEq, pBtm, pTop, &rangeDiv);
107758         if( pTop ){
107759           nBound = 1;
107760           pc.plan.wsFlags |= WHERE_TOP_LIMIT;
107761           pc.used |= pTop->prereqRight;
107762           testcase( pTop->pWC!=pWC );
107763         }
107764         if( pBtm ){
107765           nBound++;
107766           pc.plan.wsFlags |= WHERE_BTM_LIMIT;
107767           pc.used |= pBtm->prereqRight;
107768           testcase( pBtm->pWC!=pWC );
107769         }
107770         pc.plan.wsFlags |= (WHERE_COLUMN_RANGE|WHERE_ROWID_RANGE);
107771       }
107772     }
107773
107774     /* If there is an ORDER BY clause and the index being considered will
107775     ** naturally scan rows in the required order, set the appropriate flags
107776     ** in pc.plan.wsFlags. Otherwise, if there is an ORDER BY clause but
107777     ** the index will scan rows in a different order, set the bSort
107778     ** variable.  */
107779     if( bSort && (pSrc->jointype & JT_LEFT)==0 ){
107780       int bRev = 2;
107781       int bObUnique = 0;
107782       WHERETRACE(("      --> before isSortIndex: nPriorSat=%d\n",nPriorSat));
107783       pc.plan.nOBSat = isSortingIndex(p, pProbe, iCur, &bRev, &bObUnique);
107784       WHERETRACE(("      --> after  isSortIndex: bRev=%d bObU=%d nOBSat=%d\n",
107785                   bRev, bObUnique, pc.plan.nOBSat));
107786       if( nPriorSat<pc.plan.nOBSat || (pc.plan.wsFlags & WHERE_ALL_UNIQUE)!=0 ){
107787         pc.plan.wsFlags |= WHERE_ORDERED;
107788         if( bObUnique ) pc.plan.wsFlags |= WHERE_OB_UNIQUE;
107789       }
107790       if( nOrderBy==pc.plan.nOBSat ){
107791         bSort = 0;
107792         pc.plan.wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE;
107793       }
107794       if( bRev & 1 ) pc.plan.wsFlags |= WHERE_REVERSE;
107795     }
107796
107797     /* If there is a DISTINCT qualifier and this index will scan rows in
107798     ** order of the DISTINCT expressions, clear bDist and set the appropriate
107799     ** flags in pc.plan.wsFlags. */
107800     if( bDist
107801      && isDistinctIndex(pParse, pWC, pProbe, iCur, p->pDistinct, pc.plan.nEq)
107802      && (pc.plan.wsFlags & WHERE_COLUMN_IN)==0
107803     ){
107804       bDist = 0;
107805       pc.plan.wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_DISTINCT;
107806     }
107807
107808     /* If currently calculating the cost of using an index (not the IPK
107809     ** index), determine if all required column data may be obtained without 
107810     ** using the main table (i.e. if the index is a covering
107811     ** index for this query). If it is, set the WHERE_IDX_ONLY flag in
107812     ** pc.plan.wsFlags. Otherwise, set the bLookup variable to true.  */
107813     if( pIdx ){
107814       Bitmask m = pSrc->colUsed;
107815       int j;
107816       for(j=0; j<pIdx->nColumn; j++){
107817         int x = pIdx->aiColumn[j];
107818         if( x<BMS-1 ){
107819           m &= ~(((Bitmask)1)<<x);
107820         }
107821       }
107822       if( m==0 ){
107823         pc.plan.wsFlags |= WHERE_IDX_ONLY;
107824       }else{
107825         bLookup = 1;
107826       }
107827     }
107828
107829     /*
107830     ** Estimate the number of rows of output.  For an "x IN (SELECT...)"
107831     ** constraint, do not let the estimate exceed half the rows in the table.
107832     */
107833     pc.plan.nRow = (double)(aiRowEst[pc.plan.nEq] * nInMul);
107834     if( bInEst && pc.plan.nRow*2>aiRowEst[0] ){
107835       pc.plan.nRow = aiRowEst[0]/2;
107836       nInMul = (int)(pc.plan.nRow / aiRowEst[pc.plan.nEq]);
107837     }
107838
107839 #ifdef SQLITE_ENABLE_STAT3
107840     /* If the constraint is of the form x=VALUE or x IN (E1,E2,...)
107841     ** and we do not think that values of x are unique and if histogram
107842     ** data is available for column x, then it might be possible
107843     ** to get a better estimate on the number of rows based on
107844     ** VALUE and how common that value is according to the histogram.
107845     */
107846     if( pc.plan.nRow>(double)1 && pc.plan.nEq==1
107847      && pFirstTerm!=0 && aiRowEst[1]>1 ){
107848       assert( (pFirstTerm->eOperator & (WO_EQ|WO_ISNULL|WO_IN))!=0 );
107849       if( pFirstTerm->eOperator & (WO_EQ|WO_ISNULL) ){
107850         testcase( pFirstTerm->eOperator & WO_EQ );
107851         testcase( pFirstTerm->eOperator & WO_EQUIV );
107852         testcase( pFirstTerm->eOperator & WO_ISNULL );
107853         whereEqualScanEst(pParse, pProbe, pFirstTerm->pExpr->pRight,
107854                           &pc.plan.nRow);
107855       }else if( bInEst==0 ){
107856         assert( pFirstTerm->eOperator & WO_IN );
107857         whereInScanEst(pParse, pProbe, pFirstTerm->pExpr->x.pList,
107858                        &pc.plan.nRow);
107859       }
107860     }
107861 #endif /* SQLITE_ENABLE_STAT3 */
107862
107863     /* Adjust the number of output rows and downward to reflect rows
107864     ** that are excluded by range constraints.
107865     */
107866     pc.plan.nRow = pc.plan.nRow/rangeDiv;
107867     if( pc.plan.nRow<1 ) pc.plan.nRow = 1;
107868
107869     /* Experiments run on real SQLite databases show that the time needed
107870     ** to do a binary search to locate a row in a table or index is roughly
107871     ** log10(N) times the time to move from one row to the next row within
107872     ** a table or index.  The actual times can vary, with the size of
107873     ** records being an important factor.  Both moves and searches are
107874     ** slower with larger records, presumably because fewer records fit
107875     ** on one page and hence more pages have to be fetched.
107876     **
107877     ** The ANALYZE command and the sqlite_stat1 and sqlite_stat3 tables do
107878     ** not give us data on the relative sizes of table and index records.
107879     ** So this computation assumes table records are about twice as big
107880     ** as index records
107881     */
107882     if( (pc.plan.wsFlags&~(WHERE_REVERSE|WHERE_ORDERED|WHERE_OB_UNIQUE))
107883                                                               ==WHERE_IDX_ONLY
107884      && (pWC->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
107885      && sqlite3GlobalConfig.bUseCis
107886      && OptimizationEnabled(pParse->db, SQLITE_CoverIdxScan)
107887     ){
107888       /* This index is not useful for indexing, but it is a covering index.
107889       ** A full-scan of the index might be a little faster than a full-scan
107890       ** of the table, so give this case a cost slightly less than a table
107891       ** scan. */
107892       pc.rCost = aiRowEst[0]*3 + pProbe->nColumn;
107893       pc.plan.wsFlags |= WHERE_COVER_SCAN|WHERE_COLUMN_RANGE;
107894     }else if( (pc.plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ){
107895       /* The cost of a full table scan is a number of move operations equal
107896       ** to the number of rows in the table.
107897       **
107898       ** We add an additional 4x penalty to full table scans.  This causes
107899       ** the cost function to err on the side of choosing an index over
107900       ** choosing a full scan.  This 4x full-scan penalty is an arguable
107901       ** decision and one which we expect to revisit in the future.  But
107902       ** it seems to be working well enough at the moment.
107903       */
107904       pc.rCost = aiRowEst[0]*4;
107905       pc.plan.wsFlags &= ~WHERE_IDX_ONLY;
107906       if( pIdx ){
107907         pc.plan.wsFlags &= ~WHERE_ORDERED;
107908         pc.plan.nOBSat = nPriorSat;
107909       }
107910     }else{
107911       log10N = estLog(aiRowEst[0]);
107912       pc.rCost = pc.plan.nRow;
107913       if( pIdx ){
107914         if( bLookup ){
107915           /* For an index lookup followed by a table lookup:
107916           **    nInMul index searches to find the start of each index range
107917           **  + nRow steps through the index
107918           **  + nRow table searches to lookup the table entry using the rowid
107919           */
107920           pc.rCost += (nInMul + pc.plan.nRow)*log10N;
107921         }else{
107922           /* For a covering index:
107923           **     nInMul index searches to find the initial entry 
107924           **   + nRow steps through the index
107925           */
107926           pc.rCost += nInMul*log10N;
107927         }
107928       }else{
107929         /* For a rowid primary key lookup:
107930         **    nInMult table searches to find the initial entry for each range
107931         **  + nRow steps through the table
107932         */
107933         pc.rCost += nInMul*log10N;
107934       }
107935     }
107936
107937     /* Add in the estimated cost of sorting the result.  Actual experimental
107938     ** measurements of sorting performance in SQLite show that sorting time
107939     ** adds C*N*log10(N) to the cost, where N is the number of rows to be 
107940     ** sorted and C is a factor between 1.95 and 4.3.  We will split the
107941     ** difference and select C of 3.0.
107942     */
107943     if( bSort ){
107944       double m = estLog(pc.plan.nRow*(nOrderBy - pc.plan.nOBSat)/nOrderBy);
107945       m *= (double)(pc.plan.nOBSat ? 2 : 3);
107946       pc.rCost += pc.plan.nRow*m;
107947     }
107948     if( bDist ){
107949       pc.rCost += pc.plan.nRow*estLog(pc.plan.nRow)*3;
107950     }
107951
107952     /**** Cost of using this index has now been computed ****/
107953
107954     /* If there are additional constraints on this table that cannot
107955     ** be used with the current index, but which might lower the number
107956     ** of output rows, adjust the nRow value accordingly.  This only 
107957     ** matters if the current index is the least costly, so do not bother
107958     ** with this step if we already know this index will not be chosen.
107959     ** Also, never reduce the output row count below 2 using this step.
107960     **
107961     ** It is critical that the notValid mask be used here instead of
107962     ** the notReady mask.  When computing an "optimal" index, the notReady
107963     ** mask will only have one bit set - the bit for the current table.
107964     ** The notValid mask, on the other hand, always has all bits set for
107965     ** tables that are not in outer loops.  If notReady is used here instead
107966     ** of notValid, then a optimal index that depends on inner joins loops
107967     ** might be selected even when there exists an optimal index that has
107968     ** no such dependency.
107969     */
107970     if( pc.plan.nRow>2 && pc.rCost<=p->cost.rCost ){
107971       int k;                       /* Loop counter */
107972       int nSkipEq = pc.plan.nEq;   /* Number of == constraints to skip */
107973       int nSkipRange = nBound;     /* Number of < constraints to skip */
107974       Bitmask thisTab;             /* Bitmap for pSrc */
107975
107976       thisTab = getMask(pWC->pMaskSet, iCur);
107977       for(pTerm=pWC->a, k=pWC->nTerm; pc.plan.nRow>2 && k; k--, pTerm++){
107978         if( pTerm->wtFlags & TERM_VIRTUAL ) continue;
107979         if( (pTerm->prereqAll & p->notValid)!=thisTab ) continue;
107980         if( pTerm->eOperator & (WO_EQ|WO_IN|WO_ISNULL) ){
107981           if( nSkipEq ){
107982             /* Ignore the first pc.plan.nEq equality matches since the index
107983             ** has already accounted for these */
107984             nSkipEq--;
107985           }else{
107986             /* Assume each additional equality match reduces the result
107987             ** set size by a factor of 10 */
107988             pc.plan.nRow /= 10;
107989           }
107990         }else if( pTerm->eOperator & (WO_LT|WO_LE|WO_GT|WO_GE) ){
107991           if( nSkipRange ){
107992             /* Ignore the first nSkipRange range constraints since the index
107993             ** has already accounted for these */
107994             nSkipRange--;
107995           }else{
107996             /* Assume each additional range constraint reduces the result
107997             ** set size by a factor of 3.  Indexed range constraints reduce
107998             ** the search space by a larger factor: 4.  We make indexed range
107999             ** more selective intentionally because of the subjective 
108000             ** observation that indexed range constraints really are more
108001             ** selective in practice, on average. */
108002             pc.plan.nRow /= 3;
108003           }
108004         }else if( (pTerm->eOperator & WO_NOOP)==0 ){
108005           /* Any other expression lowers the output row count by half */
108006           pc.plan.nRow /= 2;
108007         }
108008       }
108009       if( pc.plan.nRow<2 ) pc.plan.nRow = 2;
108010     }
108011
108012
108013     WHERETRACE((
108014       "      nEq=%d nInMul=%d rangeDiv=%d bSort=%d bLookup=%d wsFlags=0x%08x\n"
108015       "      notReady=0x%llx log10N=%.1f nRow=%.1f cost=%.1f\n"
108016       "      used=0x%llx nOBSat=%d\n",
108017       pc.plan.nEq, nInMul, (int)rangeDiv, bSort, bLookup, pc.plan.wsFlags,
108018       p->notReady, log10N, pc.plan.nRow, pc.rCost, pc.used,
108019       pc.plan.nOBSat
108020     ));
108021
108022     /* If this index is the best we have seen so far, then record this
108023     ** index and its cost in the p->cost structure.
108024     */
108025     if( (!pIdx || pc.plan.wsFlags) && compareCost(&pc, &p->cost) ){
108026       p->cost = pc;
108027       p->cost.plan.wsFlags &= wsFlagMask;
108028       p->cost.plan.u.pIdx = pIdx;
108029     }
108030
108031     /* If there was an INDEXED BY clause, then only that one index is
108032     ** considered. */
108033     if( pSrc->pIndex ) break;
108034
108035     /* Reset masks for the next index in the loop */
108036     wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
108037     eqTermMask = idxEqTermMask;
108038   }
108039
108040   /* If there is no ORDER BY clause and the SQLITE_ReverseOrder flag
108041   ** is set, then reverse the order that the index will be scanned
108042   ** in. This is used for application testing, to help find cases
108043   ** where application behavior depends on the (undefined) order that
108044   ** SQLite outputs rows in in the absence of an ORDER BY clause.  */
108045   if( !p->pOrderBy && pParse->db->flags & SQLITE_ReverseOrder ){
108046     p->cost.plan.wsFlags |= WHERE_REVERSE;
108047   }
108048
108049   assert( p->pOrderBy || (p->cost.plan.wsFlags&WHERE_ORDERED)==0 );
108050   assert( p->cost.plan.u.pIdx==0 || (p->cost.plan.wsFlags&WHERE_ROWID_EQ)==0 );
108051   assert( pSrc->pIndex==0 
108052        || p->cost.plan.u.pIdx==0 
108053        || p->cost.plan.u.pIdx==pSrc->pIndex 
108054   );
108055
108056   WHERETRACE(("   best index is %s cost=%.1f\n",
108057          p->cost.plan.u.pIdx ? p->cost.plan.u.pIdx->zName : "ipk",
108058          p->cost.rCost));
108059   
108060   bestOrClauseIndex(p);
108061   bestAutomaticIndex(p);
108062   p->cost.plan.wsFlags |= eqTermMask;
108063 }
108064
108065 /*
108066 ** Find the query plan for accessing table pSrc->pTab. Write the
108067 ** best query plan and its cost into the WhereCost object supplied 
108068 ** as the last parameter. This function may calculate the cost of
108069 ** both real and virtual table scans.
108070 **
108071 ** This function does not take ORDER BY or DISTINCT into account.  Nor
108072 ** does it remember the virtual table query plan.  All it does is compute
108073 ** the cost while determining if an OR optimization is applicable.  The
108074 ** details will be reconsidered later if the optimization is found to be
108075 ** applicable.
108076 */
108077 static void bestIndex(WhereBestIdx *p){
108078 #ifndef SQLITE_OMIT_VIRTUALTABLE
108079   if( IsVirtual(p->pSrc->pTab) ){
108080     sqlite3_index_info *pIdxInfo = 0;
108081     p->ppIdxInfo = &pIdxInfo;
108082     bestVirtualIndex(p);
108083     assert( pIdxInfo!=0 || p->pParse->db->mallocFailed );
108084     if( pIdxInfo && pIdxInfo->needToFreeIdxStr ){
108085       sqlite3_free(pIdxInfo->idxStr);
108086     }
108087     sqlite3DbFree(p->pParse->db, pIdxInfo);
108088   }else
108089 #endif
108090   {
108091     bestBtreeIndex(p);
108092   }
108093 }
108094
108095 /*
108096 ** Disable a term in the WHERE clause.  Except, do not disable the term
108097 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
108098 ** or USING clause of that join.
108099 **
108100 ** Consider the term t2.z='ok' in the following queries:
108101 **
108102 **   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
108103 **   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
108104 **   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
108105 **
108106 ** The t2.z='ok' is disabled in the in (2) because it originates
108107 ** in the ON clause.  The term is disabled in (3) because it is not part
108108 ** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
108109 **
108110 ** IMPLEMENTATION-OF: R-24597-58655 No tests are done for terms that are
108111 ** completely satisfied by indices.
108112 **
108113 ** Disabling a term causes that term to not be tested in the inner loop
108114 ** of the join.  Disabling is an optimization.  When terms are satisfied
108115 ** by indices, we disable them to prevent redundant tests in the inner
108116 ** loop.  We would get the correct results if nothing were ever disabled,
108117 ** but joins might run a little slower.  The trick is to disable as much
108118 ** as we can without disabling too much.  If we disabled in (1), we'd get
108119 ** the wrong answer.  See ticket #813.
108120 */
108121 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
108122   if( pTerm
108123       && (pTerm->wtFlags & TERM_CODED)==0
108124       && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
108125   ){
108126     pTerm->wtFlags |= TERM_CODED;
108127     if( pTerm->iParent>=0 ){
108128       WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
108129       if( (--pOther->nChild)==0 ){
108130         disableTerm(pLevel, pOther);
108131       }
108132     }
108133   }
108134 }
108135
108136 /*
108137 ** Code an OP_Affinity opcode to apply the column affinity string zAff
108138 ** to the n registers starting at base. 
108139 **
108140 ** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
108141 ** beginning and end of zAff are ignored.  If all entries in zAff are
108142 ** SQLITE_AFF_NONE, then no code gets generated.
108143 **
108144 ** This routine makes its own copy of zAff so that the caller is free
108145 ** to modify zAff after this routine returns.
108146 */
108147 static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
108148   Vdbe *v = pParse->pVdbe;
108149   if( zAff==0 ){
108150     assert( pParse->db->mallocFailed );
108151     return;
108152   }
108153   assert( v!=0 );
108154
108155   /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
108156   ** and end of the affinity string.
108157   */
108158   while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
108159     n--;
108160     base++;
108161     zAff++;
108162   }
108163   while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
108164     n--;
108165   }
108166
108167   /* Code the OP_Affinity opcode if there is anything left to do. */
108168   if( n>0 ){
108169     sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
108170     sqlite3VdbeChangeP4(v, -1, zAff, n);
108171     sqlite3ExprCacheAffinityChange(pParse, base, n);
108172   }
108173 }
108174
108175
108176 /*
108177 ** Generate code for a single equality term of the WHERE clause.  An equality
108178 ** term can be either X=expr or X IN (...).   pTerm is the term to be 
108179 ** coded.
108180 **
108181 ** The current value for the constraint is left in register iReg.
108182 **
108183 ** For a constraint of the form X=expr, the expression is evaluated and its
108184 ** result is left on the stack.  For constraints of the form X IN (...)
108185 ** this routine sets up a loop that will iterate over all values of X.
108186 */
108187 static int codeEqualityTerm(
108188   Parse *pParse,      /* The parsing context */
108189   WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
108190   WhereLevel *pLevel, /* The level of the FROM clause we are working on */
108191   int iEq,            /* Index of the equality term within this level */
108192   int iTarget         /* Attempt to leave results in this register */
108193 ){
108194   Expr *pX = pTerm->pExpr;
108195   Vdbe *v = pParse->pVdbe;
108196   int iReg;                  /* Register holding results */
108197
108198   assert( iTarget>0 );
108199   if( pX->op==TK_EQ ){
108200     iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
108201   }else if( pX->op==TK_ISNULL ){
108202     iReg = iTarget;
108203     sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
108204 #ifndef SQLITE_OMIT_SUBQUERY
108205   }else{
108206     int eType;
108207     int iTab;
108208     struct InLoop *pIn;
108209     u8 bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
108210
108211     if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 
108212       && pLevel->plan.u.pIdx->aSortOrder[iEq]
108213     ){
108214       testcase( iEq==0 );
108215       testcase( iEq==pLevel->plan.u.pIdx->nColumn-1 );
108216       testcase( iEq>0 && iEq+1<pLevel->plan.u.pIdx->nColumn );
108217       testcase( bRev );
108218       bRev = !bRev;
108219     }
108220     assert( pX->op==TK_IN );
108221     iReg = iTarget;
108222     eType = sqlite3FindInIndex(pParse, pX, 0);
108223     if( eType==IN_INDEX_INDEX_DESC ){
108224       testcase( bRev );
108225       bRev = !bRev;
108226     }
108227     iTab = pX->iTable;
108228     sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
108229     assert( pLevel->plan.wsFlags & WHERE_IN_ABLE );
108230     if( pLevel->u.in.nIn==0 ){
108231       pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
108232     }
108233     pLevel->u.in.nIn++;
108234     pLevel->u.in.aInLoop =
108235        sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
108236                               sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
108237     pIn = pLevel->u.in.aInLoop;
108238     if( pIn ){
108239       pIn += pLevel->u.in.nIn - 1;
108240       pIn->iCur = iTab;
108241       if( eType==IN_INDEX_ROWID ){
108242         pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
108243       }else{
108244         pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
108245       }
108246       pIn->eEndLoopOp = bRev ? OP_Prev : OP_Next;
108247       sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
108248     }else{
108249       pLevel->u.in.nIn = 0;
108250     }
108251 #endif
108252   }
108253   disableTerm(pLevel, pTerm);
108254   return iReg;
108255 }
108256
108257 /*
108258 ** Generate code that will evaluate all == and IN constraints for an
108259 ** index.
108260 **
108261 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
108262 ** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
108263 ** The index has as many as three equality constraints, but in this
108264 ** example, the third "c" value is an inequality.  So only two 
108265 ** constraints are coded.  This routine will generate code to evaluate
108266 ** a==5 and b IN (1,2,3).  The current values for a and b will be stored
108267 ** in consecutive registers and the index of the first register is returned.
108268 **
108269 ** In the example above nEq==2.  But this subroutine works for any value
108270 ** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
108271 ** The only thing it does is allocate the pLevel->iMem memory cell and
108272 ** compute the affinity string.
108273 **
108274 ** This routine always allocates at least one memory cell and returns
108275 ** the index of that memory cell. The code that
108276 ** calls this routine will use that memory cell to store the termination
108277 ** key value of the loop.  If one or more IN operators appear, then
108278 ** this routine allocates an additional nEq memory cells for internal
108279 ** use.
108280 **
108281 ** Before returning, *pzAff is set to point to a buffer containing a
108282 ** copy of the column affinity string of the index allocated using
108283 ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
108284 ** with equality constraints that use NONE affinity are set to
108285 ** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
108286 **
108287 **   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
108288 **   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
108289 **
108290 ** In the example above, the index on t1(a) has TEXT affinity. But since
108291 ** the right hand side of the equality constraint (t2.b) has NONE affinity,
108292 ** no conversion should be attempted before using a t2.b value as part of
108293 ** a key to search the index. Hence the first byte in the returned affinity
108294 ** string in this example would be set to SQLITE_AFF_NONE.
108295 */
108296 static int codeAllEqualityTerms(
108297   Parse *pParse,        /* Parsing context */
108298   WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
108299   WhereClause *pWC,     /* The WHERE clause */
108300   Bitmask notReady,     /* Which parts of FROM have not yet been coded */
108301   int nExtraReg,        /* Number of extra registers to allocate */
108302   char **pzAff          /* OUT: Set to point to affinity string */
108303 ){
108304   int nEq = pLevel->plan.nEq;   /* The number of == or IN constraints to code */
108305   Vdbe *v = pParse->pVdbe;      /* The vm under construction */
108306   Index *pIdx;                  /* The index being used for this loop */
108307   int iCur = pLevel->iTabCur;   /* The cursor of the table */
108308   WhereTerm *pTerm;             /* A single constraint term */
108309   int j;                        /* Loop counter */
108310   int regBase;                  /* Base register */
108311   int nReg;                     /* Number of registers to allocate */
108312   char *zAff;                   /* Affinity string to return */
108313
108314   /* This module is only called on query plans that use an index. */
108315   assert( pLevel->plan.wsFlags & WHERE_INDEXED );
108316   pIdx = pLevel->plan.u.pIdx;
108317
108318   /* Figure out how many memory cells we will need then allocate them.
108319   */
108320   regBase = pParse->nMem + 1;
108321   nReg = pLevel->plan.nEq + nExtraReg;
108322   pParse->nMem += nReg;
108323
108324   zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
108325   if( !zAff ){
108326     pParse->db->mallocFailed = 1;
108327   }
108328
108329   /* Evaluate the equality constraints
108330   */
108331   assert( pIdx->nColumn>=nEq );
108332   for(j=0; j<nEq; j++){
108333     int r1;
108334     int k = pIdx->aiColumn[j];
108335     pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
108336     if( pTerm==0 ) break;
108337     /* The following true for indices with redundant columns. 
108338     ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
108339     testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
108340     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
108341     r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, regBase+j);
108342     if( r1!=regBase+j ){
108343       if( nReg==1 ){
108344         sqlite3ReleaseTempReg(pParse, regBase);
108345         regBase = r1;
108346       }else{
108347         sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
108348       }
108349     }
108350     testcase( pTerm->eOperator & WO_ISNULL );
108351     testcase( pTerm->eOperator & WO_IN );
108352     if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
108353       Expr *pRight = pTerm->pExpr->pRight;
108354       sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
108355       if( zAff ){
108356         if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
108357           zAff[j] = SQLITE_AFF_NONE;
108358         }
108359         if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
108360           zAff[j] = SQLITE_AFF_NONE;
108361         }
108362       }
108363     }
108364   }
108365   *pzAff = zAff;
108366   return regBase;
108367 }
108368
108369 #ifndef SQLITE_OMIT_EXPLAIN
108370 /*
108371 ** This routine is a helper for explainIndexRange() below
108372 **
108373 ** pStr holds the text of an expression that we are building up one term
108374 ** at a time.  This routine adds a new term to the end of the expression.
108375 ** Terms are separated by AND so add the "AND" text for second and subsequent
108376 ** terms only.
108377 */
108378 static void explainAppendTerm(
108379   StrAccum *pStr,             /* The text expression being built */
108380   int iTerm,                  /* Index of this term.  First is zero */
108381   const char *zColumn,        /* Name of the column */
108382   const char *zOp             /* Name of the operator */
108383 ){
108384   if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
108385   sqlite3StrAccumAppend(pStr, zColumn, -1);
108386   sqlite3StrAccumAppend(pStr, zOp, 1);
108387   sqlite3StrAccumAppend(pStr, "?", 1);
108388 }
108389
108390 /*
108391 ** Argument pLevel describes a strategy for scanning table pTab. This 
108392 ** function returns a pointer to a string buffer containing a description
108393 ** of the subset of table rows scanned by the strategy in the form of an
108394 ** SQL expression. Or, if all rows are scanned, NULL is returned.
108395 **
108396 ** For example, if the query:
108397 **
108398 **   SELECT * FROM t1 WHERE a=1 AND b>2;
108399 **
108400 ** is run and there is an index on (a, b), then this function returns a
108401 ** string similar to:
108402 **
108403 **   "a=? AND b>?"
108404 **
108405 ** The returned pointer points to memory obtained from sqlite3DbMalloc().
108406 ** It is the responsibility of the caller to free the buffer when it is
108407 ** no longer required.
108408 */
108409 static char *explainIndexRange(sqlite3 *db, WhereLevel *pLevel, Table *pTab){
108410   WherePlan *pPlan = &pLevel->plan;
108411   Index *pIndex = pPlan->u.pIdx;
108412   int nEq = pPlan->nEq;
108413   int i, j;
108414   Column *aCol = pTab->aCol;
108415   int *aiColumn = pIndex->aiColumn;
108416   StrAccum txt;
108417
108418   if( nEq==0 && (pPlan->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
108419     return 0;
108420   }
108421   sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
108422   txt.db = db;
108423   sqlite3StrAccumAppend(&txt, " (", 2);
108424   for(i=0; i<nEq; i++){
108425     explainAppendTerm(&txt, i, aCol[aiColumn[i]].zName, "=");
108426   }
108427
108428   j = i;
108429   if( pPlan->wsFlags&WHERE_BTM_LIMIT ){
108430     char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
108431     explainAppendTerm(&txt, i++, z, ">");
108432   }
108433   if( pPlan->wsFlags&WHERE_TOP_LIMIT ){
108434     char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
108435     explainAppendTerm(&txt, i, z, "<");
108436   }
108437   sqlite3StrAccumAppend(&txt, ")", 1);
108438   return sqlite3StrAccumFinish(&txt);
108439 }
108440
108441 /*
108442 ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
108443 ** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
108444 ** record is added to the output to describe the table scan strategy in 
108445 ** pLevel.
108446 */
108447 static void explainOneScan(
108448   Parse *pParse,                  /* Parse context */
108449   SrcList *pTabList,              /* Table list this loop refers to */
108450   WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
108451   int iLevel,                     /* Value for "level" column of output */
108452   int iFrom,                      /* Value for "from" column of output */
108453   u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
108454 ){
108455   if( pParse->explain==2 ){
108456     u32 flags = pLevel->plan.wsFlags;
108457     struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
108458     Vdbe *v = pParse->pVdbe;      /* VM being constructed */
108459     sqlite3 *db = pParse->db;     /* Database handle */
108460     char *zMsg;                   /* Text to add to EQP output */
108461     sqlite3_int64 nRow;           /* Expected number of rows visited by scan */
108462     int iId = pParse->iSelectId;  /* Select id (left-most output column) */
108463     int isSearch;                 /* True for a SEARCH. False for SCAN. */
108464
108465     if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
108466
108467     isSearch = (pLevel->plan.nEq>0)
108468              || (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
108469              || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
108470
108471     zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
108472     if( pItem->pSelect ){
108473       zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
108474     }else{
108475       zMsg = sqlite3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName);
108476     }
108477
108478     if( pItem->zAlias ){
108479       zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
108480     }
108481     if( (flags & WHERE_INDEXED)!=0 ){
108482       char *zWhere = explainIndexRange(db, pLevel, pItem->pTab);
108483       zMsg = sqlite3MAppendf(db, zMsg, "%s USING %s%sINDEX%s%s%s", zMsg, 
108484           ((flags & WHERE_TEMP_INDEX)?"AUTOMATIC ":""),
108485           ((flags & WHERE_IDX_ONLY)?"COVERING ":""),
108486           ((flags & WHERE_TEMP_INDEX)?"":" "),
108487           ((flags & WHERE_TEMP_INDEX)?"": pLevel->plan.u.pIdx->zName),
108488           zWhere
108489       );
108490       sqlite3DbFree(db, zWhere);
108491     }else if( flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
108492       zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
108493
108494       if( flags&WHERE_ROWID_EQ ){
108495         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
108496       }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
108497         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
108498       }else if( flags&WHERE_BTM_LIMIT ){
108499         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
108500       }else if( flags&WHERE_TOP_LIMIT ){
108501         zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
108502       }
108503     }
108504 #ifndef SQLITE_OMIT_VIRTUALTABLE
108505     else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
108506       sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
108507       zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
108508                   pVtabIdx->idxNum, pVtabIdx->idxStr);
108509     }
108510 #endif
108511     if( wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX) ){
108512       testcase( wctrlFlags & WHERE_ORDERBY_MIN );
108513       nRow = 1;
108514     }else{
108515       nRow = (sqlite3_int64)pLevel->plan.nRow;
108516     }
108517     zMsg = sqlite3MAppendf(db, zMsg, "%s (~%lld rows)", zMsg, nRow);
108518     sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
108519   }
108520 }
108521 #else
108522 # define explainOneScan(u,v,w,x,y,z)
108523 #endif /* SQLITE_OMIT_EXPLAIN */
108524
108525
108526 /*
108527 ** Generate code for the start of the iLevel-th loop in the WHERE clause
108528 ** implementation described by pWInfo.
108529 */
108530 static Bitmask codeOneLoopStart(
108531   WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
108532   int iLevel,          /* Which level of pWInfo->a[] should be coded */
108533   u16 wctrlFlags,      /* One of the WHERE_* flags defined in sqliteInt.h */
108534   Bitmask notReady     /* Which tables are currently available */
108535 ){
108536   int j, k;            /* Loop counters */
108537   int iCur;            /* The VDBE cursor for the table */
108538   int addrNxt;         /* Where to jump to continue with the next IN case */
108539   int omitTable;       /* True if we use the index only */
108540   int bRev;            /* True if we need to scan in reverse order */
108541   WhereLevel *pLevel;  /* The where level to be coded */
108542   WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
108543   WhereTerm *pTerm;               /* A WHERE clause term */
108544   Parse *pParse;                  /* Parsing context */
108545   Vdbe *v;                        /* The prepared stmt under constructions */
108546   struct SrcList_item *pTabItem;  /* FROM clause term being coded */
108547   int addrBrk;                    /* Jump here to break out of the loop */
108548   int addrCont;                   /* Jump here to continue with next cycle */
108549   int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
108550   int iReleaseReg = 0;      /* Temp register to free before returning */
108551   Bitmask newNotReady;      /* Return value */
108552
108553   pParse = pWInfo->pParse;
108554   v = pParse->pVdbe;
108555   pWC = pWInfo->pWC;
108556   pLevel = &pWInfo->a[iLevel];
108557   pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
108558   iCur = pTabItem->iCursor;
108559   bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
108560   omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0 
108561            && (wctrlFlags & WHERE_FORCE_TABLE)==0;
108562   VdbeNoopComment((v, "Begin Join Loop %d", iLevel));
108563
108564   /* Create labels for the "break" and "continue" instructions
108565   ** for the current loop.  Jump to addrBrk to break out of a loop.
108566   ** Jump to cont to go immediately to the next iteration of the
108567   ** loop.
108568   **
108569   ** When there is an IN operator, we also have a "addrNxt" label that
108570   ** means to continue with the next IN value combination.  When
108571   ** there are no IN operators in the constraints, the "addrNxt" label
108572   ** is the same as "addrBrk".
108573   */
108574   addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
108575   addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
108576
108577   /* If this is the right table of a LEFT OUTER JOIN, allocate and
108578   ** initialize a memory cell that records if this table matches any
108579   ** row of the left table of the join.
108580   */
108581   if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
108582     pLevel->iLeftJoin = ++pParse->nMem;
108583     sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
108584     VdbeComment((v, "init LEFT JOIN no-match flag"));
108585   }
108586
108587   /* Special case of a FROM clause subquery implemented as a co-routine */
108588   if( pTabItem->viaCoroutine ){
108589     int regYield = pTabItem->regReturn;
108590     sqlite3VdbeAddOp2(v, OP_Integer, pTabItem->addrFillSub-1, regYield);
108591     pLevel->p2 =  sqlite3VdbeAddOp1(v, OP_Yield, regYield);
108592     VdbeComment((v, "next row of co-routine %s", pTabItem->pTab->zName));
108593     sqlite3VdbeAddOp2(v, OP_If, regYield+1, addrBrk);
108594     pLevel->op = OP_Goto;
108595   }else
108596
108597 #ifndef SQLITE_OMIT_VIRTUALTABLE
108598   if(  (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
108599     /* Case 0:  The table is a virtual-table.  Use the VFilter and VNext
108600     **          to access the data.
108601     */
108602     int iReg;   /* P3 Value for OP_VFilter */
108603     int addrNotFound;
108604     sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
108605     int nConstraint = pVtabIdx->nConstraint;
108606     struct sqlite3_index_constraint_usage *aUsage =
108607                                                 pVtabIdx->aConstraintUsage;
108608     const struct sqlite3_index_constraint *aConstraint =
108609                                                 pVtabIdx->aConstraint;
108610
108611     sqlite3ExprCachePush(pParse);
108612     iReg = sqlite3GetTempRange(pParse, nConstraint+2);
108613     addrNotFound = pLevel->addrBrk;
108614     for(j=1; j<=nConstraint; j++){
108615       for(k=0; k<nConstraint; k++){
108616         if( aUsage[k].argvIndex==j ){
108617           int iTarget = iReg+j+1;
108618           pTerm = &pWC->a[aConstraint[k].iTermOffset];
108619           if( pTerm->eOperator & WO_IN ){
108620             codeEqualityTerm(pParse, pTerm, pLevel, k, iTarget);
108621             addrNotFound = pLevel->addrNxt;
108622           }else{
108623             sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
108624           }
108625           break;
108626         }
108627       }
108628       if( k==nConstraint ) break;
108629     }
108630     sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
108631     sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
108632     sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg, pVtabIdx->idxStr,
108633                       pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
108634     pVtabIdx->needToFreeIdxStr = 0;
108635     for(j=0; j<nConstraint; j++){
108636       if( aUsage[j].omit ){
108637         int iTerm = aConstraint[j].iTermOffset;
108638         disableTerm(pLevel, &pWC->a[iTerm]);
108639       }
108640     }
108641     pLevel->op = OP_VNext;
108642     pLevel->p1 = iCur;
108643     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
108644     sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
108645     sqlite3ExprCachePop(pParse, 1);
108646   }else
108647 #endif /* SQLITE_OMIT_VIRTUALTABLE */
108648
108649   if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
108650     /* Case 1:  We can directly reference a single row using an
108651     **          equality comparison against the ROWID field.  Or
108652     **          we reference multiple rows using a "rowid IN (...)"
108653     **          construct.
108654     */
108655     iReleaseReg = sqlite3GetTempReg(pParse);
108656     pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
108657     assert( pTerm!=0 );
108658     assert( pTerm->pExpr!=0 );
108659     assert( omitTable==0 );
108660     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
108661     iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, iReleaseReg);
108662     addrNxt = pLevel->addrNxt;
108663     sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
108664     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
108665     sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
108666     sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
108667     VdbeComment((v, "pk"));
108668     pLevel->op = OP_Noop;
108669   }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
108670     /* Case 2:  We have an inequality comparison against the ROWID field.
108671     */
108672     int testOp = OP_Noop;
108673     int start;
108674     int memEndValue = 0;
108675     WhereTerm *pStart, *pEnd;
108676
108677     assert( omitTable==0 );
108678     pStart = findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0);
108679     pEnd = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0);
108680     if( bRev ){
108681       pTerm = pStart;
108682       pStart = pEnd;
108683       pEnd = pTerm;
108684     }
108685     if( pStart ){
108686       Expr *pX;             /* The expression that defines the start bound */
108687       int r1, rTemp;        /* Registers for holding the start boundary */
108688
108689       /* The following constant maps TK_xx codes into corresponding 
108690       ** seek opcodes.  It depends on a particular ordering of TK_xx
108691       */
108692       const u8 aMoveOp[] = {
108693            /* TK_GT */  OP_SeekGt,
108694            /* TK_LE */  OP_SeekLe,
108695            /* TK_LT */  OP_SeekLt,
108696            /* TK_GE */  OP_SeekGe
108697       };
108698       assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
108699       assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
108700       assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
108701
108702       testcase( pStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
108703       pX = pStart->pExpr;
108704       assert( pX!=0 );
108705       assert( pStart->leftCursor==iCur );
108706       r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
108707       sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
108708       VdbeComment((v, "pk"));
108709       sqlite3ExprCacheAffinityChange(pParse, r1, 1);
108710       sqlite3ReleaseTempReg(pParse, rTemp);
108711       disableTerm(pLevel, pStart);
108712     }else{
108713       sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
108714     }
108715     if( pEnd ){
108716       Expr *pX;
108717       pX = pEnd->pExpr;
108718       assert( pX!=0 );
108719       assert( pEnd->leftCursor==iCur );
108720       testcase( pEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
108721       memEndValue = ++pParse->nMem;
108722       sqlite3ExprCode(pParse, pX->pRight, memEndValue);
108723       if( pX->op==TK_LT || pX->op==TK_GT ){
108724         testOp = bRev ? OP_Le : OP_Ge;
108725       }else{
108726         testOp = bRev ? OP_Lt : OP_Gt;
108727       }
108728       disableTerm(pLevel, pEnd);
108729     }
108730     start = sqlite3VdbeCurrentAddr(v);
108731     pLevel->op = bRev ? OP_Prev : OP_Next;
108732     pLevel->p1 = iCur;
108733     pLevel->p2 = start;
108734     if( pStart==0 && pEnd==0 ){
108735       pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
108736     }else{
108737       assert( pLevel->p5==0 );
108738     }
108739     if( testOp!=OP_Noop ){
108740       iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
108741       sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
108742       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
108743       sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
108744       sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
108745     }
108746   }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
108747     /* Case 3: A scan using an index.
108748     **
108749     **         The WHERE clause may contain zero or more equality 
108750     **         terms ("==" or "IN" operators) that refer to the N
108751     **         left-most columns of the index. It may also contain
108752     **         inequality constraints (>, <, >= or <=) on the indexed
108753     **         column that immediately follows the N equalities. Only 
108754     **         the right-most column can be an inequality - the rest must
108755     **         use the "==" and "IN" operators. For example, if the 
108756     **         index is on (x,y,z), then the following clauses are all 
108757     **         optimized:
108758     **
108759     **            x=5
108760     **            x=5 AND y=10
108761     **            x=5 AND y<10
108762     **            x=5 AND y>5 AND y<10
108763     **            x=5 AND y=5 AND z<=10
108764     **
108765     **         The z<10 term of the following cannot be used, only
108766     **         the x=5 term:
108767     **
108768     **            x=5 AND z<10
108769     **
108770     **         N may be zero if there are inequality constraints.
108771     **         If there are no inequality constraints, then N is at
108772     **         least one.
108773     **
108774     **         This case is also used when there are no WHERE clause
108775     **         constraints but an index is selected anyway, in order
108776     **         to force the output order to conform to an ORDER BY.
108777     */  
108778     static const u8 aStartOp[] = {
108779       0,
108780       0,
108781       OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
108782       OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
108783       OP_SeekGt,           /* 4: (start_constraints  && !startEq && !bRev) */
108784       OP_SeekLt,           /* 5: (start_constraints  && !startEq &&  bRev) */
108785       OP_SeekGe,           /* 6: (start_constraints  &&  startEq && !bRev) */
108786       OP_SeekLe            /* 7: (start_constraints  &&  startEq &&  bRev) */
108787     };
108788     static const u8 aEndOp[] = {
108789       OP_Noop,             /* 0: (!end_constraints) */
108790       OP_IdxGE,            /* 1: (end_constraints && !bRev) */
108791       OP_IdxLT             /* 2: (end_constraints && bRev) */
108792     };
108793     int nEq = pLevel->plan.nEq;  /* Number of == or IN terms */
108794     int isMinQuery = 0;          /* If this is an optimized SELECT min(x).. */
108795     int regBase;                 /* Base register holding constraint values */
108796     int r1;                      /* Temp register */
108797     WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
108798     WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
108799     int startEq;                 /* True if range start uses ==, >= or <= */
108800     int endEq;                   /* True if range end uses ==, >= or <= */
108801     int start_constraints;       /* Start of range is constrained */
108802     int nConstraint;             /* Number of constraint terms */
108803     Index *pIdx;                 /* The index we will be using */
108804     int iIdxCur;                 /* The VDBE cursor for the index */
108805     int nExtraReg = 0;           /* Number of extra registers needed */
108806     int op;                      /* Instruction opcode */
108807     char *zStartAff;             /* Affinity for start of range constraint */
108808     char *zEndAff;               /* Affinity for end of range constraint */
108809
108810     pIdx = pLevel->plan.u.pIdx;
108811     iIdxCur = pLevel->iIdxCur;
108812     k = (nEq==pIdx->nColumn ? -1 : pIdx->aiColumn[nEq]);
108813
108814     /* If this loop satisfies a sort order (pOrderBy) request that 
108815     ** was passed to this function to implement a "SELECT min(x) ..." 
108816     ** query, then the caller will only allow the loop to run for
108817     ** a single iteration. This means that the first row returned
108818     ** should not have a NULL value stored in 'x'. If column 'x' is
108819     ** the first one after the nEq equality constraints in the index,
108820     ** this requires some special handling.
108821     */
108822     if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0
108823      && (pLevel->plan.wsFlags&WHERE_ORDERED)
108824      && (pIdx->nColumn>nEq)
108825     ){
108826       /* assert( pOrderBy->nExpr==1 ); */
108827       /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
108828       isMinQuery = 1;
108829       nExtraReg = 1;
108830     }
108831
108832     /* Find any inequality constraint terms for the start and end 
108833     ** of the range. 
108834     */
108835     if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){
108836       pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
108837       nExtraReg = 1;
108838     }
108839     if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){
108840       pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
108841       nExtraReg = 1;
108842     }
108843
108844     /* Generate code to evaluate all constraint terms using == or IN
108845     ** and store the values of those terms in an array of registers
108846     ** starting at regBase.
108847     */
108848     regBase = codeAllEqualityTerms(
108849         pParse, pLevel, pWC, notReady, nExtraReg, &zStartAff
108850     );
108851     zEndAff = sqlite3DbStrDup(pParse->db, zStartAff);
108852     addrNxt = pLevel->addrNxt;
108853
108854     /* If we are doing a reverse order scan on an ascending index, or
108855     ** a forward order scan on a descending index, interchange the 
108856     ** start and end terms (pRangeStart and pRangeEnd).
108857     */
108858     if( (nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
108859      || (bRev && pIdx->nColumn==nEq)
108860     ){
108861       SWAP(WhereTerm *, pRangeEnd, pRangeStart);
108862     }
108863
108864     testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
108865     testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
108866     testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
108867     testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
108868     startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
108869     endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
108870     start_constraints = pRangeStart || nEq>0;
108871
108872     /* Seek the index cursor to the start of the range. */
108873     nConstraint = nEq;
108874     if( pRangeStart ){
108875       Expr *pRight = pRangeStart->pExpr->pRight;
108876       sqlite3ExprCode(pParse, pRight, regBase+nEq);
108877       if( (pRangeStart->wtFlags & TERM_VNULL)==0 ){
108878         sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
108879       }
108880       if( zStartAff ){
108881         if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
108882           /* Since the comparison is to be performed with no conversions
108883           ** applied to the operands, set the affinity to apply to pRight to 
108884           ** SQLITE_AFF_NONE.  */
108885           zStartAff[nEq] = SQLITE_AFF_NONE;
108886         }
108887         if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
108888           zStartAff[nEq] = SQLITE_AFF_NONE;
108889         }
108890       }  
108891       nConstraint++;
108892       testcase( pRangeStart->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
108893     }else if( isMinQuery ){
108894       sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
108895       nConstraint++;
108896       startEq = 0;
108897       start_constraints = 1;
108898     }
108899     codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
108900     op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
108901     assert( op!=0 );
108902     testcase( op==OP_Rewind );
108903     testcase( op==OP_Last );
108904     testcase( op==OP_SeekGt );
108905     testcase( op==OP_SeekGe );
108906     testcase( op==OP_SeekLe );
108907     testcase( op==OP_SeekLt );
108908     sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
108909
108910     /* Load the value for the inequality constraint at the end of the
108911     ** range (if any).
108912     */
108913     nConstraint = nEq;
108914     if( pRangeEnd ){
108915       Expr *pRight = pRangeEnd->pExpr->pRight;
108916       sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
108917       sqlite3ExprCode(pParse, pRight, regBase+nEq);
108918       if( (pRangeEnd->wtFlags & TERM_VNULL)==0 ){
108919         sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
108920       }
108921       if( zEndAff ){
108922         if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){
108923           /* Since the comparison is to be performed with no conversions
108924           ** applied to the operands, set the affinity to apply to pRight to 
108925           ** SQLITE_AFF_NONE.  */
108926           zEndAff[nEq] = SQLITE_AFF_NONE;
108927         }
108928         if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){
108929           zEndAff[nEq] = SQLITE_AFF_NONE;
108930         }
108931       }  
108932       codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);
108933       nConstraint++;
108934       testcase( pRangeEnd->wtFlags & TERM_VIRTUAL ); /* EV: R-30575-11662 */
108935     }
108936     sqlite3DbFree(pParse->db, zStartAff);
108937     sqlite3DbFree(pParse->db, zEndAff);
108938
108939     /* Top of the loop body */
108940     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
108941
108942     /* Check if the index cursor is past the end of the range. */
108943     op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
108944     testcase( op==OP_Noop );
108945     testcase( op==OP_IdxGE );
108946     testcase( op==OP_IdxLT );
108947     if( op!=OP_Noop ){
108948       sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
108949       sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
108950     }
108951
108952     /* If there are inequality constraints, check that the value
108953     ** of the table column that the inequality contrains is not NULL.
108954     ** If it is, jump to the next iteration of the loop.
108955     */
108956     r1 = sqlite3GetTempReg(pParse);
108957     testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT );
108958     testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
108959     if( (pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 ){
108960       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
108961       sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
108962     }
108963     sqlite3ReleaseTempReg(pParse, r1);
108964
108965     /* Seek the table cursor, if required */
108966     disableTerm(pLevel, pRangeStart);
108967     disableTerm(pLevel, pRangeEnd);
108968     if( !omitTable ){
108969       iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
108970       sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
108971       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
108972       sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg);  /* Deferred seek */
108973     }
108974
108975     /* Record the instruction used to terminate the loop. Disable 
108976     ** WHERE clause terms made redundant by the index range scan.
108977     */
108978     if( pLevel->plan.wsFlags & WHERE_UNIQUE ){
108979       pLevel->op = OP_Noop;
108980     }else if( bRev ){
108981       pLevel->op = OP_Prev;
108982     }else{
108983       pLevel->op = OP_Next;
108984     }
108985     pLevel->p1 = iIdxCur;
108986     if( pLevel->plan.wsFlags & WHERE_COVER_SCAN ){
108987       pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
108988     }else{
108989       assert( pLevel->p5==0 );
108990     }
108991   }else
108992
108993 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
108994   if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
108995     /* Case 4:  Two or more separately indexed terms connected by OR
108996     **
108997     ** Example:
108998     **
108999     **   CREATE TABLE t1(a,b,c,d);
109000     **   CREATE INDEX i1 ON t1(a);
109001     **   CREATE INDEX i2 ON t1(b);
109002     **   CREATE INDEX i3 ON t1(c);
109003     **
109004     **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
109005     **
109006     ** In the example, there are three indexed terms connected by OR.
109007     ** The top of the loop looks like this:
109008     **
109009     **          Null       1                # Zero the rowset in reg 1
109010     **
109011     ** Then, for each indexed term, the following. The arguments to
109012     ** RowSetTest are such that the rowid of the current row is inserted
109013     ** into the RowSet. If it is already present, control skips the
109014     ** Gosub opcode and jumps straight to the code generated by WhereEnd().
109015     **
109016     **        sqlite3WhereBegin(<term>)
109017     **          RowSetTest                  # Insert rowid into rowset
109018     **          Gosub      2 A
109019     **        sqlite3WhereEnd()
109020     **
109021     ** Following the above, code to terminate the loop. Label A, the target
109022     ** of the Gosub above, jumps to the instruction right after the Goto.
109023     **
109024     **          Null       1                # Zero the rowset in reg 1
109025     **          Goto       B                # The loop is finished.
109026     **
109027     **       A: <loop body>                 # Return data, whatever.
109028     **
109029     **          Return     2                # Jump back to the Gosub
109030     **
109031     **       B: <after the loop>
109032     **
109033     */
109034     WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
109035     SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
109036     Index *pCov = 0;             /* Potential covering index (or NULL) */
109037     int iCovCur = pParse->nTab++;  /* Cursor used for index scans (if any) */
109038
109039     int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
109040     int regRowset = 0;                        /* Register for RowSet object */
109041     int regRowid = 0;                         /* Register holding rowid */
109042     int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
109043     int iRetInit;                             /* Address of regReturn init */
109044     int untestedTerms = 0;             /* Some terms not completely tested */
109045     int ii;                            /* Loop counter */
109046     Expr *pAndExpr = 0;                /* An ".. AND (...)" expression */
109047    
109048     pTerm = pLevel->plan.u.pTerm;
109049     assert( pTerm!=0 );
109050     assert( pTerm->eOperator & WO_OR );
109051     assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
109052     pOrWc = &pTerm->u.pOrInfo->wc;
109053     pLevel->op = OP_Return;
109054     pLevel->p1 = regReturn;
109055
109056     /* Set up a new SrcList in pOrTab containing the table being scanned
109057     ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
109058     ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
109059     */
109060     if( pWInfo->nLevel>1 ){
109061       int nNotReady;                 /* The number of notReady tables */
109062       struct SrcList_item *origSrc;     /* Original list of tables */
109063       nNotReady = pWInfo->nLevel - iLevel - 1;
109064       pOrTab = sqlite3StackAllocRaw(pParse->db,
109065                             sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
109066       if( pOrTab==0 ) return notReady;
109067       pOrTab->nAlloc = (i16)(nNotReady + 1);
109068       pOrTab->nSrc = pOrTab->nAlloc;
109069       memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
109070       origSrc = pWInfo->pTabList->a;
109071       for(k=1; k<=nNotReady; k++){
109072         memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
109073       }
109074     }else{
109075       pOrTab = pWInfo->pTabList;
109076     }
109077
109078     /* Initialize the rowset register to contain NULL. An SQL NULL is 
109079     ** equivalent to an empty rowset.
109080     **
109081     ** Also initialize regReturn to contain the address of the instruction 
109082     ** immediately following the OP_Return at the bottom of the loop. This
109083     ** is required in a few obscure LEFT JOIN cases where control jumps
109084     ** over the top of the loop into the body of it. In this case the 
109085     ** correct response for the end-of-loop code (the OP_Return) is to 
109086     ** fall through to the next instruction, just as an OP_Next does if
109087     ** called on an uninitialized cursor.
109088     */
109089     if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
109090       regRowset = ++pParse->nMem;
109091       regRowid = ++pParse->nMem;
109092       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
109093     }
109094     iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
109095
109096     /* If the original WHERE clause is z of the form:  (x1 OR x2 OR ...) AND y
109097     ** Then for every term xN, evaluate as the subexpression: xN AND z
109098     ** That way, terms in y that are factored into the disjunction will
109099     ** be picked up by the recursive calls to sqlite3WhereBegin() below.
109100     **
109101     ** Actually, each subexpression is converted to "xN AND w" where w is
109102     ** the "interesting" terms of z - terms that did not originate in the
109103     ** ON or USING clause of a LEFT JOIN, and terms that are usable as 
109104     ** indices.
109105     **
109106     ** This optimization also only applies if the (x1 OR x2 OR ...) term
109107     ** is not contained in the ON clause of a LEFT JOIN.
109108     ** See ticket http://www.sqlite.org/src/info/f2369304e4
109109     */
109110     if( pWC->nTerm>1 ){
109111       int iTerm;
109112       for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
109113         Expr *pExpr = pWC->a[iTerm].pExpr;
109114         if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
109115         if( pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_ORINFO) ) continue;
109116         if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
109117         pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
109118         pAndExpr = sqlite3ExprAnd(pParse->db, pAndExpr, pExpr);
109119       }
109120       if( pAndExpr ){
109121         pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
109122       }
109123     }
109124
109125     for(ii=0; ii<pOrWc->nTerm; ii++){
109126       WhereTerm *pOrTerm = &pOrWc->a[ii];
109127       if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
109128         WhereInfo *pSubWInfo;          /* Info for single OR-term scan */
109129         Expr *pOrExpr = pOrTerm->pExpr;
109130         if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
109131           pAndExpr->pLeft = pOrExpr;
109132           pOrExpr = pAndExpr;
109133         }
109134         /* Loop through table entries that match term pOrTerm. */
109135         pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
109136                         WHERE_OMIT_OPEN_CLOSE | WHERE_AND_ONLY |
109137                         WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY, iCovCur);
109138         assert( pSubWInfo || pParse->nErr || pParse->db->mallocFailed );
109139         if( pSubWInfo ){
109140           WhereLevel *pLvl;
109141           explainOneScan(
109142               pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
109143           );
109144           if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
109145             int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
109146             int r;
109147             r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur, 
109148                                          regRowid, 0);
109149             sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
109150                                  sqlite3VdbeCurrentAddr(v)+2, r, iSet);
109151           }
109152           sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
109153
109154           /* The pSubWInfo->untestedTerms flag means that this OR term
109155           ** contained one or more AND term from a notReady table.  The
109156           ** terms from the notReady table could not be tested and will
109157           ** need to be tested later.
109158           */
109159           if( pSubWInfo->untestedTerms ) untestedTerms = 1;
109160
109161           /* If all of the OR-connected terms are optimized using the same
109162           ** index, and the index is opened using the same cursor number
109163           ** by each call to sqlite3WhereBegin() made by this loop, it may
109164           ** be possible to use that index as a covering index.
109165           **
109166           ** If the call to sqlite3WhereBegin() above resulted in a scan that
109167           ** uses an index, and this is either the first OR-connected term
109168           ** processed or the index is the same as that used by all previous
109169           ** terms, set pCov to the candidate covering index. Otherwise, set 
109170           ** pCov to NULL to indicate that no candidate covering index will 
109171           ** be available.
109172           */
109173           pLvl = &pSubWInfo->a[0];
109174           if( (pLvl->plan.wsFlags & WHERE_INDEXED)!=0
109175            && (pLvl->plan.wsFlags & WHERE_TEMP_INDEX)==0
109176            && (ii==0 || pLvl->plan.u.pIdx==pCov)
109177           ){
109178             assert( pLvl->iIdxCur==iCovCur );
109179             pCov = pLvl->plan.u.pIdx;
109180           }else{
109181             pCov = 0;
109182           }
109183
109184           /* Finish the loop through table entries that match term pOrTerm. */
109185           sqlite3WhereEnd(pSubWInfo);
109186         }
109187       }
109188     }
109189     pLevel->u.pCovidx = pCov;
109190     if( pCov ) pLevel->iIdxCur = iCovCur;
109191     if( pAndExpr ){
109192       pAndExpr->pLeft = 0;
109193       sqlite3ExprDelete(pParse->db, pAndExpr);
109194     }
109195     sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
109196     sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
109197     sqlite3VdbeResolveLabel(v, iLoopBody);
109198
109199     if( pWInfo->nLevel>1 ) sqlite3StackFree(pParse->db, pOrTab);
109200     if( !untestedTerms ) disableTerm(pLevel, pTerm);
109201   }else
109202 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
109203
109204   {
109205     /* Case 5:  There is no usable index.  We must do a complete
109206     **          scan of the entire table.
109207     */
109208     static const u8 aStep[] = { OP_Next, OP_Prev };
109209     static const u8 aStart[] = { OP_Rewind, OP_Last };
109210     assert( bRev==0 || bRev==1 );
109211     assert( omitTable==0 );
109212     pLevel->op = aStep[bRev];
109213     pLevel->p1 = iCur;
109214     pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
109215     pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
109216   }
109217   newNotReady = notReady & ~getMask(pWC->pMaskSet, iCur);
109218
109219   /* Insert code to test every subexpression that can be completely
109220   ** computed using the current set of tables.
109221   **
109222   ** IMPLEMENTATION-OF: R-49525-50935 Terms that cannot be satisfied through
109223   ** the use of indices become tests that are evaluated against each row of
109224   ** the relevant input tables.
109225   */
109226   for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
109227     Expr *pE;
109228     testcase( pTerm->wtFlags & TERM_VIRTUAL ); /* IMP: R-30575-11662 */
109229     testcase( pTerm->wtFlags & TERM_CODED );
109230     if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
109231     if( (pTerm->prereqAll & newNotReady)!=0 ){
109232       testcase( pWInfo->untestedTerms==0
109233                && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
109234       pWInfo->untestedTerms = 1;
109235       continue;
109236     }
109237     pE = pTerm->pExpr;
109238     assert( pE!=0 );
109239     if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
109240       continue;
109241     }
109242     sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
109243     pTerm->wtFlags |= TERM_CODED;
109244   }
109245
109246   /* Insert code to test for implied constraints based on transitivity
109247   ** of the "==" operator.
109248   **
109249   ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
109250   ** and we are coding the t1 loop and the t2 loop has not yet coded,
109251   ** then we cannot use the "t1.a=t2.b" constraint, but we can code
109252   ** the implied "t1.a=123" constraint.
109253   */
109254   for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
109255     Expr *pE;
109256     WhereTerm *pAlt;
109257     Expr sEq;
109258     if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
109259     if( pTerm->eOperator!=(WO_EQUIV|WO_EQ) ) continue;
109260     if( pTerm->leftCursor!=iCur ) continue;
109261     pE = pTerm->pExpr;
109262     assert( !ExprHasProperty(pE, EP_FromJoin) );
109263     assert( (pTerm->prereqRight & newNotReady)!=0 );
109264     pAlt = findTerm(pWC, iCur, pTerm->u.leftColumn, notReady, WO_EQ|WO_IN, 0);
109265     if( pAlt==0 ) continue;
109266     if( pAlt->wtFlags & (TERM_CODED) ) continue;
109267     VdbeNoopComment((v, "begin transitive constraint"));
109268     sEq = *pAlt->pExpr;
109269     sEq.pLeft = pE->pLeft;
109270     sqlite3ExprIfFalse(pParse, &sEq, addrCont, SQLITE_JUMPIFNULL);
109271   }
109272
109273   /* For a LEFT OUTER JOIN, generate code that will record the fact that
109274   ** at least one row of the right table has matched the left table.  
109275   */
109276   if( pLevel->iLeftJoin ){
109277     pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
109278     sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
109279     VdbeComment((v, "record LEFT JOIN hit"));
109280     sqlite3ExprCacheClear(pParse);
109281     for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
109282       testcase( pTerm->wtFlags & TERM_VIRTUAL );  /* IMP: R-30575-11662 */
109283       testcase( pTerm->wtFlags & TERM_CODED );
109284       if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
109285       if( (pTerm->prereqAll & newNotReady)!=0 ){
109286         assert( pWInfo->untestedTerms );
109287         continue;
109288       }
109289       assert( pTerm->pExpr );
109290       sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
109291       pTerm->wtFlags |= TERM_CODED;
109292     }
109293   }
109294   sqlite3ReleaseTempReg(pParse, iReleaseReg);
109295
109296   return newNotReady;
109297 }
109298
109299 #if defined(SQLITE_TEST)
109300 /*
109301 ** The following variable holds a text description of query plan generated
109302 ** by the most recent call to sqlite3WhereBegin().  Each call to WhereBegin
109303 ** overwrites the previous.  This information is used for testing and
109304 ** analysis only.
109305 */
109306 SQLITE_API char sqlite3_query_plan[BMS*2*40];  /* Text of the join */
109307 static int nQPlan = 0;              /* Next free slow in _query_plan[] */
109308
109309 #endif /* SQLITE_TEST */
109310
109311
109312 /*
109313 ** Free a WhereInfo structure
109314 */
109315 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
109316   if( ALWAYS(pWInfo) ){
109317     int i;
109318     for(i=0; i<pWInfo->nLevel; i++){
109319       sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
109320       if( pInfo ){
109321         /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */
109322         if( pInfo->needToFreeIdxStr ){
109323           sqlite3_free(pInfo->idxStr);
109324         }
109325         sqlite3DbFree(db, pInfo);
109326       }
109327       if( pWInfo->a[i].plan.wsFlags & WHERE_TEMP_INDEX ){
109328         Index *pIdx = pWInfo->a[i].plan.u.pIdx;
109329         if( pIdx ){
109330           sqlite3DbFree(db, pIdx->zColAff);
109331           sqlite3DbFree(db, pIdx);
109332         }
109333       }
109334     }
109335     whereClauseClear(pWInfo->pWC);
109336     sqlite3DbFree(db, pWInfo);
109337   }
109338 }
109339
109340
109341 /*
109342 ** Generate the beginning of the loop used for WHERE clause processing.
109343 ** The return value is a pointer to an opaque structure that contains
109344 ** information needed to terminate the loop.  Later, the calling routine
109345 ** should invoke sqlite3WhereEnd() with the return value of this function
109346 ** in order to complete the WHERE clause processing.
109347 **
109348 ** If an error occurs, this routine returns NULL.
109349 **
109350 ** The basic idea is to do a nested loop, one loop for each table in
109351 ** the FROM clause of a select.  (INSERT and UPDATE statements are the
109352 ** same as a SELECT with only a single table in the FROM clause.)  For
109353 ** example, if the SQL is this:
109354 **
109355 **       SELECT * FROM t1, t2, t3 WHERE ...;
109356 **
109357 ** Then the code generated is conceptually like the following:
109358 **
109359 **      foreach row1 in t1 do       \    Code generated
109360 **        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
109361 **          foreach row3 in t3 do   /
109362 **            ...
109363 **          end                     \    Code generated
109364 **        end                        |-- by sqlite3WhereEnd()
109365 **      end                         /
109366 **
109367 ** Note that the loops might not be nested in the order in which they
109368 ** appear in the FROM clause if a different order is better able to make
109369 ** use of indices.  Note also that when the IN operator appears in
109370 ** the WHERE clause, it might result in additional nested loops for
109371 ** scanning through all values on the right-hand side of the IN.
109372 **
109373 ** There are Btree cursors associated with each table.  t1 uses cursor
109374 ** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
109375 ** And so forth.  This routine generates code to open those VDBE cursors
109376 ** and sqlite3WhereEnd() generates the code to close them.
109377 **
109378 ** The code that sqlite3WhereBegin() generates leaves the cursors named
109379 ** in pTabList pointing at their appropriate entries.  The [...] code
109380 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
109381 ** data from the various tables of the loop.
109382 **
109383 ** If the WHERE clause is empty, the foreach loops must each scan their
109384 ** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
109385 ** the tables have indices and there are terms in the WHERE clause that
109386 ** refer to those indices, a complete table scan can be avoided and the
109387 ** code will run much faster.  Most of the work of this routine is checking
109388 ** to see if there are indices that can be used to speed up the loop.
109389 **
109390 ** Terms of the WHERE clause are also used to limit which rows actually
109391 ** make it to the "..." in the middle of the loop.  After each "foreach",
109392 ** terms of the WHERE clause that use only terms in that loop and outer
109393 ** loops are evaluated and if false a jump is made around all subsequent
109394 ** inner loops (or around the "..." if the test occurs within the inner-
109395 ** most loop)
109396 **
109397 ** OUTER JOINS
109398 **
109399 ** An outer join of tables t1 and t2 is conceptally coded as follows:
109400 **
109401 **    foreach row1 in t1 do
109402 **      flag = 0
109403 **      foreach row2 in t2 do
109404 **        start:
109405 **          ...
109406 **          flag = 1
109407 **      end
109408 **      if flag==0 then
109409 **        move the row2 cursor to a null row
109410 **        goto start
109411 **      fi
109412 **    end
109413 **
109414 ** ORDER BY CLAUSE PROCESSING
109415 **
109416 ** pOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
109417 ** if there is one.  If there is no ORDER BY clause or if this routine
109418 ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
109419 **
109420 ** If an index can be used so that the natural output order of the table
109421 ** scan is correct for the ORDER BY clause, then that index is used and
109422 ** the returned WhereInfo.nOBSat field is set to pOrderBy->nExpr.  This
109423 ** is an optimization that prevents an unnecessary sort of the result set
109424 ** if an index appropriate for the ORDER BY clause already exists.
109425 **
109426 ** If the where clause loops cannot be arranged to provide the correct
109427 ** output order, then WhereInfo.nOBSat is 0.
109428 */
109429 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
109430   Parse *pParse,        /* The parser context */
109431   SrcList *pTabList,    /* A list of all tables to be scanned */
109432   Expr *pWhere,         /* The WHERE clause */
109433   ExprList *pOrderBy,   /* An ORDER BY clause, or NULL */
109434   ExprList *pDistinct,  /* The select-list for DISTINCT queries - or NULL */
109435   u16 wctrlFlags,       /* One of the WHERE_* flags defined in sqliteInt.h */
109436   int iIdxCur           /* If WHERE_ONETABLE_ONLY is set, index cursor number */
109437 ){
109438   int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
109439   int nTabList;              /* Number of elements in pTabList */
109440   WhereInfo *pWInfo;         /* Will become the return value of this function */
109441   Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
109442   Bitmask notReady;          /* Cursors that are not yet positioned */
109443   WhereBestIdx sWBI;         /* Best index search context */
109444   WhereMaskSet *pMaskSet;    /* The expression mask set */
109445   WhereLevel *pLevel;        /* A single level in pWInfo->a[] */
109446   int iFrom;                 /* First unused FROM clause element */
109447   int andFlags;              /* AND-ed combination of all pWC->a[].wtFlags */
109448   int ii;                    /* Loop counter */
109449   sqlite3 *db;               /* Database connection */
109450
109451
109452   /* Variable initialization */
109453   memset(&sWBI, 0, sizeof(sWBI));
109454   sWBI.pParse = pParse;
109455
109456   /* The number of tables in the FROM clause is limited by the number of
109457   ** bits in a Bitmask 
109458   */
109459   testcase( pTabList->nSrc==BMS );
109460   if( pTabList->nSrc>BMS ){
109461     sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
109462     return 0;
109463   }
109464
109465   /* This function normally generates a nested loop for all tables in 
109466   ** pTabList.  But if the WHERE_ONETABLE_ONLY flag is set, then we should
109467   ** only generate code for the first table in pTabList and assume that
109468   ** any cursors associated with subsequent tables are uninitialized.
109469   */
109470   nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
109471
109472   /* Allocate and initialize the WhereInfo structure that will become the
109473   ** return value. A single allocation is used to store the WhereInfo
109474   ** struct, the contents of WhereInfo.a[], the WhereClause structure
109475   ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
109476   ** field (type Bitmask) it must be aligned on an 8-byte boundary on
109477   ** some architectures. Hence the ROUND8() below.
109478   */
109479   db = pParse->db;
109480   nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
109481   pWInfo = sqlite3DbMallocZero(db, 
109482       nByteWInfo + 
109483       sizeof(WhereClause) +
109484       sizeof(WhereMaskSet)
109485   );
109486   if( db->mallocFailed ){
109487     sqlite3DbFree(db, pWInfo);
109488     pWInfo = 0;
109489     goto whereBeginError;
109490   }
109491   pWInfo->nLevel = nTabList;
109492   pWInfo->pParse = pParse;
109493   pWInfo->pTabList = pTabList;
109494   pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
109495   pWInfo->pWC = sWBI.pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
109496   pWInfo->wctrlFlags = wctrlFlags;
109497   pWInfo->savedNQueryLoop = pParse->nQueryLoop;
109498   pMaskSet = (WhereMaskSet*)&sWBI.pWC[1];
109499   sWBI.aLevel = pWInfo->a;
109500
109501   /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
109502   ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
109503   if( OptimizationDisabled(db, SQLITE_DistinctOpt) ) pDistinct = 0;
109504
109505   /* Split the WHERE clause into separate subexpressions where each
109506   ** subexpression is separated by an AND operator.
109507   */
109508   initMaskSet(pMaskSet);
109509   whereClauseInit(sWBI.pWC, pParse, pMaskSet, wctrlFlags);
109510   sqlite3ExprCodeConstants(pParse, pWhere);
109511   whereSplit(sWBI.pWC, pWhere, TK_AND);   /* IMP: R-15842-53296 */
109512     
109513   /* Special case: a WHERE clause that is constant.  Evaluate the
109514   ** expression and either jump over all of the code or fall thru.
109515   */
109516   if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
109517     sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
109518     pWhere = 0;
109519   }
109520
109521   /* Assign a bit from the bitmask to every term in the FROM clause.
109522   **
109523   ** When assigning bitmask values to FROM clause cursors, it must be
109524   ** the case that if X is the bitmask for the N-th FROM clause term then
109525   ** the bitmask for all FROM clause terms to the left of the N-th term
109526   ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
109527   ** its Expr.iRightJoinTable value to find the bitmask of the right table
109528   ** of the join.  Subtracting one from the right table bitmask gives a
109529   ** bitmask for all tables to the left of the join.  Knowing the bitmask
109530   ** for all tables to the left of a left join is important.  Ticket #3015.
109531   **
109532   ** Note that bitmasks are created for all pTabList->nSrc tables in
109533   ** pTabList, not just the first nTabList tables.  nTabList is normally
109534   ** equal to pTabList->nSrc but might be shortened to 1 if the
109535   ** WHERE_ONETABLE_ONLY flag is set.
109536   */
109537   for(ii=0; ii<pTabList->nSrc; ii++){
109538     createMask(pMaskSet, pTabList->a[ii].iCursor);
109539   }
109540 #ifndef NDEBUG
109541   {
109542     Bitmask toTheLeft = 0;
109543     for(ii=0; ii<pTabList->nSrc; ii++){
109544       Bitmask m = getMask(pMaskSet, pTabList->a[ii].iCursor);
109545       assert( (m-1)==toTheLeft );
109546       toTheLeft |= m;
109547     }
109548   }
109549 #endif
109550
109551   /* Analyze all of the subexpressions.  Note that exprAnalyze() might
109552   ** add new virtual terms onto the end of the WHERE clause.  We do not
109553   ** want to analyze these virtual terms, so start analyzing at the end
109554   ** and work forward so that the added virtual terms are never processed.
109555   */
109556   exprAnalyzeAll(pTabList, sWBI.pWC);
109557   if( db->mallocFailed ){
109558     goto whereBeginError;
109559   }
109560
109561   /* Check if the DISTINCT qualifier, if there is one, is redundant. 
109562   ** If it is, then set pDistinct to NULL and WhereInfo.eDistinct to
109563   ** WHERE_DISTINCT_UNIQUE to tell the caller to ignore the DISTINCT.
109564   */
109565   if( pDistinct && isDistinctRedundant(pParse, pTabList, sWBI.pWC, pDistinct) ){
109566     pDistinct = 0;
109567     pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
109568   }
109569
109570   /* Chose the best index to use for each table in the FROM clause.
109571   **
109572   ** This loop fills in the following fields:
109573   **
109574   **   pWInfo->a[].pIdx      The index to use for this level of the loop.
109575   **   pWInfo->a[].wsFlags   WHERE_xxx flags associated with pIdx
109576   **   pWInfo->a[].nEq       The number of == and IN constraints
109577   **   pWInfo->a[].iFrom     Which term of the FROM clause is being coded
109578   **   pWInfo->a[].iTabCur   The VDBE cursor for the database table
109579   **   pWInfo->a[].iIdxCur   The VDBE cursor for the index
109580   **   pWInfo->a[].pTerm     When wsFlags==WO_OR, the OR-clause term
109581   **
109582   ** This loop also figures out the nesting order of tables in the FROM
109583   ** clause.
109584   */
109585   sWBI.notValid = ~(Bitmask)0;
109586   sWBI.pOrderBy = pOrderBy;
109587   sWBI.n = nTabList;
109588   sWBI.pDistinct = pDistinct;
109589   andFlags = ~0;
109590   WHERETRACE(("*** Optimizer Start ***\n"));
109591   for(sWBI.i=iFrom=0, pLevel=pWInfo->a; sWBI.i<nTabList; sWBI.i++, pLevel++){
109592     WhereCost bestPlan;         /* Most efficient plan seen so far */
109593     Index *pIdx;                /* Index for FROM table at pTabItem */
109594     int j;                      /* For looping over FROM tables */
109595     int bestJ = -1;             /* The value of j */
109596     Bitmask m;                  /* Bitmask value for j or bestJ */
109597     int isOptimal;              /* Iterator for optimal/non-optimal search */
109598     int ckOptimal;              /* Do the optimal scan check */
109599     int nUnconstrained;         /* Number tables without INDEXED BY */
109600     Bitmask notIndexed;         /* Mask of tables that cannot use an index */
109601
109602     memset(&bestPlan, 0, sizeof(bestPlan));
109603     bestPlan.rCost = SQLITE_BIG_DBL;
109604     WHERETRACE(("*** Begin search for loop %d ***\n", sWBI.i));
109605
109606     /* Loop through the remaining entries in the FROM clause to find the
109607     ** next nested loop. The loop tests all FROM clause entries
109608     ** either once or twice. 
109609     **
109610     ** The first test is always performed if there are two or more entries
109611     ** remaining and never performed if there is only one FROM clause entry
109612     ** to choose from.  The first test looks for an "optimal" scan.  In
109613     ** this context an optimal scan is one that uses the same strategy
109614     ** for the given FROM clause entry as would be selected if the entry
109615     ** were used as the innermost nested loop.  In other words, a table
109616     ** is chosen such that the cost of running that table cannot be reduced
109617     ** by waiting for other tables to run first.  This "optimal" test works
109618     ** by first assuming that the FROM clause is on the inner loop and finding
109619     ** its query plan, then checking to see if that query plan uses any
109620     ** other FROM clause terms that are sWBI.notValid.  If no notValid terms
109621     ** are used then the "optimal" query plan works.
109622     **
109623     ** Note that the WhereCost.nRow parameter for an optimal scan might
109624     ** not be as small as it would be if the table really were the innermost
109625     ** join.  The nRow value can be reduced by WHERE clause constraints
109626     ** that do not use indices.  But this nRow reduction only happens if the
109627     ** table really is the innermost join.  
109628     **
109629     ** The second loop iteration is only performed if no optimal scan
109630     ** strategies were found by the first iteration. This second iteration
109631     ** is used to search for the lowest cost scan overall.
109632     **
109633     ** Without the optimal scan step (the first iteration) a suboptimal
109634     ** plan might be chosen for queries like this:
109635     **   
109636     **   CREATE TABLE t1(a, b); 
109637     **   CREATE TABLE t2(c, d);
109638     **   SELECT * FROM t2, t1 WHERE t2.rowid = t1.a;
109639     **
109640     ** The best strategy is to iterate through table t1 first. However it
109641     ** is not possible to determine this with a simple greedy algorithm.
109642     ** Since the cost of a linear scan through table t2 is the same 
109643     ** as the cost of a linear scan through table t1, a simple greedy 
109644     ** algorithm may choose to use t2 for the outer loop, which is a much
109645     ** costlier approach.
109646     */
109647     nUnconstrained = 0;
109648     notIndexed = 0;
109649
109650     /* The optimal scan check only occurs if there are two or more tables
109651     ** available to be reordered */
109652     if( iFrom==nTabList-1 ){
109653       ckOptimal = 0;  /* Common case of just one table in the FROM clause */
109654     }else{
109655       ckOptimal = -1;
109656       for(j=iFrom, sWBI.pSrc=&pTabList->a[j]; j<nTabList; j++, sWBI.pSrc++){
109657         m = getMask(pMaskSet, sWBI.pSrc->iCursor);
109658         if( (m & sWBI.notValid)==0 ){
109659           if( j==iFrom ) iFrom++;
109660           continue;
109661         }
109662         if( j>iFrom && (sWBI.pSrc->jointype & (JT_LEFT|JT_CROSS))!=0 ) break;
109663         if( ++ckOptimal ) break;
109664         if( (sWBI.pSrc->jointype & JT_LEFT)!=0 ) break;
109665       }
109666     }
109667     assert( ckOptimal==0 || ckOptimal==1 );
109668
109669     for(isOptimal=ckOptimal; isOptimal>=0 && bestJ<0; isOptimal--){
109670       for(j=iFrom, sWBI.pSrc=&pTabList->a[j]; j<nTabList; j++, sWBI.pSrc++){
109671         if( j>iFrom && (sWBI.pSrc->jointype & (JT_LEFT|JT_CROSS))!=0 ){
109672           /* This break and one like it in the ckOptimal computation loop
109673           ** above prevent table reordering across LEFT and CROSS JOINs.
109674           ** The LEFT JOIN case is necessary for correctness.  The prohibition
109675           ** against reordering across a CROSS JOIN is an SQLite feature that
109676           ** allows the developer to control table reordering */
109677           break;
109678         }
109679         m = getMask(pMaskSet, sWBI.pSrc->iCursor);
109680         if( (m & sWBI.notValid)==0 ){
109681           assert( j>iFrom );
109682           continue;
109683         }
109684         sWBI.notReady = (isOptimal ? m : sWBI.notValid);
109685         if( sWBI.pSrc->pIndex==0 ) nUnconstrained++;
109686   
109687         WHERETRACE(("   === trying table %d (%s) with isOptimal=%d ===\n",
109688                     j, sWBI.pSrc->pTab->zName, isOptimal));
109689         assert( sWBI.pSrc->pTab );
109690 #ifndef SQLITE_OMIT_VIRTUALTABLE
109691         if( IsVirtual(sWBI.pSrc->pTab) ){
109692           sWBI.ppIdxInfo = &pWInfo->a[j].pIdxInfo;
109693           bestVirtualIndex(&sWBI);
109694         }else 
109695 #endif
109696         {
109697           bestBtreeIndex(&sWBI);
109698         }
109699         assert( isOptimal || (sWBI.cost.used&sWBI.notValid)==0 );
109700
109701         /* If an INDEXED BY clause is present, then the plan must use that
109702         ** index if it uses any index at all */
109703         assert( sWBI.pSrc->pIndex==0 
109704                   || (sWBI.cost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0
109705                   || sWBI.cost.plan.u.pIdx==sWBI.pSrc->pIndex );
109706
109707         if( isOptimal && (sWBI.cost.plan.wsFlags & WHERE_NOT_FULLSCAN)==0 ){
109708           notIndexed |= m;
109709         }
109710         if( isOptimal ){
109711           pWInfo->a[j].rOptCost = sWBI.cost.rCost;
109712         }else if( ckOptimal ){
109713           /* If two or more tables have nearly the same outer loop cost, but
109714           ** very different inner loop (optimal) cost, we want to choose
109715           ** for the outer loop that table which benefits the least from
109716           ** being in the inner loop.  The following code scales the 
109717           ** outer loop cost estimate to accomplish that. */
109718           WHERETRACE(("   scaling cost from %.1f to %.1f\n",
109719                       sWBI.cost.rCost,
109720                       sWBI.cost.rCost/pWInfo->a[j].rOptCost));
109721           sWBI.cost.rCost /= pWInfo->a[j].rOptCost;
109722         }
109723
109724         /* Conditions under which this table becomes the best so far:
109725         **
109726         **   (1) The table must not depend on other tables that have not
109727         **       yet run.  (In other words, it must not depend on tables
109728         **       in inner loops.)
109729         **
109730         **   (2) (This rule was removed on 2012-11-09.  The scaling of the
109731         **       cost using the optimal scan cost made this rule obsolete.)
109732         **
109733         **   (3) All tables have an INDEXED BY clause or this table lacks an
109734         **       INDEXED BY clause or this table uses the specific
109735         **       index specified by its INDEXED BY clause.  This rule ensures
109736         **       that a best-so-far is always selected even if an impossible
109737         **       combination of INDEXED BY clauses are given.  The error
109738         **       will be detected and relayed back to the application later.
109739         **       The NEVER() comes about because rule (2) above prevents
109740         **       An indexable full-table-scan from reaching rule (3).
109741         **
109742         **   (4) The plan cost must be lower than prior plans, where "cost"
109743         **       is defined by the compareCost() function above. 
109744         */
109745         if( (sWBI.cost.used&sWBI.notValid)==0                    /* (1) */
109746             && (nUnconstrained==0 || sWBI.pSrc->pIndex==0        /* (3) */
109747                 || NEVER((sWBI.cost.plan.wsFlags & WHERE_NOT_FULLSCAN)!=0))
109748             && (bestJ<0 || compareCost(&sWBI.cost, &bestPlan))   /* (4) */
109749         ){
109750           WHERETRACE(("   === table %d (%s) is best so far\n"
109751                       "       cost=%.1f, nRow=%.1f, nOBSat=%d, wsFlags=%08x\n",
109752                       j, sWBI.pSrc->pTab->zName,
109753                       sWBI.cost.rCost, sWBI.cost.plan.nRow,
109754                       sWBI.cost.plan.nOBSat, sWBI.cost.plan.wsFlags));
109755           bestPlan = sWBI.cost;
109756           bestJ = j;
109757         }
109758
109759         /* In a join like "w JOIN x LEFT JOIN y JOIN z"  make sure that
109760         ** table y (and not table z) is always the next inner loop inside
109761         ** of table x. */
109762         if( (sWBI.pSrc->jointype & JT_LEFT)!=0 ) break;
109763       }
109764     }
109765     assert( bestJ>=0 );
109766     assert( sWBI.notValid & getMask(pMaskSet, pTabList->a[bestJ].iCursor) );
109767     assert( bestJ==iFrom || (pTabList->a[iFrom].jointype & JT_LEFT)==0 );
109768     testcase( bestJ>iFrom && (pTabList->a[iFrom].jointype & JT_CROSS)!=0 );
109769     testcase( bestJ>iFrom && bestJ<nTabList-1
109770                           && (pTabList->a[bestJ+1].jointype & JT_LEFT)!=0 );
109771     WHERETRACE(("*** Optimizer selects table %d (%s) for loop %d with:\n"
109772                 "    cost=%.1f, nRow=%.1f, nOBSat=%d, wsFlags=0x%08x\n",
109773                 bestJ, pTabList->a[bestJ].pTab->zName,
109774                 pLevel-pWInfo->a, bestPlan.rCost, bestPlan.plan.nRow,
109775                 bestPlan.plan.nOBSat, bestPlan.plan.wsFlags));
109776     if( (bestPlan.plan.wsFlags & WHERE_DISTINCT)!=0 ){
109777       assert( pWInfo->eDistinct==0 );
109778       pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
109779     }
109780     andFlags &= bestPlan.plan.wsFlags;
109781     pLevel->plan = bestPlan.plan;
109782     pLevel->iTabCur = pTabList->a[bestJ].iCursor;
109783     testcase( bestPlan.plan.wsFlags & WHERE_INDEXED );
109784     testcase( bestPlan.plan.wsFlags & WHERE_TEMP_INDEX );
109785     if( bestPlan.plan.wsFlags & (WHERE_INDEXED|WHERE_TEMP_INDEX) ){
109786       if( (wctrlFlags & WHERE_ONETABLE_ONLY) 
109787        && (bestPlan.plan.wsFlags & WHERE_TEMP_INDEX)==0 
109788       ){
109789         pLevel->iIdxCur = iIdxCur;
109790       }else{
109791         pLevel->iIdxCur = pParse->nTab++;
109792       }
109793     }else{
109794       pLevel->iIdxCur = -1;
109795     }
109796     sWBI.notValid &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
109797     pLevel->iFrom = (u8)bestJ;
109798     if( bestPlan.plan.nRow>=(double)1 ){
109799       pParse->nQueryLoop *= bestPlan.plan.nRow;
109800     }
109801
109802     /* Check that if the table scanned by this loop iteration had an
109803     ** INDEXED BY clause attached to it, that the named index is being
109804     ** used for the scan. If not, then query compilation has failed.
109805     ** Return an error.
109806     */
109807     pIdx = pTabList->a[bestJ].pIndex;
109808     if( pIdx ){
109809       if( (bestPlan.plan.wsFlags & WHERE_INDEXED)==0 ){
109810         sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
109811         goto whereBeginError;
109812       }else{
109813         /* If an INDEXED BY clause is used, the bestIndex() function is
109814         ** guaranteed to find the index specified in the INDEXED BY clause
109815         ** if it find an index at all. */
109816         assert( bestPlan.plan.u.pIdx==pIdx );
109817       }
109818     }
109819   }
109820   WHERETRACE(("*** Optimizer Finished ***\n"));
109821   if( pParse->nErr || db->mallocFailed ){
109822     goto whereBeginError;
109823   }
109824   if( nTabList ){
109825     pLevel--;
109826     pWInfo->nOBSat = pLevel->plan.nOBSat;
109827   }else{
109828     pWInfo->nOBSat = 0;
109829   }
109830
109831   /* If the total query only selects a single row, then the ORDER BY
109832   ** clause is irrelevant.
109833   */
109834   if( (andFlags & WHERE_UNIQUE)!=0 && pOrderBy ){
109835     assert( nTabList==0 || (pLevel->plan.wsFlags & WHERE_ALL_UNIQUE)!=0 );
109836     pWInfo->nOBSat = pOrderBy->nExpr;
109837   }
109838
109839   /* If the caller is an UPDATE or DELETE statement that is requesting
109840   ** to use a one-pass algorithm, determine if this is appropriate.
109841   ** The one-pass algorithm only works if the WHERE clause constraints
109842   ** the statement to update a single row.
109843   */
109844   assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
109845   if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
109846     pWInfo->okOnePass = 1;
109847     pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;
109848   }
109849
109850   /* Open all tables in the pTabList and any indices selected for
109851   ** searching those tables.
109852   */
109853   sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
109854   notReady = ~(Bitmask)0;
109855   pWInfo->nRowOut = (double)1;
109856   for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
109857     Table *pTab;     /* Table to open */
109858     int iDb;         /* Index of database containing table/index */
109859     struct SrcList_item *pTabItem;
109860
109861     pTabItem = &pTabList->a[pLevel->iFrom];
109862     pTab = pTabItem->pTab;
109863     pWInfo->nRowOut *= pLevel->plan.nRow;
109864     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
109865     if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
109866       /* Do nothing */
109867     }else
109868 #ifndef SQLITE_OMIT_VIRTUALTABLE
109869     if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
109870       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
109871       int iCur = pTabItem->iCursor;
109872       sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
109873     }else if( IsVirtual(pTab) ){
109874       /* noop */
109875     }else
109876 #endif
109877     if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
109878          && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
109879       int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
109880       sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
109881       testcase( pTab->nCol==BMS-1 );
109882       testcase( pTab->nCol==BMS );
109883       if( !pWInfo->okOnePass && pTab->nCol<BMS ){
109884         Bitmask b = pTabItem->colUsed;
109885         int n = 0;
109886         for(; b; b=b>>1, n++){}
109887         sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1, 
109888                             SQLITE_INT_TO_PTR(n), P4_INT32);
109889         assert( n<=pTab->nCol );
109890       }
109891     }else{
109892       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
109893     }
109894 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
109895     if( (pLevel->plan.wsFlags & WHERE_TEMP_INDEX)!=0 ){
109896       constructAutomaticIndex(pParse, sWBI.pWC, pTabItem, notReady, pLevel);
109897     }else
109898 #endif
109899     if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
109900       Index *pIx = pLevel->plan.u.pIdx;
109901       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
109902       int iIndexCur = pLevel->iIdxCur;
109903       assert( pIx->pSchema==pTab->pSchema );
109904       assert( iIndexCur>=0 );
109905       sqlite3VdbeAddOp4(v, OP_OpenRead, iIndexCur, pIx->tnum, iDb,
109906                         (char*)pKey, P4_KEYINFO_HANDOFF);
109907       VdbeComment((v, "%s", pIx->zName));
109908     }
109909     sqlite3CodeVerifySchema(pParse, iDb);
109910     notReady &= ~getMask(sWBI.pWC->pMaskSet, pTabItem->iCursor);
109911   }
109912   pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
109913   if( db->mallocFailed ) goto whereBeginError;
109914
109915   /* Generate the code to do the search.  Each iteration of the for
109916   ** loop below generates code for a single nested loop of the VM
109917   ** program.
109918   */
109919   notReady = ~(Bitmask)0;
109920   for(ii=0; ii<nTabList; ii++){
109921     pLevel = &pWInfo->a[ii];
109922     explainOneScan(pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags);
109923     notReady = codeOneLoopStart(pWInfo, ii, wctrlFlags, notReady);
109924     pWInfo->iContinue = pLevel->addrCont;
109925   }
109926
109927 #ifdef SQLITE_TEST  /* For testing and debugging use only */
109928   /* Record in the query plan information about the current table
109929   ** and the index used to access it (if any).  If the table itself
109930   ** is not used, its name is just '{}'.  If no index is used
109931   ** the index is listed as "{}".  If the primary key is used the
109932   ** index name is '*'.
109933   */
109934   for(ii=0; ii<nTabList; ii++){
109935     char *z;
109936     int n;
109937     int w;
109938     struct SrcList_item *pTabItem;
109939
109940     pLevel = &pWInfo->a[ii];
109941     w = pLevel->plan.wsFlags;
109942     pTabItem = &pTabList->a[pLevel->iFrom];
109943     z = pTabItem->zAlias;
109944     if( z==0 ) z = pTabItem->pTab->zName;
109945     n = sqlite3Strlen30(z);
109946     if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
109947       if( (w & WHERE_IDX_ONLY)!=0 && (w & WHERE_COVER_SCAN)==0 ){
109948         memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
109949         nQPlan += 2;
109950       }else{
109951         memcpy(&sqlite3_query_plan[nQPlan], z, n);
109952         nQPlan += n;
109953       }
109954       sqlite3_query_plan[nQPlan++] = ' ';
109955     }
109956     testcase( w & WHERE_ROWID_EQ );
109957     testcase( w & WHERE_ROWID_RANGE );
109958     if( w & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
109959       memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
109960       nQPlan += 2;
109961     }else if( (w & WHERE_INDEXED)!=0 && (w & WHERE_COVER_SCAN)==0 ){
109962       n = sqlite3Strlen30(pLevel->plan.u.pIdx->zName);
109963       if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
109964         memcpy(&sqlite3_query_plan[nQPlan], pLevel->plan.u.pIdx->zName, n);
109965         nQPlan += n;
109966         sqlite3_query_plan[nQPlan++] = ' ';
109967       }
109968     }else{
109969       memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
109970       nQPlan += 3;
109971     }
109972   }
109973   while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
109974     sqlite3_query_plan[--nQPlan] = 0;
109975   }
109976   sqlite3_query_plan[nQPlan] = 0;
109977   nQPlan = 0;
109978 #endif /* SQLITE_TEST // Testing and debugging use only */
109979
109980   /* Record the continuation address in the WhereInfo structure.  Then
109981   ** clean up and return.
109982   */
109983   return pWInfo;
109984
109985   /* Jump here if malloc fails */
109986 whereBeginError:
109987   if( pWInfo ){
109988     pParse->nQueryLoop = pWInfo->savedNQueryLoop;
109989     whereInfoFree(db, pWInfo);
109990   }
109991   return 0;
109992 }
109993
109994 /*
109995 ** Generate the end of the WHERE loop.  See comments on 
109996 ** sqlite3WhereBegin() for additional information.
109997 */
109998 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
109999   Parse *pParse = pWInfo->pParse;
110000   Vdbe *v = pParse->pVdbe;
110001   int i;
110002   WhereLevel *pLevel;
110003   SrcList *pTabList = pWInfo->pTabList;
110004   sqlite3 *db = pParse->db;
110005
110006   /* Generate loop termination code.
110007   */
110008   sqlite3ExprCacheClear(pParse);
110009   for(i=pWInfo->nLevel-1; i>=0; i--){
110010     pLevel = &pWInfo->a[i];
110011     sqlite3VdbeResolveLabel(v, pLevel->addrCont);
110012     if( pLevel->op!=OP_Noop ){
110013       sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
110014       sqlite3VdbeChangeP5(v, pLevel->p5);
110015     }
110016     if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
110017       struct InLoop *pIn;
110018       int j;
110019       sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
110020       for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
110021         sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
110022         sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
110023         sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
110024       }
110025       sqlite3DbFree(db, pLevel->u.in.aInLoop);
110026     }
110027     sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
110028     if( pLevel->iLeftJoin ){
110029       int addr;
110030       addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
110031       assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
110032            || (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 );
110033       if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
110034         sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
110035       }
110036       if( pLevel->iIdxCur>=0 ){
110037         sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
110038       }
110039       if( pLevel->op==OP_Return ){
110040         sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
110041       }else{
110042         sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
110043       }
110044       sqlite3VdbeJumpHere(v, addr);
110045     }
110046   }
110047
110048   /* The "break" point is here, just past the end of the outer loop.
110049   ** Set it.
110050   */
110051   sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
110052
110053   /* Close all of the cursors that were opened by sqlite3WhereBegin.
110054   */
110055   assert( pWInfo->nLevel==1 || pWInfo->nLevel==pTabList->nSrc );
110056   for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
110057     Index *pIdx = 0;
110058     struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
110059     Table *pTab = pTabItem->pTab;
110060     assert( pTab!=0 );
110061     if( (pTab->tabFlags & TF_Ephemeral)==0
110062      && pTab->pSelect==0
110063      && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
110064     ){
110065       int ws = pLevel->plan.wsFlags;
110066       if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
110067         sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
110068       }
110069       if( (ws & WHERE_INDEXED)!=0 && (ws & WHERE_TEMP_INDEX)==0 ){
110070         sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
110071       }
110072     }
110073
110074     /* If this scan uses an index, make code substitutions to read data
110075     ** from the index in preference to the table. Sometimes, this means
110076     ** the table need never be read from. This is a performance boost,
110077     ** as the vdbe level waits until the table is read before actually
110078     ** seeking the table cursor to the record corresponding to the current
110079     ** position in the index.
110080     ** 
110081     ** Calls to the code generator in between sqlite3WhereBegin and
110082     ** sqlite3WhereEnd will have created code that references the table
110083     ** directly.  This loop scans all that code looking for opcodes
110084     ** that reference the table and converts them into opcodes that
110085     ** reference the index.
110086     */
110087     if( pLevel->plan.wsFlags & WHERE_INDEXED ){
110088       pIdx = pLevel->plan.u.pIdx;
110089     }else if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
110090       pIdx = pLevel->u.pCovidx;
110091     }
110092     if( pIdx && !db->mallocFailed){
110093       int k, j, last;
110094       VdbeOp *pOp;
110095
110096       pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
110097       last = sqlite3VdbeCurrentAddr(v);
110098       for(k=pWInfo->iTop; k<last; k++, pOp++){
110099         if( pOp->p1!=pLevel->iTabCur ) continue;
110100         if( pOp->opcode==OP_Column ){
110101           for(j=0; j<pIdx->nColumn; j++){
110102             if( pOp->p2==pIdx->aiColumn[j] ){
110103               pOp->p2 = j;
110104               pOp->p1 = pLevel->iIdxCur;
110105               break;
110106             }
110107           }
110108           assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
110109                || j<pIdx->nColumn );
110110         }else if( pOp->opcode==OP_Rowid ){
110111           pOp->p1 = pLevel->iIdxCur;
110112           pOp->opcode = OP_IdxRowid;
110113         }
110114       }
110115     }
110116   }
110117
110118   /* Final cleanup
110119   */
110120   pParse->nQueryLoop = pWInfo->savedNQueryLoop;
110121   whereInfoFree(db, pWInfo);
110122   return;
110123 }
110124
110125 /************** End of where.c ***********************************************/
110126 /************** Begin file parse.c *******************************************/
110127 /* Driver template for the LEMON parser generator.
110128 ** The author disclaims copyright to this source code.
110129 **
110130 ** This version of "lempar.c" is modified, slightly, for use by SQLite.
110131 ** The only modifications are the addition of a couple of NEVER()
110132 ** macros to disable tests that are needed in the case of a general
110133 ** LALR(1) grammar but which are always false in the
110134 ** specific grammar used by SQLite.
110135 */
110136 /* First off, code is included that follows the "include" declaration
110137 ** in the input grammar file. */
110138 /* #include <stdio.h> */
110139
110140
110141 /*
110142 ** Disable all error recovery processing in the parser push-down
110143 ** automaton.
110144 */
110145 #define YYNOERRORRECOVERY 1
110146
110147 /*
110148 ** Make yytestcase() the same as testcase()
110149 */
110150 #define yytestcase(X) testcase(X)
110151
110152 /*
110153 ** An instance of this structure holds information about the
110154 ** LIMIT clause of a SELECT statement.
110155 */
110156 struct LimitVal {
110157   Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
110158   Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
110159 };
110160
110161 /*
110162 ** An instance of this structure is used to store the LIKE,
110163 ** GLOB, NOT LIKE, and NOT GLOB operators.
110164 */
110165 struct LikeOp {
110166   Token eOperator;  /* "like" or "glob" or "regexp" */
110167   int bNot;         /* True if the NOT keyword is present */
110168 };
110169
110170 /*
110171 ** An instance of the following structure describes the event of a
110172 ** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
110173 ** TK_DELETE, or TK_INSTEAD.  If the event is of the form
110174 **
110175 **      UPDATE ON (a,b,c)
110176 **
110177 ** Then the "b" IdList records the list "a,b,c".
110178 */
110179 struct TrigEvent { int a; IdList * b; };
110180
110181 /*
110182 ** An instance of this structure holds the ATTACH key and the key type.
110183 */
110184 struct AttachKey { int type;  Token key; };
110185
110186 /*
110187 ** One or more VALUES claues
110188 */
110189 struct ValueList {
110190   ExprList *pList;
110191   Select *pSelect;
110192 };
110193
110194
110195   /* This is a utility routine used to set the ExprSpan.zStart and
110196   ** ExprSpan.zEnd values of pOut so that the span covers the complete
110197   ** range of text beginning with pStart and going to the end of pEnd.
110198   */
110199   static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
110200     pOut->zStart = pStart->z;
110201     pOut->zEnd = &pEnd->z[pEnd->n];
110202   }
110203
110204   /* Construct a new Expr object from a single identifier.  Use the
110205   ** new Expr to populate pOut.  Set the span of pOut to be the identifier
110206   ** that created the expression.
110207   */
110208   static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
110209     pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
110210     pOut->zStart = pValue->z;
110211     pOut->zEnd = &pValue->z[pValue->n];
110212   }
110213
110214   /* This routine constructs a binary expression node out of two ExprSpan
110215   ** objects and uses the result to populate a new ExprSpan object.
110216   */
110217   static void spanBinaryExpr(
110218     ExprSpan *pOut,     /* Write the result here */
110219     Parse *pParse,      /* The parsing context.  Errors accumulate here */
110220     int op,             /* The binary operation */
110221     ExprSpan *pLeft,    /* The left operand */
110222     ExprSpan *pRight    /* The right operand */
110223   ){
110224     pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
110225     pOut->zStart = pLeft->zStart;
110226     pOut->zEnd = pRight->zEnd;
110227   }
110228
110229   /* Construct an expression node for a unary postfix operator
110230   */
110231   static void spanUnaryPostfix(
110232     ExprSpan *pOut,        /* Write the new expression node here */
110233     Parse *pParse,         /* Parsing context to record errors */
110234     int op,                /* The operator */
110235     ExprSpan *pOperand,    /* The operand */
110236     Token *pPostOp         /* The operand token for setting the span */
110237   ){
110238     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
110239     pOut->zStart = pOperand->zStart;
110240     pOut->zEnd = &pPostOp->z[pPostOp->n];
110241   }                           
110242
110243   /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
110244   ** unary TK_ISNULL or TK_NOTNULL expression. */
110245   static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
110246     sqlite3 *db = pParse->db;
110247     if( db->mallocFailed==0 && pY->op==TK_NULL ){
110248       pA->op = (u8)op;
110249       sqlite3ExprDelete(db, pA->pRight);
110250       pA->pRight = 0;
110251     }
110252   }
110253
110254   /* Construct an expression node for a unary prefix operator
110255   */
110256   static void spanUnaryPrefix(
110257     ExprSpan *pOut,        /* Write the new expression node here */
110258     Parse *pParse,         /* Parsing context to record errors */
110259     int op,                /* The operator */
110260     ExprSpan *pOperand,    /* The operand */
110261     Token *pPreOp         /* The operand token for setting the span */
110262   ){
110263     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
110264     pOut->zStart = pPreOp->z;
110265     pOut->zEnd = pOperand->zEnd;
110266   }
110267 /* Next is all token values, in a form suitable for use by makeheaders.
110268 ** This section will be null unless lemon is run with the -m switch.
110269 */
110270 /* 
110271 ** These constants (all generated automatically by the parser generator)
110272 ** specify the various kinds of tokens (terminals) that the parser
110273 ** understands. 
110274 **
110275 ** Each symbol here is a terminal symbol in the grammar.
110276 */
110277 /* Make sure the INTERFACE macro is defined.
110278 */
110279 #ifndef INTERFACE
110280 # define INTERFACE 1
110281 #endif
110282 /* The next thing included is series of defines which control
110283 ** various aspects of the generated parser.
110284 **    YYCODETYPE         is the data type used for storing terminal
110285 **                       and nonterminal numbers.  "unsigned char" is
110286 **                       used if there are fewer than 250 terminals
110287 **                       and nonterminals.  "int" is used otherwise.
110288 **    YYNOCODE           is a number of type YYCODETYPE which corresponds
110289 **                       to no legal terminal or nonterminal number.  This
110290 **                       number is used to fill in empty slots of the hash 
110291 **                       table.
110292 **    YYFALLBACK         If defined, this indicates that one or more tokens
110293 **                       have fall-back values which should be used if the
110294 **                       original value of the token will not parse.
110295 **    YYACTIONTYPE       is the data type used for storing terminal
110296 **                       and nonterminal numbers.  "unsigned char" is
110297 **                       used if there are fewer than 250 rules and
110298 **                       states combined.  "int" is used otherwise.
110299 **    sqlite3ParserTOKENTYPE     is the data type used for minor tokens given 
110300 **                       directly to the parser from the tokenizer.
110301 **    YYMINORTYPE        is the data type used for all minor tokens.
110302 **                       This is typically a union of many types, one of
110303 **                       which is sqlite3ParserTOKENTYPE.  The entry in the union
110304 **                       for base tokens is called "yy0".
110305 **    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
110306 **                       zero the stack is dynamically sized using realloc()
110307 **    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
110308 **    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
110309 **    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
110310 **    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
110311 **    YYNSTATE           the combined number of states.
110312 **    YYNRULE            the number of rules in the grammar
110313 **    YYERRORSYMBOL      is the code number of the error symbol.  If not
110314 **                       defined, then do no error processing.
110315 */
110316 #define YYCODETYPE unsigned char
110317 #define YYNOCODE 251
110318 #define YYACTIONTYPE unsigned short int
110319 #define YYWILDCARD 67
110320 #define sqlite3ParserTOKENTYPE Token
110321 typedef union {
110322   int yyinit;
110323   sqlite3ParserTOKENTYPE yy0;
110324   struct LimitVal yy64;
110325   Expr* yy122;
110326   Select* yy159;
110327   IdList* yy180;
110328   struct {int value; int mask;} yy207;
110329   u8 yy258;
110330   u16 yy305;
110331   struct LikeOp yy318;
110332   TriggerStep* yy327;
110333   ExprSpan yy342;
110334   SrcList* yy347;
110335   int yy392;
110336   struct TrigEvent yy410;
110337   ExprList* yy442;
110338   struct ValueList yy487;
110339 } YYMINORTYPE;
110340 #ifndef YYSTACKDEPTH
110341 #define YYSTACKDEPTH 100
110342 #endif
110343 #define sqlite3ParserARG_SDECL Parse *pParse;
110344 #define sqlite3ParserARG_PDECL ,Parse *pParse
110345 #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
110346 #define sqlite3ParserARG_STORE yypParser->pParse = pParse
110347 #define YYNSTATE 627
110348 #define YYNRULE 327
110349 #define YYFALLBACK 1
110350 #define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
110351 #define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
110352 #define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)
110353
110354 /* The yyzerominor constant is used to initialize instances of
110355 ** YYMINORTYPE objects to zero. */
110356 static const YYMINORTYPE yyzerominor = { 0 };
110357
110358 /* Define the yytestcase() macro to be a no-op if is not already defined
110359 ** otherwise.
110360 **
110361 ** Applications can choose to define yytestcase() in the %include section
110362 ** to a macro that can assist in verifying code coverage.  For production
110363 ** code the yytestcase() macro should be turned off.  But it is useful
110364 ** for testing.
110365 */
110366 #ifndef yytestcase
110367 # define yytestcase(X)
110368 #endif
110369
110370
110371 /* Next are the tables used to determine what action to take based on the
110372 ** current state and lookahead token.  These tables are used to implement
110373 ** functions that take a state number and lookahead value and return an
110374 ** action integer.  
110375 **
110376 ** Suppose the action integer is N.  Then the action is determined as
110377 ** follows
110378 **
110379 **   0 <= N < YYNSTATE                  Shift N.  That is, push the lookahead
110380 **                                      token onto the stack and goto state N.
110381 **
110382 **   YYNSTATE <= N < YYNSTATE+YYNRULE   Reduce by rule N-YYNSTATE.
110383 **
110384 **   N == YYNSTATE+YYNRULE              A syntax error has occurred.
110385 **
110386 **   N == YYNSTATE+YYNRULE+1            The parser accepts its input.
110387 **
110388 **   N == YYNSTATE+YYNRULE+2            No such action.  Denotes unused
110389 **                                      slots in the yy_action[] table.
110390 **
110391 ** The action table is constructed as a single large table named yy_action[].
110392 ** Given state S and lookahead X, the action is computed as
110393 **
110394 **      yy_action[ yy_shift_ofst[S] + X ]
110395 **
110396 ** If the index value yy_shift_ofst[S]+X is out of range or if the value
110397 ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
110398 ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
110399 ** and that yy_default[S] should be used instead.  
110400 **
110401 ** The formula above is for computing the action when the lookahead is
110402 ** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
110403 ** a reduce action) then the yy_reduce_ofst[] array is used in place of
110404 ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
110405 ** YY_SHIFT_USE_DFLT.
110406 **
110407 ** The following are the tables generated in this section:
110408 **
110409 **  yy_action[]        A single table containing all actions.
110410 **  yy_lookahead[]     A table containing the lookahead for each entry in
110411 **                     yy_action.  Used to detect hash collisions.
110412 **  yy_shift_ofst[]    For each state, the offset into yy_action for
110413 **                     shifting terminals.
110414 **  yy_reduce_ofst[]   For each state, the offset into yy_action for
110415 **                     shifting non-terminals after a reduce.
110416 **  yy_default[]       Default action for each state.
110417 */
110418 #define YY_ACTTAB_COUNT (1564)
110419 static const YYACTIONTYPE yy_action[] = {
110420  /*     0 */   309,  955,  184,  417,    2,  171,  624,  594,   56,   56,
110421  /*    10 */    56,   56,   49,   54,   54,   54,   54,   53,   53,   52,
110422  /*    20 */    52,   52,   51,  233,  620,  619,  298,  620,  619,  234,
110423  /*    30 */   587,  581,   56,   56,   56,   56,   19,   54,   54,   54,
110424  /*    40 */    54,   53,   53,   52,   52,   52,   51,  233,  605,   57,
110425  /*    50 */    58,   48,  579,  578,  580,  580,   55,   55,   56,   56,
110426  /*    60 */    56,   56,  541,   54,   54,   54,   54,   53,   53,   52,
110427  /*    70 */    52,   52,   51,  233,  309,  594,  325,  196,  195,  194,
110428  /*    80 */    33,   54,   54,   54,   54,   53,   53,   52,   52,   52,
110429  /*    90 */    51,  233,  617,  616,  165,  617,  616,  380,  377,  376,
110430  /*   100 */   407,  532,  576,  576,  587,  581,  303,  422,  375,   59,
110431  /*   110 */    53,   53,   52,   52,   52,   51,  233,   50,   47,  146,
110432  /*   120 */   574,  545,   65,   57,   58,   48,  579,  578,  580,  580,
110433  /*   130 */    55,   55,   56,   56,   56,   56,  213,   54,   54,   54,
110434  /*   140 */    54,   53,   53,   52,   52,   52,   51,  233,  309,  223,
110435  /*   150 */   539,  420,  170,  176,  138,  280,  383,  275,  382,  168,
110436  /*   160 */   489,  551,  409,  668,  620,  619,  271,  438,  409,  438,
110437  /*   170 */   550,  604,   67,  482,  507,  618,  599,  412,  587,  581,
110438  /*   180 */   600,  483,  618,  412,  618,  598,   91,  439,  440,  439,
110439  /*   190 */   335,  598,   73,  669,  222,  266,  480,   57,   58,   48,
110440  /*   200 */   579,  578,  580,  580,   55,   55,   56,   56,   56,   56,
110441  /*   210 */   670,   54,   54,   54,   54,   53,   53,   52,   52,   52,
110442  /*   220 */    51,  233,  309,  279,  232,  231,    1,  132,  200,  385,
110443  /*   230 */   620,  619,  617,  616,  278,  435,  289,  563,  175,  262,
110444  /*   240 */   409,  264,  437,  497,  436,  166,  441,  568,  336,  568,
110445  /*   250 */   201,  537,  587,  581,  599,  412,  165,  594,  600,  380,
110446  /*   260 */   377,  376,  597,  598,   92,  523,  618,  569,  569,  592,
110447  /*   270 */   375,   57,   58,   48,  579,  578,  580,  580,   55,   55,
110448  /*   280 */    56,   56,   56,   56,  597,   54,   54,   54,   54,   53,
110449  /*   290 */    53,   52,   52,   52,   51,  233,  309,  463,  617,  616,
110450  /*   300 */   590,  590,  590,  174,  272,  396,  409,  272,  409,  548,
110451  /*   310 */   397,  620,  619,   68,  326,  620,  619,  620,  619,  618,
110452  /*   320 */   546,  412,  618,  412,  471,  594,  587,  581,  472,  598,
110453  /*   330 */    92,  598,   92,   52,   52,   52,   51,  233,  513,  512,
110454  /*   340 */   206,  322,  363,  464,  221,   57,   58,   48,  579,  578,
110455  /*   350 */   580,  580,   55,   55,   56,   56,   56,   56,  529,   54,
110456  /*   360 */    54,   54,   54,   53,   53,   52,   52,   52,   51,  233,
110457  /*   370 */   309,  396,  409,  396,  597,  372,  386,  530,  347,  617,
110458  /*   380 */   616,  575,  202,  617,  616,  617,  616,  412,  620,  619,
110459  /*   390 */   145,  255,  346,  254,  577,  598,   74,  351,   45,  489,
110460  /*   400 */   587,  581,  235,  189,  464,  544,  167,  296,  187,  469,
110461  /*   410 */   479,   67,   62,   39,  618,  546,  597,  345,  573,   57,
110462  /*   420 */    58,   48,  579,  578,  580,  580,   55,   55,   56,   56,
110463  /*   430 */    56,   56,    6,   54,   54,   54,   54,   53,   53,   52,
110464  /*   440 */    52,   52,   51,  233,  309,  562,  558,  407,  528,  576,
110465  /*   450 */   576,  344,  255,  346,  254,  182,  617,  616,  503,  504,
110466  /*   460 */   314,  409,  557,  235,  166,  271,  409,  352,  564,  181,
110467  /*   470 */   407,  546,  576,  576,  587,  581,  412,  537,  556,  561,
110468  /*   480 */   517,  412,  618,  249,  598,   16,    7,   36,  467,  598,
110469  /*   490 */    92,  516,  618,   57,   58,   48,  579,  578,  580,  580,
110470  /*   500 */    55,   55,   56,   56,   56,   56,  541,   54,   54,   54,
110471  /*   510 */    54,   53,   53,   52,   52,   52,   51,  233,  309,  327,
110472  /*   520 */   572,  571,  525,  558,  560,  394,  871,  246,  409,  248,
110473  /*   530 */   171,  392,  594,  219,  407,  409,  576,  576,  502,  557,
110474  /*   540 */   364,  145,  510,  412,  407,  229,  576,  576,  587,  581,
110475  /*   550 */   412,  598,   92,  381,  269,  556,  166,  400,  598,   69,
110476  /*   560 */   501,  419,  945,  199,  945,  198,  546,   57,   58,   48,
110477  /*   570 */   579,  578,  580,  580,   55,   55,   56,   56,   56,   56,
110478  /*   580 */   568,   54,   54,   54,   54,   53,   53,   52,   52,   52,
110479  /*   590 */    51,  233,  309,  317,  419,  944,  508,  944,  308,  597,
110480  /*   600 */   594,  565,  490,  212,  173,  247,  423,  615,  614,  613,
110481  /*   610 */   323,  197,  143,  405,  572,  571,  489,   66,   50,   47,
110482  /*   620 */   146,  594,  587,  581,  232,  231,  559,  427,   67,  555,
110483  /*   630 */    15,  618,  186,  543,  303,  421,   35,  206,  432,  423,
110484  /*   640 */   552,   57,   58,   48,  579,  578,  580,  580,   55,   55,
110485  /*   650 */    56,   56,   56,   56,  205,   54,   54,   54,   54,   53,
110486  /*   660 */    53,   52,   52,   52,   51,  233,  309,  569,  569,  260,
110487  /*   670 */   268,  597,   12,  373,  568,  166,  409,  313,  409,  420,
110488  /*   680 */   409,  473,  473,  365,  618,   50,   47,  146,  597,  594,
110489  /*   690 */   468,  412,  166,  412,  351,  412,  587,  581,   32,  598,
110490  /*   700 */    94,  598,   97,  598,   95,  627,  625,  329,  142,   50,
110491  /*   710 */    47,  146,  333,  349,  358,   57,   58,   48,  579,  578,
110492  /*   720 */   580,  580,   55,   55,   56,   56,   56,   56,  409,   54,
110493  /*   730 */    54,   54,   54,   53,   53,   52,   52,   52,   51,  233,
110494  /*   740 */   309,  409,  388,  412,  409,   22,  565,  404,  212,  362,
110495  /*   750 */   389,  598,  104,  359,  409,  156,  412,  409,  603,  412,
110496  /*   760 */   537,  331,  569,  569,  598,  103,  493,  598,  105,  412,
110497  /*   770 */   587,  581,  412,  260,  549,  618,   11,  598,  106,  521,
110498  /*   780 */   598,  133,  169,  457,  456,  170,   35,  601,  618,   57,
110499  /*   790 */    58,   48,  579,  578,  580,  580,   55,   55,   56,   56,
110500  /*   800 */    56,   56,  409,   54,   54,   54,   54,   53,   53,   52,
110501  /*   810 */    52,   52,   51,  233,  309,  409,  259,  412,  409,   50,
110502  /*   820 */    47,  146,  357,  318,  355,  598,  134,  527,  352,  337,
110503  /*   830 */   412,  409,  356,  412,  357,  409,  357,  618,  598,   98,
110504  /*   840 */   129,  598,  102,  618,  587,  581,  412,   21,  235,  618,
110505  /*   850 */   412,  618,  211,  143,  598,  101,   30,  167,  598,   93,
110506  /*   860 */   350,  535,  203,   57,   58,   48,  579,  578,  580,  580,
110507  /*   870 */    55,   55,   56,   56,   56,   56,  409,   54,   54,   54,
110508  /*   880 */    54,   53,   53,   52,   52,   52,   51,  233,  309,  409,
110509  /*   890 */   526,  412,  409,  425,  215,  305,  597,  551,  141,  598,
110510  /*   900 */   100,   40,  409,   38,  412,  409,  550,  412,  409,  228,
110511  /*   910 */   220,  314,  598,   77,  500,  598,   96,  412,  587,  581,
110512  /*   920 */   412,  338,  253,  412,  218,  598,  137,  379,  598,  136,
110513  /*   930 */    28,  598,  135,  270,  715,  210,  481,   57,   58,   48,
110514  /*   940 */   579,  578,  580,  580,   55,   55,   56,   56,   56,   56,
110515  /*   950 */   409,   54,   54,   54,   54,   53,   53,   52,   52,   52,
110516  /*   960 */    51,  233,  309,  409,  272,  412,  409,  315,  147,  597,
110517  /*   970 */   272,  626,    2,  598,   76,  209,  409,  127,  412,  618,
110518  /*   980 */   126,  412,  409,  621,  235,  618,  598,   90,  374,  598,
110519  /*   990 */    89,  412,  587,  581,   27,  260,  350,  412,  618,  598,
110520  /*  1000 */    75,  321,  541,  541,  125,  598,   88,  320,  278,  597,
110521  /*  1010 */   618,   57,   46,   48,  579,  578,  580,  580,   55,   55,
110522  /*  1020 */    56,   56,   56,   56,  409,   54,   54,   54,   54,   53,
110523  /*  1030 */    53,   52,   52,   52,   51,  233,  309,  409,  450,  412,
110524  /*  1040 */   164,  284,  282,  272,  609,  424,  304,  598,   87,  370,
110525  /*  1050 */   409,  477,  412,  409,  608,  409,  607,  602,  618,  618,
110526  /*  1060 */   598,   99,  586,  585,  122,  412,  587,  581,  412,  618,
110527  /*  1070 */   412,  618,  618,  598,   86,  366,  598,   17,  598,   85,
110528  /*  1080 */   319,  185,  519,  518,  583,  582,   58,   48,  579,  578,
110529  /*  1090 */   580,  580,   55,   55,   56,   56,   56,   56,  409,   54,
110530  /*  1100 */    54,   54,   54,   53,   53,   52,   52,   52,   51,  233,
110531  /*  1110 */   309,  584,  409,  412,  409,  260,  260,  260,  408,  591,
110532  /*  1120 */   474,  598,   84,  170,  409,  466,  518,  412,  121,  412,
110533  /*  1130 */   618,  618,  618,  618,  618,  598,   83,  598,   72,  412,
110534  /*  1140 */   587,  581,   51,  233,  625,  329,  470,  598,   71,  257,
110535  /*  1150 */   159,  120,   14,  462,  157,  158,  117,  260,  448,  447,
110536  /*  1160 */   446,   48,  579,  578,  580,  580,   55,   55,   56,   56,
110537  /*  1170 */    56,   56,  618,   54,   54,   54,   54,   53,   53,   52,
110538  /*  1180 */    52,   52,   51,  233,   44,  403,  260,    3,  409,  459,
110539  /*  1190 */   260,  413,  619,  118,  398,   10,   25,   24,  554,  348,
110540  /*  1200 */   217,  618,  406,  412,  409,  618,    4,   44,  403,  618,
110541  /*  1210 */     3,  598,   82,  618,  413,  619,  455,  542,  115,  412,
110542  /*  1220 */   538,  401,  536,  274,  506,  406,  251,  598,   81,  216,
110543  /*  1230 */   273,  563,  618,  243,  453,  618,  154,  618,  618,  618,
110544  /*  1240 */   449,  416,  623,  110,  401,  618,  409,  236,   64,  123,
110545  /*  1250 */   487,   41,   42,  531,  563,  204,  409,  267,   43,  411,
110546  /*  1260 */   410,  412,  265,  592,  108,  618,  107,  434,  332,  598,
110547  /*  1270 */    80,  412,  618,  263,   41,   42,  443,  618,  409,  598,
110548  /*  1280 */    70,   43,  411,  410,  433,  261,  592,  149,  618,  597,
110549  /*  1290 */   256,  237,  188,  412,  590,  590,  590,  589,  588,   13,
110550  /*  1300 */   618,  598,   18,  328,  235,  618,   44,  403,  360,    3,
110551  /*  1310 */   418,  461,  339,  413,  619,  227,  124,  590,  590,  590,
110552  /*  1320 */   589,  588,   13,  618,  406,  409,  618,  409,  139,   34,
110553  /*  1330 */   403,  387,    3,  148,  622,  312,  413,  619,  311,  330,
110554  /*  1340 */   412,  460,  412,  401,  180,  353,  412,  406,  598,   79,
110555  /*  1350 */   598,   78,  250,  563,  598,    9,  618,  612,  611,  610,
110556  /*  1360 */   618,    8,  452,  442,  242,  415,  401,  618,  239,  235,
110557  /*  1370 */   179,  238,  428,   41,   42,  288,  563,  618,  618,  618,
110558  /*  1380 */    43,  411,  410,  618,  144,  592,  618,  618,  177,   61,
110559  /*  1390 */   618,  596,  391,  620,  619,  287,   41,   42,  414,  618,
110560  /*  1400 */   293,   30,  393,   43,  411,  410,  292,  618,  592,   31,
110561  /*  1410 */   618,  395,  291,   60,  230,   37,  590,  590,  590,  589,
110562  /*  1420 */   588,   13,  214,  553,  183,  290,  172,  301,  300,  299,
110563  /*  1430 */   178,  297,  595,  563,  451,   29,  285,  390,  540,  590,
110564  /*  1440 */   590,  590,  589,  588,   13,  283,  520,  534,  150,  533,
110565  /*  1450 */   241,  281,  384,  192,  191,  324,  515,  514,  276,  240,
110566  /*  1460 */   510,  523,  307,  511,  128,  592,  509,  225,  226,  486,
110567  /*  1470 */   485,  224,  152,  491,  464,  306,  484,  163,  153,  371,
110568  /*  1480 */   478,  151,  162,  258,  369,  161,  367,  208,  475,  476,
110569  /*  1490 */    26,  160,  465,  140,  361,  131,  590,  590,  590,  116,
110570  /*  1500 */   119,  454,  343,  155,  114,  342,  113,  112,  445,  111,
110571  /*  1510 */   130,  109,  431,  316,  426,  430,   23,  429,   20,  606,
110572  /*  1520 */   190,  507,  255,  341,  244,   63,  294,  593,  310,  570,
110573  /*  1530 */   277,  402,  354,  235,  567,  496,  495,  492,  494,  302,
110574  /*  1540 */   458,  378,  286,  245,  566,    5,  252,  547,  193,  444,
110575  /*  1550 */   233,  340,  207,  524,  368,  505,  334,  522,  499,  399,
110576  /*  1560 */   295,  498,  956,  488,
110577 };
110578 static const YYCODETYPE yy_lookahead[] = {
110579  /*     0 */    19,  142,  143,  144,  145,   24,    1,   26,   77,   78,
110580  /*    10 */    79,   80,   81,   82,   83,   84,   85,   86,   87,   88,
110581  /*    20 */    89,   90,   91,   92,   26,   27,   15,   26,   27,  197,
110582  /*    30 */    49,   50,   77,   78,   79,   80,  204,   82,   83,   84,
110583  /*    40 */    85,   86,   87,   88,   89,   90,   91,   92,   23,   68,
110584  /*    50 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
110585  /*    60 */    79,   80,  166,   82,   83,   84,   85,   86,   87,   88,
110586  /*    70 */    89,   90,   91,   92,   19,   94,   19,  105,  106,  107,
110587  /*    80 */    25,   82,   83,   84,   85,   86,   87,   88,   89,   90,
110588  /*    90 */    91,   92,   94,   95,   96,   94,   95,   99,  100,  101,
110589  /*   100 */   112,  205,  114,  115,   49,   50,   22,   23,  110,   54,
110590  /*   110 */    86,   87,   88,   89,   90,   91,   92,  221,  222,  223,
110591  /*   120 */    23,  120,   25,   68,   69,   70,   71,   72,   73,   74,
110592  /*   130 */    75,   76,   77,   78,   79,   80,   22,   82,   83,   84,
110593  /*   140 */    85,   86,   87,   88,   89,   90,   91,   92,   19,   92,
110594  /*   150 */    23,   67,   25,   96,   97,   98,   99,  100,  101,  102,
110595  /*   160 */   150,   32,  150,  118,   26,   27,  109,  150,  150,  150,
110596  /*   170 */    41,  161,  162,  180,  181,  165,  113,  165,   49,   50,
110597  /*   180 */   117,  188,  165,  165,  165,  173,  174,  170,  171,  170,
110598  /*   190 */   171,  173,  174,  118,  184,   16,  186,   68,   69,   70,
110599  /*   200 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
110600  /*   210 */   118,   82,   83,   84,   85,   86,   87,   88,   89,   90,
110601  /*   220 */    91,   92,   19,   98,   86,   87,   22,   24,  160,   88,
110602  /*   230 */    26,   27,   94,   95,  109,   97,  224,   66,  118,   60,
110603  /*   240 */   150,   62,  104,   23,  106,   25,  229,  230,  229,  230,
110604  /*   250 */   160,  150,   49,   50,  113,  165,   96,   26,  117,   99,
110605  /*   260 */   100,  101,  194,  173,  174,   94,  165,  129,  130,   98,
110606  /*   270 */   110,   68,   69,   70,   71,   72,   73,   74,   75,   76,
110607  /*   280 */    77,   78,   79,   80,  194,   82,   83,   84,   85,   86,
110608  /*   290 */    87,   88,   89,   90,   91,   92,   19,   11,   94,   95,
110609  /*   300 */   129,  130,  131,  118,  150,  215,  150,  150,  150,   25,
110610  /*   310 */   220,   26,   27,   22,  213,   26,   27,   26,   27,  165,
110611  /*   320 */    25,  165,  165,  165,   30,   94,   49,   50,   34,  173,
110612  /*   330 */   174,  173,  174,   88,   89,   90,   91,   92,    7,    8,
110613  /*   340 */   160,  187,   48,   57,  187,   68,   69,   70,   71,   72,
110614  /*   350 */    73,   74,   75,   76,   77,   78,   79,   80,   23,   82,
110615  /*   360 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
110616  /*   370 */    19,  215,  150,  215,  194,   19,  220,   88,  220,   94,
110617  /*   380 */    95,   23,  160,   94,   95,   94,   95,  165,   26,   27,
110618  /*   390 */    95,  105,  106,  107,  113,  173,  174,  217,   22,  150,
110619  /*   400 */    49,   50,  116,  119,   57,  120,   50,  158,   22,   21,
110620  /*   410 */   161,  162,  232,  136,  165,  120,  194,  237,   23,   68,
110621  /*   420 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
110622  /*   430 */    79,   80,   22,   82,   83,   84,   85,   86,   87,   88,
110623  /*   440 */    89,   90,   91,   92,   19,   23,   12,  112,   23,  114,
110624  /*   450 */   115,   63,  105,  106,  107,   23,   94,   95,   97,   98,
110625  /*   460 */   104,  150,   28,  116,   25,  109,  150,  150,   23,   23,
110626  /*   470 */   112,   25,  114,  115,   49,   50,  165,  150,   44,   11,
110627  /*   480 */    46,  165,  165,   16,  173,  174,   76,  136,  100,  173,
110628  /*   490 */   174,   57,  165,   68,   69,   70,   71,   72,   73,   74,
110629  /*   500 */    75,   76,   77,   78,   79,   80,  166,   82,   83,   84,
110630  /*   510 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  169,
110631  /*   520 */   170,  171,   23,   12,   23,  214,  138,   60,  150,   62,
110632  /*   530 */    24,  215,   26,  216,  112,  150,  114,  115,   36,   28,
110633  /*   540 */   213,   95,  103,  165,  112,  205,  114,  115,   49,   50,
110634  /*   550 */   165,  173,  174,   51,   23,   44,   25,   46,  173,  174,
110635  /*   560 */    58,   22,   23,   22,   25,  160,  120,   68,   69,   70,
110636  /*   570 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
110637  /*   580 */   230,   82,   83,   84,   85,   86,   87,   88,   89,   90,
110638  /*   590 */    91,   92,   19,  215,   22,   23,   23,   25,  163,  194,
110639  /*   600 */    94,  166,  167,  168,   25,  138,   67,    7,    8,    9,
110640  /*   610 */   108,  206,  207,  169,  170,  171,  150,   22,  221,  222,
110641  /*   620 */   223,   26,   49,   50,   86,   87,   23,  161,  162,   23,
110642  /*   630 */    22,  165,   24,  120,   22,   23,   25,  160,  241,   67,
110643  /*   640 */   176,   68,   69,   70,   71,   72,   73,   74,   75,   76,
110644  /*   650 */    77,   78,   79,   80,  160,   82,   83,   84,   85,   86,
110645  /*   660 */    87,   88,   89,   90,   91,   92,   19,  129,  130,  150,
110646  /*   670 */    23,  194,   35,   23,  230,   25,  150,  155,  150,   67,
110647  /*   680 */   150,  105,  106,  107,  165,  221,  222,  223,  194,   94,
110648  /*   690 */    23,  165,   25,  165,  217,  165,   49,   50,   25,  173,
110649  /*   700 */   174,  173,  174,  173,  174,    0,    1,    2,  118,  221,
110650  /*   710 */   222,  223,  193,  219,  237,   68,   69,   70,   71,   72,
110651  /*   720 */    73,   74,   75,   76,   77,   78,   79,   80,  150,   82,
110652  /*   730 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
110653  /*   740 */    19,  150,   19,  165,  150,   24,  166,  167,  168,  227,
110654  /*   750 */    27,  173,  174,  231,  150,   25,  165,  150,  172,  165,
110655  /*   760 */   150,  242,  129,  130,  173,  174,  180,  173,  174,  165,
110656  /*   770 */    49,   50,  165,  150,  176,  165,   35,  173,  174,  165,
110657  /*   780 */   173,  174,   35,   23,   23,   25,   25,  173,  165,   68,
110658  /*   790 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
110659  /*   800 */    79,   80,  150,   82,   83,   84,   85,   86,   87,   88,
110660  /*   810 */    89,   90,   91,   92,   19,  150,  193,  165,  150,  221,
110661  /*   820 */   222,  223,  150,  213,   19,  173,  174,   23,  150,   97,
110662  /*   830 */   165,  150,   27,  165,  150,  150,  150,  165,  173,  174,
110663  /*   840 */    22,  173,  174,  165,   49,   50,  165,   52,  116,  165,
110664  /*   850 */   165,  165,  206,  207,  173,  174,  126,   50,  173,  174,
110665  /*   860 */   128,   27,  160,   68,   69,   70,   71,   72,   73,   74,
110666  /*   870 */    75,   76,   77,   78,   79,   80,  150,   82,   83,   84,
110667  /*   880 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  150,
110668  /*   890 */    23,  165,  150,   23,  216,   25,  194,   32,   39,  173,
110669  /*   900 */   174,  135,  150,  137,  165,  150,   41,  165,  150,   52,
110670  /*   910 */   238,  104,  173,  174,   29,  173,  174,  165,   49,   50,
110671  /*   920 */   165,  219,  238,  165,  238,  173,  174,   52,  173,  174,
110672  /*   930 */    22,  173,  174,   23,   23,  160,   25,   68,   69,   70,
110673  /*   940 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
110674  /*   950 */   150,   82,   83,   84,   85,   86,   87,   88,   89,   90,
110675  /*   960 */    91,   92,   19,  150,  150,  165,  150,  245,  246,  194,
110676  /*   970 */   150,  144,  145,  173,  174,  160,  150,   22,  165,  165,
110677  /*   980 */    22,  165,  150,  150,  116,  165,  173,  174,   52,  173,
110678  /*   990 */   174,  165,   49,   50,   22,  150,  128,  165,  165,  173,
110679  /*  1000 */   174,  187,  166,  166,   22,  173,  174,  187,  109,  194,
110680  /*  1010 */   165,   68,   69,   70,   71,   72,   73,   74,   75,   76,
110681  /*  1020 */    77,   78,   79,   80,  150,   82,   83,   84,   85,   86,
110682  /*  1030 */    87,   88,   89,   90,   91,   92,   19,  150,  193,  165,
110683  /*  1040 */   102,  205,  205,  150,  150,  247,  248,  173,  174,   19,
110684  /*  1050 */   150,   20,  165,  150,  150,  150,  150,  150,  165,  165,
110685  /*  1060 */   173,  174,   49,   50,  104,  165,   49,   50,  165,  165,
110686  /*  1070 */   165,  165,  165,  173,  174,   43,  173,  174,  173,  174,
110687  /*  1080 */   187,   24,  190,  191,   71,   72,   69,   70,   71,   72,
110688  /*  1090 */    73,   74,   75,   76,   77,   78,   79,   80,  150,   82,
110689  /*  1100 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
110690  /*  1110 */    19,   98,  150,  165,  150,  150,  150,  150,  150,  150,
110691  /*  1120 */    59,  173,  174,   25,  150,  190,  191,  165,   53,  165,
110692  /*  1130 */   165,  165,  165,  165,  165,  173,  174,  173,  174,  165,
110693  /*  1140 */    49,   50,   91,   92,    1,    2,   53,  173,  174,  138,
110694  /*  1150 */   104,   22,    5,    1,   35,  118,  127,  150,  193,  193,
110695  /*  1160 */   193,   70,   71,   72,   73,   74,   75,   76,   77,   78,
110696  /*  1170 */    79,   80,  165,   82,   83,   84,   85,   86,   87,   88,
110697  /*  1180 */    89,   90,   91,   92,   19,   20,  150,   22,  150,   27,
110698  /*  1190 */   150,   26,   27,  108,  150,   22,   76,   76,  150,   25,
110699  /*  1200 */   193,  165,   37,  165,  150,  165,   22,   19,   20,  165,
110700  /*  1210 */    22,  173,  174,  165,   26,   27,   23,  150,  119,  165,
110701  /*  1220 */   150,   56,  150,  150,  150,   37,   16,  173,  174,  193,
110702  /*  1230 */   150,   66,  165,  193,    1,  165,  121,  165,  165,  165,
110703  /*  1240 */    20,  146,  147,  119,   56,  165,  150,  152,   16,  154,
110704  /*  1250 */   150,   86,   87,   88,   66,  160,  150,  150,   93,   94,
110705  /*  1260 */    95,  165,  150,   98,  108,  165,  127,   23,   65,  173,
110706  /*  1270 */   174,  165,  165,  150,   86,   87,  128,  165,  150,  173,
110707  /*  1280 */   174,   93,   94,   95,   23,  150,   98,   15,  165,  194,
110708  /*  1290 */   150,  140,   22,  165,  129,  130,  131,  132,  133,  134,
110709  /*  1300 */   165,  173,  174,    3,  116,  165,   19,   20,  150,   22,
110710  /*  1310 */     4,  150,  217,   26,   27,  179,  179,  129,  130,  131,
110711  /*  1320 */   132,  133,  134,  165,   37,  150,  165,  150,  164,   19,
110712  /*  1330 */    20,  150,   22,  246,  149,  249,   26,   27,  249,  244,
110713  /*  1340 */   165,  150,  165,   56,    6,  150,  165,   37,  173,  174,
110714  /*  1350 */   173,  174,  150,   66,  173,  174,  165,  149,  149,   13,
110715  /*  1360 */   165,   25,  150,  150,  150,  149,   56,  165,  150,  116,
110716  /*  1370 */   151,  150,  150,   86,   87,  150,   66,  165,  165,  165,
110717  /*  1380 */    93,   94,   95,  165,  150,   98,  165,  165,  151,   22,
110718  /*  1390 */   165,  194,  150,   26,   27,  150,   86,   87,  159,  165,
110719  /*  1400 */   199,  126,  123,   93,   94,   95,  200,  165,   98,  124,
110720  /*  1410 */   165,  122,  201,  125,  225,  135,  129,  130,  131,  132,
110721  /*  1420 */   133,  134,    5,  157,  157,  202,  118,   10,   11,   12,
110722  /*  1430 */    13,   14,  203,   66,   17,  104,  210,  121,  211,  129,
110723  /*  1440 */   130,  131,  132,  133,  134,  210,  175,  211,   31,  211,
110724  /*  1450 */    33,  210,  104,   86,   87,   47,  175,  183,  175,   42,
110725  /*  1460 */   103,   94,  178,  177,   22,   98,  175,   92,  228,  175,
110726  /*  1470 */   175,  228,   55,  183,   57,  178,  175,  156,   61,   18,
110727  /*  1480 */   157,   64,  156,  235,  157,  156,   45,  157,  236,  157,
110728  /*  1490 */   135,  156,  189,   68,  157,  218,  129,  130,  131,   22,
110729  /*  1500 */   189,  199,  157,  156,  192,   18,  192,  192,  199,  192,
110730  /*  1510 */   218,  189,   40,  157,   38,  157,  240,  157,  240,  153,
110731  /*  1520 */   196,  181,  105,  106,  107,  243,  198,  166,  111,  230,
110732  /*  1530 */   176,  226,  239,  116,  230,  176,  166,  166,  176,  148,
110733  /*  1540 */   199,  177,  209,  209,  166,  196,  239,  208,  185,  199,
110734  /*  1550 */    92,  209,  233,  173,  234,  182,  139,  173,  182,  191,
110735  /*  1560 */   195,  182,  250,  186,
110736 };
110737 #define YY_SHIFT_USE_DFLT (-70)
110738 #define YY_SHIFT_COUNT (416)
110739 #define YY_SHIFT_MIN   (-69)
110740 #define YY_SHIFT_MAX   (1487)
110741 static const short yy_shift_ofst[] = {
110742  /*     0 */  1143, 1188, 1417, 1188, 1287, 1287,  138,  138,   -2,  -19,
110743  /*    10 */  1287, 1287, 1287, 1287,  347,  362,  129,  129,  795, 1165,
110744  /*    20 */  1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
110745  /*    30 */  1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
110746  /*    40 */  1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1310, 1287,
110747  /*    50 */  1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
110748  /*    60 */  1287, 1287,  286,  362,  362,  538,  538,  231, 1253,   55,
110749  /*    70 */   721,  647,  573,  499,  425,  351,  277,  203,  869,  869,
110750  /*    80 */   869,  869,  869,  869,  869,  869,  869,  869,  869,  869,
110751  /*    90 */   869,  869,  869,  943,  869, 1017, 1091, 1091,  -69,  -45,
110752  /*   100 */   -45,  -45,  -45,  -45,   -1,   24,  245,  362,  362,  362,
110753  /*   110 */   362,  362,  362,  362,  362,  362,  362,  362,  362,  362,
110754  /*   120 */   362,  362,  362,  388,  356,  362,  362,  362,  362,  362,
110755  /*   130 */   732,  868,  231, 1051, 1458,  -70,  -70,  -70, 1367,   57,
110756  /*   140 */   434,  434,  289,  291,  285,    1,  204,  572,  539,  362,
110757  /*   150 */   362,  362,  362,  362,  362,  362,  362,  362,  362,  362,
110758  /*   160 */   362,  362,  362,  362,  362,  362,  362,  362,  362,  362,
110759  /*   170 */   362,  362,  362,  362,  362,  362,  362,  362,  362,  362,
110760  /*   180 */   362,  506,  506,  506,  705, 1253, 1253, 1253,  -70,  -70,
110761  /*   190 */   -70,  171,  171,  160,  502,  502,  502,  446,  432,  511,
110762  /*   200 */   422,  358,  335,  -12,  -12,  -12,  -12,  576,  294,  -12,
110763  /*   210 */   -12,  295,  595,  141,  600,  730,  723,  723,  805,  730,
110764  /*   220 */   805,  439,  911,  231,  865,  231,  865,  807,  865,  723,
110765  /*   230 */   766,  633,  633,  231,  284,   63,  608, 1476, 1308, 1308,
110766  /*   240 */  1472, 1472, 1308, 1477, 1425, 1275, 1487, 1487, 1487, 1487,
110767  /*   250 */  1308, 1461, 1275, 1477, 1425, 1425, 1308, 1461, 1355, 1441,
110768  /*   260 */  1308, 1308, 1461, 1308, 1461, 1308, 1461, 1442, 1348, 1348,
110769  /*   270 */  1348, 1408, 1375, 1375, 1442, 1348, 1357, 1348, 1408, 1348,
110770  /*   280 */  1348, 1316, 1331, 1316, 1331, 1316, 1331, 1308, 1308, 1280,
110771  /*   290 */  1288, 1289, 1285, 1279, 1275, 1253, 1336, 1346, 1346, 1338,
110772  /*   300 */  1338, 1338, 1338,  -70,  -70,  -70,  -70,  -70,  -70, 1013,
110773  /*   310 */   467,  612,   84,  179,  -28,  870,  410,  761,  760,  667,
110774  /*   320 */   650,  531,  220,  361,  331,  125,  127,   97, 1306, 1300,
110775  /*   330 */  1270, 1151, 1272, 1203, 1232, 1261, 1244, 1148, 1174, 1139,
110776  /*   340 */  1156, 1124, 1220, 1115, 1210, 1233, 1099, 1193, 1184, 1174,
110777  /*   350 */  1173, 1029, 1121, 1120, 1085, 1162, 1119, 1037, 1152, 1147,
110778  /*   360 */  1129, 1046, 1011, 1093, 1098, 1075, 1061, 1032,  960, 1057,
110779  /*   370 */  1031, 1030,  899,  938,  982,  936,  972,  958,  910,  955,
110780  /*   380 */   875,  885,  908,  857,  859,  867,  804,  590,  834,  747,
110781  /*   390 */   818,  513,  611,  741,  673,  637,  611,  606,  603,  579,
110782  /*   400 */   501,  541,  468,  386,  445,  395,  376,  281,  185,  120,
110783  /*   410 */    92,   75,   45,  114,   25,   11,    5,
110784 };
110785 #define YY_REDUCE_USE_DFLT (-169)
110786 #define YY_REDUCE_COUNT (308)
110787 #define YY_REDUCE_MIN   (-168)
110788 #define YY_REDUCE_MAX   (1391)
110789 static const short yy_reduce_ofst[] = {
110790  /*     0 */  -141,   90, 1095,  222,  158,  156,   19,   17,   10, -104,
110791  /*    10 */   378,  316,  311,   12,  180,  249,  598,  464,  397, 1181,
110792  /*    20 */  1177, 1175, 1128, 1106, 1096, 1054, 1038,  974,  964,  962,
110793  /*    30 */   948,  905,  903,  900,  887,  874,  832,  826,  816,  813,
110794  /*    40 */   800,  758,  755,  752,  742,  739,  726,  685,  681,  668,
110795  /*    50 */   665,  652,  607,  604,  594,  591,  578,  530,  528,  526,
110796  /*    60 */   385,   18,  477,  466,  519,  444,  350,  435,  405,  488,
110797  /*    70 */   488,  488,  488,  488,  488,  488,  488,  488,  488,  488,
110798  /*    80 */   488,  488,  488,  488,  488,  488,  488,  488,  488,  488,
110799  /*    90 */   488,  488,  488,  488,  488,  488,  488,  488,  488,  488,
110800  /*   100 */   488,  488,  488,  488,  488,  488,  488, 1040,  678, 1036,
110801  /*   110 */  1007,  967,  966,  965,  845,  686,  610,  684,  317,  672,
110802  /*   120 */   893,  327,  623,  522,   -7,  820,  814,  157,  154,  101,
110803  /*   130 */   702,  494,  580,  488,  488,  488,  488,  488,  614,  586,
110804  /*   140 */   935,  892,  968, 1245, 1242, 1234, 1225,  798,  798, 1222,
110805  /*   150 */  1221, 1218, 1214, 1213, 1212, 1202, 1195, 1191, 1161, 1158,
110806  /*   160 */  1140, 1135, 1123, 1112, 1107, 1100, 1080, 1074, 1073, 1072,
110807  /*   170 */  1070, 1067, 1048, 1044,  969,  968,  907,  906,  904,  894,
110808  /*   180 */   833,  837,  836,  340,  827,  815,  775,   68,  722,  646,
110809  /*   190 */  -168, 1384, 1380, 1377, 1379, 1376, 1373, 1339, 1365, 1368,
110810  /*   200 */  1365, 1365, 1365, 1365, 1365, 1365, 1365, 1320, 1319, 1365,
110811  /*   210 */  1365, 1339, 1378, 1349, 1391, 1350, 1342, 1334, 1307, 1341,
110812  /*   220 */  1293, 1364, 1363, 1371, 1362, 1370, 1359, 1340, 1354, 1333,
110813  /*   230 */  1305, 1304, 1299, 1361, 1328, 1324, 1366, 1282, 1360, 1358,
110814  /*   240 */  1278, 1276, 1356, 1292, 1322, 1309, 1317, 1315, 1314, 1312,
110815  /*   250 */  1345, 1347, 1302, 1277, 1311, 1303, 1337, 1335, 1252, 1248,
110816  /*   260 */  1332, 1330, 1329, 1327, 1326, 1323, 1321, 1297, 1301, 1295,
110817  /*   270 */  1294, 1290, 1243, 1240, 1284, 1291, 1286, 1283, 1274, 1281,
110818  /*   280 */  1271, 1238, 1241, 1236, 1235, 1227, 1226, 1267, 1266, 1189,
110819  /*   290 */  1229, 1223, 1211, 1206, 1201, 1197, 1239, 1237, 1219, 1216,
110820  /*   300 */  1209, 1208, 1185, 1089, 1086, 1087, 1137, 1136, 1164,
110821 };
110822 static const YYACTIONTYPE yy_default[] = {
110823  /*     0 */   632,  866,  954,  954,  866,  866,  954,  954,  954,  756,
110824  /*    10 */   954,  954,  954,  864,  954,  954,  784,  784,  928,  954,
110825  /*    20 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
110826  /*    30 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
110827  /*    40 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
110828  /*    50 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
110829  /*    60 */   954,  954,  954,  954,  954,  954,  954,  671,  760,  790,
110830  /*    70 */   954,  954,  954,  954,  954,  954,  954,  954,  927,  929,
110831  /*    80 */   798,  797,  907,  771,  795,  788,  792,  867,  860,  861,
110832  /*    90 */   859,  863,  868,  954,  791,  827,  844,  826,  838,  843,
110833  /*   100 */   850,  842,  839,  829,  828,  830,  831,  954,  954,  954,
110834  /*   110 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
110835  /*   120 */   954,  954,  954,  658,  725,  954,  954,  954,  954,  954,
110836  /*   130 */   954,  954,  954,  832,  833,  847,  846,  845,  954,  663,
110837  /*   140 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
110838  /*   150 */   934,  932,  954,  879,  954,  954,  954,  954,  954,  954,
110839  /*   160 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
110840  /*   170 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
110841  /*   180 */   638,  756,  756,  756,  632,  954,  954,  954,  946,  760,
110842  /*   190 */   750,  954,  954,  954,  954,  954,  954,  954,  954,  954,
110843  /*   200 */   954,  954,  954,  800,  739,  917,  919,  954,  900,  737,
110844  /*   210 */   660,  758,  673,  748,  640,  794,  773,  773,  912,  794,
110845  /*   220 */   912,  696,  719,  954,  784,  954,  784,  693,  784,  773,
110846  /*   230 */   862,  954,  954,  954,  757,  748,  954,  939,  764,  764,
110847  /*   240 */   931,  931,  764,  806,  729,  794,  736,  736,  736,  736,
110848  /*   250 */   764,  655,  794,  806,  729,  729,  764,  655,  906,  904,
110849  /*   260 */   764,  764,  655,  764,  655,  764,  655,  872,  727,  727,
110850  /*   270 */   727,  711,  876,  876,  872,  727,  696,  727,  711,  727,
110851  /*   280 */   727,  777,  772,  777,  772,  777,  772,  764,  764,  954,
110852  /*   290 */   789,  778,  787,  785,  794,  954,  714,  648,  648,  637,
110853  /*   300 */   637,  637,  637,  951,  951,  946,  698,  698,  681,  954,
110854  /*   310 */   954,  954,  954,  954,  954,  954,  881,  954,  954,  954,
110855  /*   320 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  633,
110856  /*   330 */   941,  954,  954,  938,  954,  954,  954,  954,  799,  954,
110857  /*   340 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  916,
110858  /*   350 */   954,  954,  954,  954,  954,  954,  954,  910,  954,  954,
110859  /*   360 */   954,  954,  954,  954,  903,  902,  954,  954,  954,  954,
110860  /*   370 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
110861  /*   380 */   954,  954,  954,  954,  954,  954,  954,  954,  954,  954,
110862  /*   390 */   954,  954,  786,  954,  779,  954,  865,  954,  954,  954,
110863  /*   400 */   954,  954,  954,  954,  954,  954,  954,  742,  815,  954,
110864  /*   410 */   814,  818,  813,  665,  954,  646,  954,  629,  634,  950,
110865  /*   420 */   953,  952,  949,  948,  947,  942,  940,  937,  936,  935,
110866  /*   430 */   933,  930,  926,  885,  883,  890,  889,  888,  887,  886,
110867  /*   440 */   884,  882,  880,  801,  796,  793,  925,  878,  738,  735,
110868  /*   450 */   734,  654,  943,  909,  918,  805,  804,  807,  915,  914,
110869  /*   460 */   913,  911,  908,  895,  803,  802,  730,  870,  869,  657,
110870  /*   470 */   899,  898,  897,  901,  905,  896,  766,  656,  653,  662,
110871  /*   480 */   717,  718,  726,  724,  723,  722,  721,  720,  716,  664,
110872  /*   490 */   672,  710,  695,  694,  875,  877,  874,  873,  703,  702,
110873  /*   500 */   708,  707,  706,  705,  704,  701,  700,  699,  692,  691,
110874  /*   510 */   697,  690,  713,  712,  709,  689,  733,  732,  731,  728,
110875  /*   520 */   688,  687,  686,  818,  685,  684,  824,  823,  811,  854,
110876  /*   530 */   753,  752,  751,  763,  762,  775,  774,  809,  808,  776,
110877  /*   540 */   761,  755,  754,  770,  769,  768,  767,  759,  749,  781,
110878  /*   550 */   783,  782,  780,  856,  765,  853,  924,  923,  922,  921,
110879  /*   560 */   920,  858,  857,  825,  822,  676,  677,  893,  892,  894,
110880  /*   570 */   891,  679,  678,  675,  674,  855,  744,  743,  851,  848,
110881  /*   580 */   840,  836,  852,  849,  841,  837,  835,  834,  820,  819,
110882  /*   590 */   817,  816,  812,  821,  667,  745,  741,  740,  810,  747,
110883  /*   600 */   746,  683,  682,  680,  661,  659,  652,  650,  649,  651,
110884  /*   610 */   647,  645,  644,  643,  642,  641,  670,  669,  668,  666,
110885  /*   620 */   665,  639,  636,  635,  631,  630,  628,
110886 };
110887
110888 /* The next table maps tokens into fallback tokens.  If a construct
110889 ** like the following:
110890 ** 
110891 **      %fallback ID X Y Z.
110892 **
110893 ** appears in the grammar, then ID becomes a fallback token for X, Y,
110894 ** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
110895 ** but it does not parse, the type of the token is changed to ID and
110896 ** the parse is retried before an error is thrown.
110897 */
110898 #ifdef YYFALLBACK
110899 static const YYCODETYPE yyFallback[] = {
110900     0,  /*          $ => nothing */
110901     0,  /*       SEMI => nothing */
110902    26,  /*    EXPLAIN => ID */
110903    26,  /*      QUERY => ID */
110904    26,  /*       PLAN => ID */
110905    26,  /*      BEGIN => ID */
110906     0,  /* TRANSACTION => nothing */
110907    26,  /*   DEFERRED => ID */
110908    26,  /*  IMMEDIATE => ID */
110909    26,  /*  EXCLUSIVE => ID */
110910     0,  /*     COMMIT => nothing */
110911    26,  /*        END => ID */
110912    26,  /*   ROLLBACK => ID */
110913    26,  /*  SAVEPOINT => ID */
110914    26,  /*    RELEASE => ID */
110915     0,  /*         TO => nothing */
110916     0,  /*      TABLE => nothing */
110917     0,  /*     CREATE => nothing */
110918    26,  /*         IF => ID */
110919     0,  /*        NOT => nothing */
110920     0,  /*     EXISTS => nothing */
110921    26,  /*       TEMP => ID */
110922     0,  /*         LP => nothing */
110923     0,  /*         RP => nothing */
110924     0,  /*         AS => nothing */
110925     0,  /*      COMMA => nothing */
110926     0,  /*         ID => nothing */
110927     0,  /*    INDEXED => nothing */
110928    26,  /*      ABORT => ID */
110929    26,  /*     ACTION => ID */
110930    26,  /*      AFTER => ID */
110931    26,  /*    ANALYZE => ID */
110932    26,  /*        ASC => ID */
110933    26,  /*     ATTACH => ID */
110934    26,  /*     BEFORE => ID */
110935    26,  /*         BY => ID */
110936    26,  /*    CASCADE => ID */
110937    26,  /*       CAST => ID */
110938    26,  /*   COLUMNKW => ID */
110939    26,  /*   CONFLICT => ID */
110940    26,  /*   DATABASE => ID */
110941    26,  /*       DESC => ID */
110942    26,  /*     DETACH => ID */
110943    26,  /*       EACH => ID */
110944    26,  /*       FAIL => ID */
110945    26,  /*        FOR => ID */
110946    26,  /*     IGNORE => ID */
110947    26,  /*  INITIALLY => ID */
110948    26,  /*    INSTEAD => ID */
110949    26,  /*    LIKE_KW => ID */
110950    26,  /*      MATCH => ID */
110951    26,  /*         NO => ID */
110952    26,  /*        KEY => ID */
110953    26,  /*         OF => ID */
110954    26,  /*     OFFSET => ID */
110955    26,  /*     PRAGMA => ID */
110956    26,  /*      RAISE => ID */
110957    26,  /*    REPLACE => ID */
110958    26,  /*   RESTRICT => ID */
110959    26,  /*        ROW => ID */
110960    26,  /*    TRIGGER => ID */
110961    26,  /*     VACUUM => ID */
110962    26,  /*       VIEW => ID */
110963    26,  /*    VIRTUAL => ID */
110964    26,  /*    REINDEX => ID */
110965    26,  /*     RENAME => ID */
110966    26,  /*   CTIME_KW => ID */
110967 };
110968 #endif /* YYFALLBACK */
110969
110970 /* The following structure represents a single element of the
110971 ** parser's stack.  Information stored includes:
110972 **
110973 **   +  The state number for the parser at this level of the stack.
110974 **
110975 **   +  The value of the token stored at this level of the stack.
110976 **      (In other words, the "major" token.)
110977 **
110978 **   +  The semantic value stored at this level of the stack.  This is
110979 **      the information used by the action routines in the grammar.
110980 **      It is sometimes called the "minor" token.
110981 */
110982 struct yyStackEntry {
110983   YYACTIONTYPE stateno;  /* The state-number */
110984   YYCODETYPE major;      /* The major token value.  This is the code
110985                          ** number for the token at this stack level */
110986   YYMINORTYPE minor;     /* The user-supplied minor token value.  This
110987                          ** is the value of the token  */
110988 };
110989 typedef struct yyStackEntry yyStackEntry;
110990
110991 /* The state of the parser is completely contained in an instance of
110992 ** the following structure */
110993 struct yyParser {
110994   int yyidx;                    /* Index of top element in stack */
110995 #ifdef YYTRACKMAXSTACKDEPTH
110996   int yyidxMax;                 /* Maximum value of yyidx */
110997 #endif
110998   int yyerrcnt;                 /* Shifts left before out of the error */
110999   sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
111000 #if YYSTACKDEPTH<=0
111001   int yystksz;                  /* Current side of the stack */
111002   yyStackEntry *yystack;        /* The parser's stack */
111003 #else
111004   yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
111005 #endif
111006 };
111007 typedef struct yyParser yyParser;
111008
111009 #ifndef NDEBUG
111010 /* #include <stdio.h> */
111011 static FILE *yyTraceFILE = 0;
111012 static char *yyTracePrompt = 0;
111013 #endif /* NDEBUG */
111014
111015 #ifndef NDEBUG
111016 /* 
111017 ** Turn parser tracing on by giving a stream to which to write the trace
111018 ** and a prompt to preface each trace message.  Tracing is turned off
111019 ** by making either argument NULL 
111020 **
111021 ** Inputs:
111022 ** <ul>
111023 ** <li> A FILE* to which trace output should be written.
111024 **      If NULL, then tracing is turned off.
111025 ** <li> A prefix string written at the beginning of every
111026 **      line of trace output.  If NULL, then tracing is
111027 **      turned off.
111028 ** </ul>
111029 **
111030 ** Outputs:
111031 ** None.
111032 */
111033 SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
111034   yyTraceFILE = TraceFILE;
111035   yyTracePrompt = zTracePrompt;
111036   if( yyTraceFILE==0 ) yyTracePrompt = 0;
111037   else if( yyTracePrompt==0 ) yyTraceFILE = 0;
111038 }
111039 #endif /* NDEBUG */
111040
111041 #ifndef NDEBUG
111042 /* For tracing shifts, the names of all terminals and nonterminals
111043 ** are required.  The following table supplies these names */
111044 static const char *const yyTokenName[] = { 
111045   "$",             "SEMI",          "EXPLAIN",       "QUERY",       
111046   "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",    
111047   "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",         
111048   "ROLLBACK",      "SAVEPOINT",     "RELEASE",       "TO",          
111049   "TABLE",         "CREATE",        "IF",            "NOT",         
111050   "EXISTS",        "TEMP",          "LP",            "RP",          
111051   "AS",            "COMMA",         "ID",            "INDEXED",     
111052   "ABORT",         "ACTION",        "AFTER",         "ANALYZE",     
111053   "ASC",           "ATTACH",        "BEFORE",        "BY",          
111054   "CASCADE",       "CAST",          "COLUMNKW",      "CONFLICT",    
111055   "DATABASE",      "DESC",          "DETACH",        "EACH",        
111056   "FAIL",          "FOR",           "IGNORE",        "INITIALLY",   
111057   "INSTEAD",       "LIKE_KW",       "MATCH",         "NO",          
111058   "KEY",           "OF",            "OFFSET",        "PRAGMA",      
111059   "RAISE",         "REPLACE",       "RESTRICT",      "ROW",         
111060   "TRIGGER",       "VACUUM",        "VIEW",          "VIRTUAL",     
111061   "REINDEX",       "RENAME",        "CTIME_KW",      "ANY",         
111062   "OR",            "AND",           "IS",            "BETWEEN",     
111063   "IN",            "ISNULL",        "NOTNULL",       "NE",          
111064   "EQ",            "GT",            "LE",            "LT",          
111065   "GE",            "ESCAPE",        "BITAND",        "BITOR",       
111066   "LSHIFT",        "RSHIFT",        "PLUS",          "MINUS",       
111067   "STAR",          "SLASH",         "REM",           "CONCAT",      
111068   "COLLATE",       "BITNOT",        "STRING",        "JOIN_KW",     
111069   "CONSTRAINT",    "DEFAULT",       "NULL",          "PRIMARY",     
111070   "UNIQUE",        "CHECK",         "REFERENCES",    "AUTOINCR",    
111071   "ON",            "INSERT",        "DELETE",        "UPDATE",      
111072   "SET",           "DEFERRABLE",    "FOREIGN",       "DROP",        
111073   "UNION",         "ALL",           "EXCEPT",        "INTERSECT",   
111074   "SELECT",        "DISTINCT",      "DOT",           "FROM",        
111075   "JOIN",          "USING",         "ORDER",         "GROUP",       
111076   "HAVING",        "LIMIT",         "WHERE",         "INTO",        
111077   "VALUES",        "INTEGER",       "FLOAT",         "BLOB",        
111078   "REGISTER",      "VARIABLE",      "CASE",          "WHEN",        
111079   "THEN",          "ELSE",          "INDEX",         "ALTER",       
111080   "ADD",           "error",         "input",         "cmdlist",     
111081   "ecmd",          "explain",       "cmdx",          "cmd",         
111082   "transtype",     "trans_opt",     "nm",            "savepoint_opt",
111083   "create_table",  "create_table_args",  "createkw",      "temp",        
111084   "ifnotexists",   "dbnm",          "columnlist",    "conslist_opt",
111085   "select",        "column",        "columnid",      "type",        
111086   "carglist",      "id",            "ids",           "typetoken",   
111087   "typename",      "signed",        "plus_num",      "minus_num",   
111088   "ccons",         "term",          "expr",          "onconf",      
111089   "sortorder",     "autoinc",       "idxlist_opt",   "refargs",     
111090   "defer_subclause",  "refarg",        "refact",        "init_deferred_pred_opt",
111091   "conslist",      "tconscomma",    "tcons",         "idxlist",     
111092   "defer_subclause_opt",  "orconf",        "resolvetype",   "raisetype",   
111093   "ifexists",      "fullname",      "oneselect",     "multiselect_op",
111094   "distinct",      "selcollist",    "from",          "where_opt",   
111095   "groupby_opt",   "having_opt",    "orderby_opt",   "limit_opt",   
111096   "sclp",          "as",            "seltablist",    "stl_prefix",  
111097   "joinop",        "indexed_opt",   "on_opt",        "using_opt",   
111098   "joinop2",       "inscollist",    "sortlist",      "nexprlist",   
111099   "setlist",       "insert_cmd",    "inscollist_opt",  "valuelist",   
111100   "exprlist",      "likeop",        "between_op",    "in_op",       
111101   "case_operand",  "case_exprlist",  "case_else",     "uniqueflag",  
111102   "collate",       "nmnum",         "number",        "trigger_decl",
111103   "trigger_cmd_list",  "trigger_time",  "trigger_event",  "foreach_clause",
111104   "when_clause",   "trigger_cmd",   "trnm",          "tridxby",     
111105   "database_kw_opt",  "key_opt",       "add_column_fullname",  "kwcolumn_opt",
111106   "create_vtab",   "vtabarglist",   "vtabarg",       "vtabargtoken",
111107   "lp",            "anylist",     
111108 };
111109 #endif /* NDEBUG */
111110
111111 #ifndef NDEBUG
111112 /* For tracing reduce actions, the names of all rules are required.
111113 */
111114 static const char *const yyRuleName[] = {
111115  /*   0 */ "input ::= cmdlist",
111116  /*   1 */ "cmdlist ::= cmdlist ecmd",
111117  /*   2 */ "cmdlist ::= ecmd",
111118  /*   3 */ "ecmd ::= SEMI",
111119  /*   4 */ "ecmd ::= explain cmdx SEMI",
111120  /*   5 */ "explain ::=",
111121  /*   6 */ "explain ::= EXPLAIN",
111122  /*   7 */ "explain ::= EXPLAIN QUERY PLAN",
111123  /*   8 */ "cmdx ::= cmd",
111124  /*   9 */ "cmd ::= BEGIN transtype trans_opt",
111125  /*  10 */ "trans_opt ::=",
111126  /*  11 */ "trans_opt ::= TRANSACTION",
111127  /*  12 */ "trans_opt ::= TRANSACTION nm",
111128  /*  13 */ "transtype ::=",
111129  /*  14 */ "transtype ::= DEFERRED",
111130  /*  15 */ "transtype ::= IMMEDIATE",
111131  /*  16 */ "transtype ::= EXCLUSIVE",
111132  /*  17 */ "cmd ::= COMMIT trans_opt",
111133  /*  18 */ "cmd ::= END trans_opt",
111134  /*  19 */ "cmd ::= ROLLBACK trans_opt",
111135  /*  20 */ "savepoint_opt ::= SAVEPOINT",
111136  /*  21 */ "savepoint_opt ::=",
111137  /*  22 */ "cmd ::= SAVEPOINT nm",
111138  /*  23 */ "cmd ::= RELEASE savepoint_opt nm",
111139  /*  24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
111140  /*  25 */ "cmd ::= create_table create_table_args",
111141  /*  26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
111142  /*  27 */ "createkw ::= CREATE",
111143  /*  28 */ "ifnotexists ::=",
111144  /*  29 */ "ifnotexists ::= IF NOT EXISTS",
111145  /*  30 */ "temp ::= TEMP",
111146  /*  31 */ "temp ::=",
111147  /*  32 */ "create_table_args ::= LP columnlist conslist_opt RP",
111148  /*  33 */ "create_table_args ::= AS select",
111149  /*  34 */ "columnlist ::= columnlist COMMA column",
111150  /*  35 */ "columnlist ::= column",
111151  /*  36 */ "column ::= columnid type carglist",
111152  /*  37 */ "columnid ::= nm",
111153  /*  38 */ "id ::= ID",
111154  /*  39 */ "id ::= INDEXED",
111155  /*  40 */ "ids ::= ID|STRING",
111156  /*  41 */ "nm ::= id",
111157  /*  42 */ "nm ::= STRING",
111158  /*  43 */ "nm ::= JOIN_KW",
111159  /*  44 */ "type ::=",
111160  /*  45 */ "type ::= typetoken",
111161  /*  46 */ "typetoken ::= typename",
111162  /*  47 */ "typetoken ::= typename LP signed RP",
111163  /*  48 */ "typetoken ::= typename LP signed COMMA signed RP",
111164  /*  49 */ "typename ::= ids",
111165  /*  50 */ "typename ::= typename ids",
111166  /*  51 */ "signed ::= plus_num",
111167  /*  52 */ "signed ::= minus_num",
111168  /*  53 */ "carglist ::= carglist ccons",
111169  /*  54 */ "carglist ::=",
111170  /*  55 */ "ccons ::= CONSTRAINT nm",
111171  /*  56 */ "ccons ::= DEFAULT term",
111172  /*  57 */ "ccons ::= DEFAULT LP expr RP",
111173  /*  58 */ "ccons ::= DEFAULT PLUS term",
111174  /*  59 */ "ccons ::= DEFAULT MINUS term",
111175  /*  60 */ "ccons ::= DEFAULT id",
111176  /*  61 */ "ccons ::= NULL onconf",
111177  /*  62 */ "ccons ::= NOT NULL onconf",
111178  /*  63 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
111179  /*  64 */ "ccons ::= UNIQUE onconf",
111180  /*  65 */ "ccons ::= CHECK LP expr RP",
111181  /*  66 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
111182  /*  67 */ "ccons ::= defer_subclause",
111183  /*  68 */ "ccons ::= COLLATE ids",
111184  /*  69 */ "autoinc ::=",
111185  /*  70 */ "autoinc ::= AUTOINCR",
111186  /*  71 */ "refargs ::=",
111187  /*  72 */ "refargs ::= refargs refarg",
111188  /*  73 */ "refarg ::= MATCH nm",
111189  /*  74 */ "refarg ::= ON INSERT refact",
111190  /*  75 */ "refarg ::= ON DELETE refact",
111191  /*  76 */ "refarg ::= ON UPDATE refact",
111192  /*  77 */ "refact ::= SET NULL",
111193  /*  78 */ "refact ::= SET DEFAULT",
111194  /*  79 */ "refact ::= CASCADE",
111195  /*  80 */ "refact ::= RESTRICT",
111196  /*  81 */ "refact ::= NO ACTION",
111197  /*  82 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
111198  /*  83 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
111199  /*  84 */ "init_deferred_pred_opt ::=",
111200  /*  85 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
111201  /*  86 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
111202  /*  87 */ "conslist_opt ::=",
111203  /*  88 */ "conslist_opt ::= COMMA conslist",
111204  /*  89 */ "conslist ::= conslist tconscomma tcons",
111205  /*  90 */ "conslist ::= tcons",
111206  /*  91 */ "tconscomma ::= COMMA",
111207  /*  92 */ "tconscomma ::=",
111208  /*  93 */ "tcons ::= CONSTRAINT nm",
111209  /*  94 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
111210  /*  95 */ "tcons ::= UNIQUE LP idxlist RP onconf",
111211  /*  96 */ "tcons ::= CHECK LP expr RP onconf",
111212  /*  97 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
111213  /*  98 */ "defer_subclause_opt ::=",
111214  /*  99 */ "defer_subclause_opt ::= defer_subclause",
111215  /* 100 */ "onconf ::=",
111216  /* 101 */ "onconf ::= ON CONFLICT resolvetype",
111217  /* 102 */ "orconf ::=",
111218  /* 103 */ "orconf ::= OR resolvetype",
111219  /* 104 */ "resolvetype ::= raisetype",
111220  /* 105 */ "resolvetype ::= IGNORE",
111221  /* 106 */ "resolvetype ::= REPLACE",
111222  /* 107 */ "cmd ::= DROP TABLE ifexists fullname",
111223  /* 108 */ "ifexists ::= IF EXISTS",
111224  /* 109 */ "ifexists ::=",
111225  /* 110 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
111226  /* 111 */ "cmd ::= DROP VIEW ifexists fullname",
111227  /* 112 */ "cmd ::= select",
111228  /* 113 */ "select ::= oneselect",
111229  /* 114 */ "select ::= select multiselect_op oneselect",
111230  /* 115 */ "multiselect_op ::= UNION",
111231  /* 116 */ "multiselect_op ::= UNION ALL",
111232  /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
111233  /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
111234  /* 119 */ "distinct ::= DISTINCT",
111235  /* 120 */ "distinct ::= ALL",
111236  /* 121 */ "distinct ::=",
111237  /* 122 */ "sclp ::= selcollist COMMA",
111238  /* 123 */ "sclp ::=",
111239  /* 124 */ "selcollist ::= sclp expr as",
111240  /* 125 */ "selcollist ::= sclp STAR",
111241  /* 126 */ "selcollist ::= sclp nm DOT STAR",
111242  /* 127 */ "as ::= AS nm",
111243  /* 128 */ "as ::= ids",
111244  /* 129 */ "as ::=",
111245  /* 130 */ "from ::=",
111246  /* 131 */ "from ::= FROM seltablist",
111247  /* 132 */ "stl_prefix ::= seltablist joinop",
111248  /* 133 */ "stl_prefix ::=",
111249  /* 134 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
111250  /* 135 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
111251  /* 136 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
111252  /* 137 */ "dbnm ::=",
111253  /* 138 */ "dbnm ::= DOT nm",
111254  /* 139 */ "fullname ::= nm dbnm",
111255  /* 140 */ "joinop ::= COMMA|JOIN",
111256  /* 141 */ "joinop ::= JOIN_KW JOIN",
111257  /* 142 */ "joinop ::= JOIN_KW nm JOIN",
111258  /* 143 */ "joinop ::= JOIN_KW nm nm JOIN",
111259  /* 144 */ "on_opt ::= ON expr",
111260  /* 145 */ "on_opt ::=",
111261  /* 146 */ "indexed_opt ::=",
111262  /* 147 */ "indexed_opt ::= INDEXED BY nm",
111263  /* 148 */ "indexed_opt ::= NOT INDEXED",
111264  /* 149 */ "using_opt ::= USING LP inscollist RP",
111265  /* 150 */ "using_opt ::=",
111266  /* 151 */ "orderby_opt ::=",
111267  /* 152 */ "orderby_opt ::= ORDER BY sortlist",
111268  /* 153 */ "sortlist ::= sortlist COMMA expr sortorder",
111269  /* 154 */ "sortlist ::= expr sortorder",
111270  /* 155 */ "sortorder ::= ASC",
111271  /* 156 */ "sortorder ::= DESC",
111272  /* 157 */ "sortorder ::=",
111273  /* 158 */ "groupby_opt ::=",
111274  /* 159 */ "groupby_opt ::= GROUP BY nexprlist",
111275  /* 160 */ "having_opt ::=",
111276  /* 161 */ "having_opt ::= HAVING expr",
111277  /* 162 */ "limit_opt ::=",
111278  /* 163 */ "limit_opt ::= LIMIT expr",
111279  /* 164 */ "limit_opt ::= LIMIT expr OFFSET expr",
111280  /* 165 */ "limit_opt ::= LIMIT expr COMMA expr",
111281  /* 166 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt",
111282  /* 167 */ "where_opt ::=",
111283  /* 168 */ "where_opt ::= WHERE expr",
111284  /* 169 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt",
111285  /* 170 */ "setlist ::= setlist COMMA nm EQ expr",
111286  /* 171 */ "setlist ::= nm EQ expr",
111287  /* 172 */ "cmd ::= insert_cmd INTO fullname inscollist_opt valuelist",
111288  /* 173 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
111289  /* 174 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
111290  /* 175 */ "insert_cmd ::= INSERT orconf",
111291  /* 176 */ "insert_cmd ::= REPLACE",
111292  /* 177 */ "valuelist ::= VALUES LP nexprlist RP",
111293  /* 178 */ "valuelist ::= valuelist COMMA LP exprlist RP",
111294  /* 179 */ "inscollist_opt ::=",
111295  /* 180 */ "inscollist_opt ::= LP inscollist RP",
111296  /* 181 */ "inscollist ::= inscollist COMMA nm",
111297  /* 182 */ "inscollist ::= nm",
111298  /* 183 */ "expr ::= term",
111299  /* 184 */ "expr ::= LP expr RP",
111300  /* 185 */ "term ::= NULL",
111301  /* 186 */ "expr ::= id",
111302  /* 187 */ "expr ::= JOIN_KW",
111303  /* 188 */ "expr ::= nm DOT nm",
111304  /* 189 */ "expr ::= nm DOT nm DOT nm",
111305  /* 190 */ "term ::= INTEGER|FLOAT|BLOB",
111306  /* 191 */ "term ::= STRING",
111307  /* 192 */ "expr ::= REGISTER",
111308  /* 193 */ "expr ::= VARIABLE",
111309  /* 194 */ "expr ::= expr COLLATE ids",
111310  /* 195 */ "expr ::= CAST LP expr AS typetoken RP",
111311  /* 196 */ "expr ::= ID LP distinct exprlist RP",
111312  /* 197 */ "expr ::= ID LP STAR RP",
111313  /* 198 */ "term ::= CTIME_KW",
111314  /* 199 */ "expr ::= expr AND expr",
111315  /* 200 */ "expr ::= expr OR expr",
111316  /* 201 */ "expr ::= expr LT|GT|GE|LE expr",
111317  /* 202 */ "expr ::= expr EQ|NE expr",
111318  /* 203 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
111319  /* 204 */ "expr ::= expr PLUS|MINUS expr",
111320  /* 205 */ "expr ::= expr STAR|SLASH|REM expr",
111321  /* 206 */ "expr ::= expr CONCAT expr",
111322  /* 207 */ "likeop ::= LIKE_KW",
111323  /* 208 */ "likeop ::= NOT LIKE_KW",
111324  /* 209 */ "likeop ::= MATCH",
111325  /* 210 */ "likeop ::= NOT MATCH",
111326  /* 211 */ "expr ::= expr likeop expr",
111327  /* 212 */ "expr ::= expr likeop expr ESCAPE expr",
111328  /* 213 */ "expr ::= expr ISNULL|NOTNULL",
111329  /* 214 */ "expr ::= expr NOT NULL",
111330  /* 215 */ "expr ::= expr IS expr",
111331  /* 216 */ "expr ::= expr IS NOT expr",
111332  /* 217 */ "expr ::= NOT expr",
111333  /* 218 */ "expr ::= BITNOT expr",
111334  /* 219 */ "expr ::= MINUS expr",
111335  /* 220 */ "expr ::= PLUS expr",
111336  /* 221 */ "between_op ::= BETWEEN",
111337  /* 222 */ "between_op ::= NOT BETWEEN",
111338  /* 223 */ "expr ::= expr between_op expr AND expr",
111339  /* 224 */ "in_op ::= IN",
111340  /* 225 */ "in_op ::= NOT IN",
111341  /* 226 */ "expr ::= expr in_op LP exprlist RP",
111342  /* 227 */ "expr ::= LP select RP",
111343  /* 228 */ "expr ::= expr in_op LP select RP",
111344  /* 229 */ "expr ::= expr in_op nm dbnm",
111345  /* 230 */ "expr ::= EXISTS LP select RP",
111346  /* 231 */ "expr ::= CASE case_operand case_exprlist case_else END",
111347  /* 232 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
111348  /* 233 */ "case_exprlist ::= WHEN expr THEN expr",
111349  /* 234 */ "case_else ::= ELSE expr",
111350  /* 235 */ "case_else ::=",
111351  /* 236 */ "case_operand ::= expr",
111352  /* 237 */ "case_operand ::=",
111353  /* 238 */ "exprlist ::= nexprlist",
111354  /* 239 */ "exprlist ::=",
111355  /* 240 */ "nexprlist ::= nexprlist COMMA expr",
111356  /* 241 */ "nexprlist ::= expr",
111357  /* 242 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
111358  /* 243 */ "uniqueflag ::= UNIQUE",
111359  /* 244 */ "uniqueflag ::=",
111360  /* 245 */ "idxlist_opt ::=",
111361  /* 246 */ "idxlist_opt ::= LP idxlist RP",
111362  /* 247 */ "idxlist ::= idxlist COMMA nm collate sortorder",
111363  /* 248 */ "idxlist ::= nm collate sortorder",
111364  /* 249 */ "collate ::=",
111365  /* 250 */ "collate ::= COLLATE ids",
111366  /* 251 */ "cmd ::= DROP INDEX ifexists fullname",
111367  /* 252 */ "cmd ::= VACUUM",
111368  /* 253 */ "cmd ::= VACUUM nm",
111369  /* 254 */ "cmd ::= PRAGMA nm dbnm",
111370  /* 255 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
111371  /* 256 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
111372  /* 257 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
111373  /* 258 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
111374  /* 259 */ "nmnum ::= plus_num",
111375  /* 260 */ "nmnum ::= nm",
111376  /* 261 */ "nmnum ::= ON",
111377  /* 262 */ "nmnum ::= DELETE",
111378  /* 263 */ "nmnum ::= DEFAULT",
111379  /* 264 */ "plus_num ::= PLUS number",
111380  /* 265 */ "plus_num ::= number",
111381  /* 266 */ "minus_num ::= MINUS number",
111382  /* 267 */ "number ::= INTEGER|FLOAT",
111383  /* 268 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
111384  /* 269 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
111385  /* 270 */ "trigger_time ::= BEFORE",
111386  /* 271 */ "trigger_time ::= AFTER",
111387  /* 272 */ "trigger_time ::= INSTEAD OF",
111388  /* 273 */ "trigger_time ::=",
111389  /* 274 */ "trigger_event ::= DELETE|INSERT",
111390  /* 275 */ "trigger_event ::= UPDATE",
111391  /* 276 */ "trigger_event ::= UPDATE OF inscollist",
111392  /* 277 */ "foreach_clause ::=",
111393  /* 278 */ "foreach_clause ::= FOR EACH ROW",
111394  /* 279 */ "when_clause ::=",
111395  /* 280 */ "when_clause ::= WHEN expr",
111396  /* 281 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
111397  /* 282 */ "trigger_cmd_list ::= trigger_cmd SEMI",
111398  /* 283 */ "trnm ::= nm",
111399  /* 284 */ "trnm ::= nm DOT nm",
111400  /* 285 */ "tridxby ::=",
111401  /* 286 */ "tridxby ::= INDEXED BY nm",
111402  /* 287 */ "tridxby ::= NOT INDEXED",
111403  /* 288 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
111404  /* 289 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt valuelist",
111405  /* 290 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
111406  /* 291 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
111407  /* 292 */ "trigger_cmd ::= select",
111408  /* 293 */ "expr ::= RAISE LP IGNORE RP",
111409  /* 294 */ "expr ::= RAISE LP raisetype COMMA nm RP",
111410  /* 295 */ "raisetype ::= ROLLBACK",
111411  /* 296 */ "raisetype ::= ABORT",
111412  /* 297 */ "raisetype ::= FAIL",
111413  /* 298 */ "cmd ::= DROP TRIGGER ifexists fullname",
111414  /* 299 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
111415  /* 300 */ "cmd ::= DETACH database_kw_opt expr",
111416  /* 301 */ "key_opt ::=",
111417  /* 302 */ "key_opt ::= KEY expr",
111418  /* 303 */ "database_kw_opt ::= DATABASE",
111419  /* 304 */ "database_kw_opt ::=",
111420  /* 305 */ "cmd ::= REINDEX",
111421  /* 306 */ "cmd ::= REINDEX nm dbnm",
111422  /* 307 */ "cmd ::= ANALYZE",
111423  /* 308 */ "cmd ::= ANALYZE nm dbnm",
111424  /* 309 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
111425  /* 310 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
111426  /* 311 */ "add_column_fullname ::= fullname",
111427  /* 312 */ "kwcolumn_opt ::=",
111428  /* 313 */ "kwcolumn_opt ::= COLUMNKW",
111429  /* 314 */ "cmd ::= create_vtab",
111430  /* 315 */ "cmd ::= create_vtab LP vtabarglist RP",
111431  /* 316 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
111432  /* 317 */ "vtabarglist ::= vtabarg",
111433  /* 318 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
111434  /* 319 */ "vtabarg ::=",
111435  /* 320 */ "vtabarg ::= vtabarg vtabargtoken",
111436  /* 321 */ "vtabargtoken ::= ANY",
111437  /* 322 */ "vtabargtoken ::= lp anylist RP",
111438  /* 323 */ "lp ::= LP",
111439  /* 324 */ "anylist ::=",
111440  /* 325 */ "anylist ::= anylist LP anylist RP",
111441  /* 326 */ "anylist ::= anylist ANY",
111442 };
111443 #endif /* NDEBUG */
111444
111445
111446 #if YYSTACKDEPTH<=0
111447 /*
111448 ** Try to increase the size of the parser stack.
111449 */
111450 static void yyGrowStack(yyParser *p){
111451   int newSize;
111452   yyStackEntry *pNew;
111453
111454   newSize = p->yystksz*2 + 100;
111455   pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
111456   if( pNew ){
111457     p->yystack = pNew;
111458     p->yystksz = newSize;
111459 #ifndef NDEBUG
111460     if( yyTraceFILE ){
111461       fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
111462               yyTracePrompt, p->yystksz);
111463     }
111464 #endif
111465   }
111466 }
111467 #endif
111468
111469 /* 
111470 ** This function allocates a new parser.
111471 ** The only argument is a pointer to a function which works like
111472 ** malloc.
111473 **
111474 ** Inputs:
111475 ** A pointer to the function used to allocate memory.
111476 **
111477 ** Outputs:
111478 ** A pointer to a parser.  This pointer is used in subsequent calls
111479 ** to sqlite3Parser and sqlite3ParserFree.
111480 */
111481 SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
111482   yyParser *pParser;
111483   pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
111484   if( pParser ){
111485     pParser->yyidx = -1;
111486 #ifdef YYTRACKMAXSTACKDEPTH
111487     pParser->yyidxMax = 0;
111488 #endif
111489 #if YYSTACKDEPTH<=0
111490     pParser->yystack = NULL;
111491     pParser->yystksz = 0;
111492     yyGrowStack(pParser);
111493 #endif
111494   }
111495   return pParser;
111496 }
111497
111498 /* The following function deletes the value associated with a
111499 ** symbol.  The symbol can be either a terminal or nonterminal.
111500 ** "yymajor" is the symbol code, and "yypminor" is a pointer to
111501 ** the value.
111502 */
111503 static void yy_destructor(
111504   yyParser *yypParser,    /* The parser */
111505   YYCODETYPE yymajor,     /* Type code for object to destroy */
111506   YYMINORTYPE *yypminor   /* The object to be destroyed */
111507 ){
111508   sqlite3ParserARG_FETCH;
111509   switch( yymajor ){
111510     /* Here is inserted the actions which take place when a
111511     ** terminal or non-terminal is destroyed.  This can happen
111512     ** when the symbol is popped from the stack during a
111513     ** reduce or during error processing or when a parser is 
111514     ** being destroyed before it is finished parsing.
111515     **
111516     ** Note: during a reduce, the only symbols destroyed are those
111517     ** which appear on the RHS of the rule, but which are not used
111518     ** inside the C code.
111519     */
111520     case 160: /* select */
111521     case 194: /* oneselect */
111522 {
111523 sqlite3SelectDelete(pParse->db, (yypminor->yy159));
111524 }
111525       break;
111526     case 173: /* term */
111527     case 174: /* expr */
111528 {
111529 sqlite3ExprDelete(pParse->db, (yypminor->yy342).pExpr);
111530 }
111531       break;
111532     case 178: /* idxlist_opt */
111533     case 187: /* idxlist */
111534     case 197: /* selcollist */
111535     case 200: /* groupby_opt */
111536     case 202: /* orderby_opt */
111537     case 204: /* sclp */
111538     case 214: /* sortlist */
111539     case 215: /* nexprlist */
111540     case 216: /* setlist */
111541     case 220: /* exprlist */
111542     case 225: /* case_exprlist */
111543 {
111544 sqlite3ExprListDelete(pParse->db, (yypminor->yy442));
111545 }
111546       break;
111547     case 193: /* fullname */
111548     case 198: /* from */
111549     case 206: /* seltablist */
111550     case 207: /* stl_prefix */
111551 {
111552 sqlite3SrcListDelete(pParse->db, (yypminor->yy347));
111553 }
111554       break;
111555     case 199: /* where_opt */
111556     case 201: /* having_opt */
111557     case 210: /* on_opt */
111558     case 224: /* case_operand */
111559     case 226: /* case_else */
111560     case 236: /* when_clause */
111561     case 241: /* key_opt */
111562 {
111563 sqlite3ExprDelete(pParse->db, (yypminor->yy122));
111564 }
111565       break;
111566     case 211: /* using_opt */
111567     case 213: /* inscollist */
111568     case 218: /* inscollist_opt */
111569 {
111570 sqlite3IdListDelete(pParse->db, (yypminor->yy180));
111571 }
111572       break;
111573     case 219: /* valuelist */
111574 {
111575
111576   sqlite3ExprListDelete(pParse->db, (yypminor->yy487).pList);
111577   sqlite3SelectDelete(pParse->db, (yypminor->yy487).pSelect);
111578
111579 }
111580       break;
111581     case 232: /* trigger_cmd_list */
111582     case 237: /* trigger_cmd */
111583 {
111584 sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy327));
111585 }
111586       break;
111587     case 234: /* trigger_event */
111588 {
111589 sqlite3IdListDelete(pParse->db, (yypminor->yy410).b);
111590 }
111591       break;
111592     default:  break;   /* If no destructor action specified: do nothing */
111593   }
111594 }
111595
111596 /*
111597 ** Pop the parser's stack once.
111598 **
111599 ** If there is a destructor routine associated with the token which
111600 ** is popped from the stack, then call it.
111601 **
111602 ** Return the major token number for the symbol popped.
111603 */
111604 static int yy_pop_parser_stack(yyParser *pParser){
111605   YYCODETYPE yymajor;
111606   yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
111607
111608   /* There is no mechanism by which the parser stack can be popped below
111609   ** empty in SQLite.  */
111610   if( NEVER(pParser->yyidx<0) ) return 0;
111611 #ifndef NDEBUG
111612   if( yyTraceFILE && pParser->yyidx>=0 ){
111613     fprintf(yyTraceFILE,"%sPopping %s\n",
111614       yyTracePrompt,
111615       yyTokenName[yytos->major]);
111616   }
111617 #endif
111618   yymajor = yytos->major;
111619   yy_destructor(pParser, yymajor, &yytos->minor);
111620   pParser->yyidx--;
111621   return yymajor;
111622 }
111623
111624 /* 
111625 ** Deallocate and destroy a parser.  Destructors are all called for
111626 ** all stack elements before shutting the parser down.
111627 **
111628 ** Inputs:
111629 ** <ul>
111630 ** <li>  A pointer to the parser.  This should be a pointer
111631 **       obtained from sqlite3ParserAlloc.
111632 ** <li>  A pointer to a function used to reclaim memory obtained
111633 **       from malloc.
111634 ** </ul>
111635 */
111636 SQLITE_PRIVATE void sqlite3ParserFree(
111637   void *p,                    /* The parser to be deleted */
111638   void (*freeProc)(void*)     /* Function used to reclaim memory */
111639 ){
111640   yyParser *pParser = (yyParser*)p;
111641   /* In SQLite, we never try to destroy a parser that was not successfully
111642   ** created in the first place. */
111643   if( NEVER(pParser==0) ) return;
111644   while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
111645 #if YYSTACKDEPTH<=0
111646   free(pParser->yystack);
111647 #endif
111648   (*freeProc)((void*)pParser);
111649 }
111650
111651 /*
111652 ** Return the peak depth of the stack for a parser.
111653 */
111654 #ifdef YYTRACKMAXSTACKDEPTH
111655 SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
111656   yyParser *pParser = (yyParser*)p;
111657   return pParser->yyidxMax;
111658 }
111659 #endif
111660
111661 /*
111662 ** Find the appropriate action for a parser given the terminal
111663 ** look-ahead token iLookAhead.
111664 **
111665 ** If the look-ahead token is YYNOCODE, then check to see if the action is
111666 ** independent of the look-ahead.  If it is, return the action, otherwise
111667 ** return YY_NO_ACTION.
111668 */
111669 static int yy_find_shift_action(
111670   yyParser *pParser,        /* The parser */
111671   YYCODETYPE iLookAhead     /* The look-ahead token */
111672 ){
111673   int i;
111674   int stateno = pParser->yystack[pParser->yyidx].stateno;
111675  
111676   if( stateno>YY_SHIFT_COUNT
111677    || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
111678     return yy_default[stateno];
111679   }
111680   assert( iLookAhead!=YYNOCODE );
111681   i += iLookAhead;
111682   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
111683     if( iLookAhead>0 ){
111684 #ifdef YYFALLBACK
111685       YYCODETYPE iFallback;            /* Fallback token */
111686       if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
111687              && (iFallback = yyFallback[iLookAhead])!=0 ){
111688 #ifndef NDEBUG
111689         if( yyTraceFILE ){
111690           fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
111691              yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
111692         }
111693 #endif
111694         return yy_find_shift_action(pParser, iFallback);
111695       }
111696 #endif
111697 #ifdef YYWILDCARD
111698       {
111699         int j = i - iLookAhead + YYWILDCARD;
111700         if( 
111701 #if YY_SHIFT_MIN+YYWILDCARD<0
111702           j>=0 &&
111703 #endif
111704 #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
111705           j<YY_ACTTAB_COUNT &&
111706 #endif
111707           yy_lookahead[j]==YYWILDCARD
111708         ){
111709 #ifndef NDEBUG
111710           if( yyTraceFILE ){
111711             fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
111712                yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
111713           }
111714 #endif /* NDEBUG */
111715           return yy_action[j];
111716         }
111717       }
111718 #endif /* YYWILDCARD */
111719     }
111720     return yy_default[stateno];
111721   }else{
111722     return yy_action[i];
111723   }
111724 }
111725
111726 /*
111727 ** Find the appropriate action for a parser given the non-terminal
111728 ** look-ahead token iLookAhead.
111729 **
111730 ** If the look-ahead token is YYNOCODE, then check to see if the action is
111731 ** independent of the look-ahead.  If it is, return the action, otherwise
111732 ** return YY_NO_ACTION.
111733 */
111734 static int yy_find_reduce_action(
111735   int stateno,              /* Current state number */
111736   YYCODETYPE iLookAhead     /* The look-ahead token */
111737 ){
111738   int i;
111739 #ifdef YYERRORSYMBOL
111740   if( stateno>YY_REDUCE_COUNT ){
111741     return yy_default[stateno];
111742   }
111743 #else
111744   assert( stateno<=YY_REDUCE_COUNT );
111745 #endif
111746   i = yy_reduce_ofst[stateno];
111747   assert( i!=YY_REDUCE_USE_DFLT );
111748   assert( iLookAhead!=YYNOCODE );
111749   i += iLookAhead;
111750 #ifdef YYERRORSYMBOL
111751   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
111752     return yy_default[stateno];
111753   }
111754 #else
111755   assert( i>=0 && i<YY_ACTTAB_COUNT );
111756   assert( yy_lookahead[i]==iLookAhead );
111757 #endif
111758   return yy_action[i];
111759 }
111760
111761 /*
111762 ** The following routine is called if the stack overflows.
111763 */
111764 static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
111765    sqlite3ParserARG_FETCH;
111766    yypParser->yyidx--;
111767 #ifndef NDEBUG
111768    if( yyTraceFILE ){
111769      fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
111770    }
111771 #endif
111772    while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
111773    /* Here code is inserted which will execute if the parser
111774    ** stack every overflows */
111775
111776   UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
111777   sqlite3ErrorMsg(pParse, "parser stack overflow");
111778    sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
111779 }
111780
111781 /*
111782 ** Perform a shift action.
111783 */
111784 static void yy_shift(
111785   yyParser *yypParser,          /* The parser to be shifted */
111786   int yyNewState,               /* The new state to shift in */
111787   int yyMajor,                  /* The major token to shift in */
111788   YYMINORTYPE *yypMinor         /* Pointer to the minor token to shift in */
111789 ){
111790   yyStackEntry *yytos;
111791   yypParser->yyidx++;
111792 #ifdef YYTRACKMAXSTACKDEPTH
111793   if( yypParser->yyidx>yypParser->yyidxMax ){
111794     yypParser->yyidxMax = yypParser->yyidx;
111795   }
111796 #endif
111797 #if YYSTACKDEPTH>0 
111798   if( yypParser->yyidx>=YYSTACKDEPTH ){
111799     yyStackOverflow(yypParser, yypMinor);
111800     return;
111801   }
111802 #else
111803   if( yypParser->yyidx>=yypParser->yystksz ){
111804     yyGrowStack(yypParser);
111805     if( yypParser->yyidx>=yypParser->yystksz ){
111806       yyStackOverflow(yypParser, yypMinor);
111807       return;
111808     }
111809   }
111810 #endif
111811   yytos = &yypParser->yystack[yypParser->yyidx];
111812   yytos->stateno = (YYACTIONTYPE)yyNewState;
111813   yytos->major = (YYCODETYPE)yyMajor;
111814   yytos->minor = *yypMinor;
111815 #ifndef NDEBUG
111816   if( yyTraceFILE && yypParser->yyidx>0 ){
111817     int i;
111818     fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
111819     fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
111820     for(i=1; i<=yypParser->yyidx; i++)
111821       fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
111822     fprintf(yyTraceFILE,"\n");
111823   }
111824 #endif
111825 }
111826
111827 /* The following table contains information about every rule that
111828 ** is used during the reduce.
111829 */
111830 static const struct {
111831   YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
111832   unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
111833 } yyRuleInfo[] = {
111834   { 142, 1 },
111835   { 143, 2 },
111836   { 143, 1 },
111837   { 144, 1 },
111838   { 144, 3 },
111839   { 145, 0 },
111840   { 145, 1 },
111841   { 145, 3 },
111842   { 146, 1 },
111843   { 147, 3 },
111844   { 149, 0 },
111845   { 149, 1 },
111846   { 149, 2 },
111847   { 148, 0 },
111848   { 148, 1 },
111849   { 148, 1 },
111850   { 148, 1 },
111851   { 147, 2 },
111852   { 147, 2 },
111853   { 147, 2 },
111854   { 151, 1 },
111855   { 151, 0 },
111856   { 147, 2 },
111857   { 147, 3 },
111858   { 147, 5 },
111859   { 147, 2 },
111860   { 152, 6 },
111861   { 154, 1 },
111862   { 156, 0 },
111863   { 156, 3 },
111864   { 155, 1 },
111865   { 155, 0 },
111866   { 153, 4 },
111867   { 153, 2 },
111868   { 158, 3 },
111869   { 158, 1 },
111870   { 161, 3 },
111871   { 162, 1 },
111872   { 165, 1 },
111873   { 165, 1 },
111874   { 166, 1 },
111875   { 150, 1 },
111876   { 150, 1 },
111877   { 150, 1 },
111878   { 163, 0 },
111879   { 163, 1 },
111880   { 167, 1 },
111881   { 167, 4 },
111882   { 167, 6 },
111883   { 168, 1 },
111884   { 168, 2 },
111885   { 169, 1 },
111886   { 169, 1 },
111887   { 164, 2 },
111888   { 164, 0 },
111889   { 172, 2 },
111890   { 172, 2 },
111891   { 172, 4 },
111892   { 172, 3 },
111893   { 172, 3 },
111894   { 172, 2 },
111895   { 172, 2 },
111896   { 172, 3 },
111897   { 172, 5 },
111898   { 172, 2 },
111899   { 172, 4 },
111900   { 172, 4 },
111901   { 172, 1 },
111902   { 172, 2 },
111903   { 177, 0 },
111904   { 177, 1 },
111905   { 179, 0 },
111906   { 179, 2 },
111907   { 181, 2 },
111908   { 181, 3 },
111909   { 181, 3 },
111910   { 181, 3 },
111911   { 182, 2 },
111912   { 182, 2 },
111913   { 182, 1 },
111914   { 182, 1 },
111915   { 182, 2 },
111916   { 180, 3 },
111917   { 180, 2 },
111918   { 183, 0 },
111919   { 183, 2 },
111920   { 183, 2 },
111921   { 159, 0 },
111922   { 159, 2 },
111923   { 184, 3 },
111924   { 184, 1 },
111925   { 185, 1 },
111926   { 185, 0 },
111927   { 186, 2 },
111928   { 186, 7 },
111929   { 186, 5 },
111930   { 186, 5 },
111931   { 186, 10 },
111932   { 188, 0 },
111933   { 188, 1 },
111934   { 175, 0 },
111935   { 175, 3 },
111936   { 189, 0 },
111937   { 189, 2 },
111938   { 190, 1 },
111939   { 190, 1 },
111940   { 190, 1 },
111941   { 147, 4 },
111942   { 192, 2 },
111943   { 192, 0 },
111944   { 147, 8 },
111945   { 147, 4 },
111946   { 147, 1 },
111947   { 160, 1 },
111948   { 160, 3 },
111949   { 195, 1 },
111950   { 195, 2 },
111951   { 195, 1 },
111952   { 194, 9 },
111953   { 196, 1 },
111954   { 196, 1 },
111955   { 196, 0 },
111956   { 204, 2 },
111957   { 204, 0 },
111958   { 197, 3 },
111959   { 197, 2 },
111960   { 197, 4 },
111961   { 205, 2 },
111962   { 205, 1 },
111963   { 205, 0 },
111964   { 198, 0 },
111965   { 198, 2 },
111966   { 207, 2 },
111967   { 207, 0 },
111968   { 206, 7 },
111969   { 206, 7 },
111970   { 206, 7 },
111971   { 157, 0 },
111972   { 157, 2 },
111973   { 193, 2 },
111974   { 208, 1 },
111975   { 208, 2 },
111976   { 208, 3 },
111977   { 208, 4 },
111978   { 210, 2 },
111979   { 210, 0 },
111980   { 209, 0 },
111981   { 209, 3 },
111982   { 209, 2 },
111983   { 211, 4 },
111984   { 211, 0 },
111985   { 202, 0 },
111986   { 202, 3 },
111987   { 214, 4 },
111988   { 214, 2 },
111989   { 176, 1 },
111990   { 176, 1 },
111991   { 176, 0 },
111992   { 200, 0 },
111993   { 200, 3 },
111994   { 201, 0 },
111995   { 201, 2 },
111996   { 203, 0 },
111997   { 203, 2 },
111998   { 203, 4 },
111999   { 203, 4 },
112000   { 147, 5 },
112001   { 199, 0 },
112002   { 199, 2 },
112003   { 147, 7 },
112004   { 216, 5 },
112005   { 216, 3 },
112006   { 147, 5 },
112007   { 147, 5 },
112008   { 147, 6 },
112009   { 217, 2 },
112010   { 217, 1 },
112011   { 219, 4 },
112012   { 219, 5 },
112013   { 218, 0 },
112014   { 218, 3 },
112015   { 213, 3 },
112016   { 213, 1 },
112017   { 174, 1 },
112018   { 174, 3 },
112019   { 173, 1 },
112020   { 174, 1 },
112021   { 174, 1 },
112022   { 174, 3 },
112023   { 174, 5 },
112024   { 173, 1 },
112025   { 173, 1 },
112026   { 174, 1 },
112027   { 174, 1 },
112028   { 174, 3 },
112029   { 174, 6 },
112030   { 174, 5 },
112031   { 174, 4 },
112032   { 173, 1 },
112033   { 174, 3 },
112034   { 174, 3 },
112035   { 174, 3 },
112036   { 174, 3 },
112037   { 174, 3 },
112038   { 174, 3 },
112039   { 174, 3 },
112040   { 174, 3 },
112041   { 221, 1 },
112042   { 221, 2 },
112043   { 221, 1 },
112044   { 221, 2 },
112045   { 174, 3 },
112046   { 174, 5 },
112047   { 174, 2 },
112048   { 174, 3 },
112049   { 174, 3 },
112050   { 174, 4 },
112051   { 174, 2 },
112052   { 174, 2 },
112053   { 174, 2 },
112054   { 174, 2 },
112055   { 222, 1 },
112056   { 222, 2 },
112057   { 174, 5 },
112058   { 223, 1 },
112059   { 223, 2 },
112060   { 174, 5 },
112061   { 174, 3 },
112062   { 174, 5 },
112063   { 174, 4 },
112064   { 174, 4 },
112065   { 174, 5 },
112066   { 225, 5 },
112067   { 225, 4 },
112068   { 226, 2 },
112069   { 226, 0 },
112070   { 224, 1 },
112071   { 224, 0 },
112072   { 220, 1 },
112073   { 220, 0 },
112074   { 215, 3 },
112075   { 215, 1 },
112076   { 147, 11 },
112077   { 227, 1 },
112078   { 227, 0 },
112079   { 178, 0 },
112080   { 178, 3 },
112081   { 187, 5 },
112082   { 187, 3 },
112083   { 228, 0 },
112084   { 228, 2 },
112085   { 147, 4 },
112086   { 147, 1 },
112087   { 147, 2 },
112088   { 147, 3 },
112089   { 147, 5 },
112090   { 147, 6 },
112091   { 147, 5 },
112092   { 147, 6 },
112093   { 229, 1 },
112094   { 229, 1 },
112095   { 229, 1 },
112096   { 229, 1 },
112097   { 229, 1 },
112098   { 170, 2 },
112099   { 170, 1 },
112100   { 171, 2 },
112101   { 230, 1 },
112102   { 147, 5 },
112103   { 231, 11 },
112104   { 233, 1 },
112105   { 233, 1 },
112106   { 233, 2 },
112107   { 233, 0 },
112108   { 234, 1 },
112109   { 234, 1 },
112110   { 234, 3 },
112111   { 235, 0 },
112112   { 235, 3 },
112113   { 236, 0 },
112114   { 236, 2 },
112115   { 232, 3 },
112116   { 232, 2 },
112117   { 238, 1 },
112118   { 238, 3 },
112119   { 239, 0 },
112120   { 239, 3 },
112121   { 239, 2 },
112122   { 237, 7 },
112123   { 237, 5 },
112124   { 237, 5 },
112125   { 237, 5 },
112126   { 237, 1 },
112127   { 174, 4 },
112128   { 174, 6 },
112129   { 191, 1 },
112130   { 191, 1 },
112131   { 191, 1 },
112132   { 147, 4 },
112133   { 147, 6 },
112134   { 147, 3 },
112135   { 241, 0 },
112136   { 241, 2 },
112137   { 240, 1 },
112138   { 240, 0 },
112139   { 147, 1 },
112140   { 147, 3 },
112141   { 147, 1 },
112142   { 147, 3 },
112143   { 147, 6 },
112144   { 147, 6 },
112145   { 242, 1 },
112146   { 243, 0 },
112147   { 243, 1 },
112148   { 147, 1 },
112149   { 147, 4 },
112150   { 244, 8 },
112151   { 245, 1 },
112152   { 245, 3 },
112153   { 246, 0 },
112154   { 246, 2 },
112155   { 247, 1 },
112156   { 247, 3 },
112157   { 248, 1 },
112158   { 249, 0 },
112159   { 249, 4 },
112160   { 249, 2 },
112161 };
112162
112163 static void yy_accept(yyParser*);  /* Forward Declaration */
112164
112165 /*
112166 ** Perform a reduce action and the shift that must immediately
112167 ** follow the reduce.
112168 */
112169 static void yy_reduce(
112170   yyParser *yypParser,         /* The parser */
112171   int yyruleno                 /* Number of the rule by which to reduce */
112172 ){
112173   int yygoto;                     /* The next state */
112174   int yyact;                      /* The next action */
112175   YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
112176   yyStackEntry *yymsp;            /* The top of the parser's stack */
112177   int yysize;                     /* Amount to pop the stack */
112178   sqlite3ParserARG_FETCH;
112179   yymsp = &yypParser->yystack[yypParser->yyidx];
112180 #ifndef NDEBUG
112181   if( yyTraceFILE && yyruleno>=0 
112182         && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
112183     fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
112184       yyRuleName[yyruleno]);
112185   }
112186 #endif /* NDEBUG */
112187
112188   /* Silence complaints from purify about yygotominor being uninitialized
112189   ** in some cases when it is copied into the stack after the following
112190   ** switch.  yygotominor is uninitialized when a rule reduces that does
112191   ** not set the value of its left-hand side nonterminal.  Leaving the
112192   ** value of the nonterminal uninitialized is utterly harmless as long
112193   ** as the value is never used.  So really the only thing this code
112194   ** accomplishes is to quieten purify.  
112195   **
112196   ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
112197   ** without this code, their parser segfaults.  I'm not sure what there
112198   ** parser is doing to make this happen.  This is the second bug report
112199   ** from wireshark this week.  Clearly they are stressing Lemon in ways
112200   ** that it has not been previously stressed...  (SQLite ticket #2172)
112201   */
112202   /*memset(&yygotominor, 0, sizeof(yygotominor));*/
112203   yygotominor = yyzerominor;
112204
112205
112206   switch( yyruleno ){
112207   /* Beginning here are the reduction cases.  A typical example
112208   ** follows:
112209   **   case 0:
112210   **  #line <lineno> <grammarfile>
112211   **     { ... }           // User supplied code
112212   **  #line <lineno> <thisfile>
112213   **     break;
112214   */
112215       case 5: /* explain ::= */
112216 { sqlite3BeginParse(pParse, 0); }
112217         break;
112218       case 6: /* explain ::= EXPLAIN */
112219 { sqlite3BeginParse(pParse, 1); }
112220         break;
112221       case 7: /* explain ::= EXPLAIN QUERY PLAN */
112222 { sqlite3BeginParse(pParse, 2); }
112223         break;
112224       case 8: /* cmdx ::= cmd */
112225 { sqlite3FinishCoding(pParse); }
112226         break;
112227       case 9: /* cmd ::= BEGIN transtype trans_opt */
112228 {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy392);}
112229         break;
112230       case 13: /* transtype ::= */
112231 {yygotominor.yy392 = TK_DEFERRED;}
112232         break;
112233       case 14: /* transtype ::= DEFERRED */
112234       case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
112235       case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
112236       case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
112237       case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
112238 {yygotominor.yy392 = yymsp[0].major;}
112239         break;
112240       case 17: /* cmd ::= COMMIT trans_opt */
112241       case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
112242 {sqlite3CommitTransaction(pParse);}
112243         break;
112244       case 19: /* cmd ::= ROLLBACK trans_opt */
112245 {sqlite3RollbackTransaction(pParse);}
112246         break;
112247       case 22: /* cmd ::= SAVEPOINT nm */
112248 {
112249   sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
112250 }
112251         break;
112252       case 23: /* cmd ::= RELEASE savepoint_opt nm */
112253 {
112254   sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
112255 }
112256         break;
112257       case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
112258 {
112259   sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
112260 }
112261         break;
112262       case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
112263 {
112264    sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy392,0,0,yymsp[-2].minor.yy392);
112265 }
112266         break;
112267       case 27: /* createkw ::= CREATE */
112268 {
112269   pParse->db->lookaside.bEnabled = 0;
112270   yygotominor.yy0 = yymsp[0].minor.yy0;
112271 }
112272         break;
112273       case 28: /* ifnotexists ::= */
112274       case 31: /* temp ::= */ yytestcase(yyruleno==31);
112275       case 69: /* autoinc ::= */ yytestcase(yyruleno==69);
112276       case 82: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==82);
112277       case 84: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==84);
112278       case 86: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==86);
112279       case 98: /* defer_subclause_opt ::= */ yytestcase(yyruleno==98);
112280       case 109: /* ifexists ::= */ yytestcase(yyruleno==109);
112281       case 221: /* between_op ::= BETWEEN */ yytestcase(yyruleno==221);
112282       case 224: /* in_op ::= IN */ yytestcase(yyruleno==224);
112283 {yygotominor.yy392 = 0;}
112284         break;
112285       case 29: /* ifnotexists ::= IF NOT EXISTS */
112286       case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
112287       case 70: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==70);
112288       case 85: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==85);
112289       case 108: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==108);
112290       case 222: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==222);
112291       case 225: /* in_op ::= NOT IN */ yytestcase(yyruleno==225);
112292 {yygotominor.yy392 = 1;}
112293         break;
112294       case 32: /* create_table_args ::= LP columnlist conslist_opt RP */
112295 {
112296   sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
112297 }
112298         break;
112299       case 33: /* create_table_args ::= AS select */
112300 {
112301   sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy159);
112302   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy159);
112303 }
112304         break;
112305       case 36: /* column ::= columnid type carglist */
112306 {
112307   yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
112308   yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
112309 }
112310         break;
112311       case 37: /* columnid ::= nm */
112312 {
112313   sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
112314   yygotominor.yy0 = yymsp[0].minor.yy0;
112315   pParse->constraintName.n = 0;
112316 }
112317         break;
112318       case 38: /* id ::= ID */
112319       case 39: /* id ::= INDEXED */ yytestcase(yyruleno==39);
112320       case 40: /* ids ::= ID|STRING */ yytestcase(yyruleno==40);
112321       case 41: /* nm ::= id */ yytestcase(yyruleno==41);
112322       case 42: /* nm ::= STRING */ yytestcase(yyruleno==42);
112323       case 43: /* nm ::= JOIN_KW */ yytestcase(yyruleno==43);
112324       case 46: /* typetoken ::= typename */ yytestcase(yyruleno==46);
112325       case 49: /* typename ::= ids */ yytestcase(yyruleno==49);
112326       case 127: /* as ::= AS nm */ yytestcase(yyruleno==127);
112327       case 128: /* as ::= ids */ yytestcase(yyruleno==128);
112328       case 138: /* dbnm ::= DOT nm */ yytestcase(yyruleno==138);
112329       case 147: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==147);
112330       case 250: /* collate ::= COLLATE ids */ yytestcase(yyruleno==250);
112331       case 259: /* nmnum ::= plus_num */ yytestcase(yyruleno==259);
112332       case 260: /* nmnum ::= nm */ yytestcase(yyruleno==260);
112333       case 261: /* nmnum ::= ON */ yytestcase(yyruleno==261);
112334       case 262: /* nmnum ::= DELETE */ yytestcase(yyruleno==262);
112335       case 263: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==263);
112336       case 264: /* plus_num ::= PLUS number */ yytestcase(yyruleno==264);
112337       case 265: /* plus_num ::= number */ yytestcase(yyruleno==265);
112338       case 266: /* minus_num ::= MINUS number */ yytestcase(yyruleno==266);
112339       case 267: /* number ::= INTEGER|FLOAT */ yytestcase(yyruleno==267);
112340       case 283: /* trnm ::= nm */ yytestcase(yyruleno==283);
112341 {yygotominor.yy0 = yymsp[0].minor.yy0;}
112342         break;
112343       case 45: /* type ::= typetoken */
112344 {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
112345         break;
112346       case 47: /* typetoken ::= typename LP signed RP */
112347 {
112348   yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
112349   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
112350 }
112351         break;
112352       case 48: /* typetoken ::= typename LP signed COMMA signed RP */
112353 {
112354   yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
112355   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
112356 }
112357         break;
112358       case 50: /* typename ::= typename ids */
112359 {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);}
112360         break;
112361       case 55: /* ccons ::= CONSTRAINT nm */
112362       case 93: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==93);
112363 {pParse->constraintName = yymsp[0].minor.yy0;}
112364         break;
112365       case 56: /* ccons ::= DEFAULT term */
112366       case 58: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==58);
112367 {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy342);}
112368         break;
112369       case 57: /* ccons ::= DEFAULT LP expr RP */
112370 {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy342);}
112371         break;
112372       case 59: /* ccons ::= DEFAULT MINUS term */
112373 {
112374   ExprSpan v;
112375   v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy342.pExpr, 0, 0);
112376   v.zStart = yymsp[-1].minor.yy0.z;
112377   v.zEnd = yymsp[0].minor.yy342.zEnd;
112378   sqlite3AddDefaultValue(pParse,&v);
112379 }
112380         break;
112381       case 60: /* ccons ::= DEFAULT id */
112382 {
112383   ExprSpan v;
112384   spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
112385   sqlite3AddDefaultValue(pParse,&v);
112386 }
112387         break;
112388       case 62: /* ccons ::= NOT NULL onconf */
112389 {sqlite3AddNotNull(pParse, yymsp[0].minor.yy392);}
112390         break;
112391       case 63: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
112392 {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy392,yymsp[0].minor.yy392,yymsp[-2].minor.yy392);}
112393         break;
112394       case 64: /* ccons ::= UNIQUE onconf */
112395 {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy392,0,0,0,0);}
112396         break;
112397       case 65: /* ccons ::= CHECK LP expr RP */
112398 {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy342.pExpr);}
112399         break;
112400       case 66: /* ccons ::= REFERENCES nm idxlist_opt refargs */
112401 {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy442,yymsp[0].minor.yy392);}
112402         break;
112403       case 67: /* ccons ::= defer_subclause */
112404 {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy392);}
112405         break;
112406       case 68: /* ccons ::= COLLATE ids */
112407 {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
112408         break;
112409       case 71: /* refargs ::= */
112410 { yygotominor.yy392 = OE_None*0x0101; /* EV: R-19803-45884 */}
112411         break;
112412       case 72: /* refargs ::= refargs refarg */
112413 { yygotominor.yy392 = (yymsp[-1].minor.yy392 & ~yymsp[0].minor.yy207.mask) | yymsp[0].minor.yy207.value; }
112414         break;
112415       case 73: /* refarg ::= MATCH nm */
112416       case 74: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==74);
112417 { yygotominor.yy207.value = 0;     yygotominor.yy207.mask = 0x000000; }
112418         break;
112419       case 75: /* refarg ::= ON DELETE refact */
112420 { yygotominor.yy207.value = yymsp[0].minor.yy392;     yygotominor.yy207.mask = 0x0000ff; }
112421         break;
112422       case 76: /* refarg ::= ON UPDATE refact */
112423 { yygotominor.yy207.value = yymsp[0].minor.yy392<<8;  yygotominor.yy207.mask = 0x00ff00; }
112424         break;
112425       case 77: /* refact ::= SET NULL */
112426 { yygotominor.yy392 = OE_SetNull;  /* EV: R-33326-45252 */}
112427         break;
112428       case 78: /* refact ::= SET DEFAULT */
112429 { yygotominor.yy392 = OE_SetDflt;  /* EV: R-33326-45252 */}
112430         break;
112431       case 79: /* refact ::= CASCADE */
112432 { yygotominor.yy392 = OE_Cascade;  /* EV: R-33326-45252 */}
112433         break;
112434       case 80: /* refact ::= RESTRICT */
112435 { yygotominor.yy392 = OE_Restrict; /* EV: R-33326-45252 */}
112436         break;
112437       case 81: /* refact ::= NO ACTION */
112438 { yygotominor.yy392 = OE_None;     /* EV: R-33326-45252 */}
112439         break;
112440       case 83: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
112441       case 99: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==99);
112442       case 101: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==101);
112443       case 104: /* resolvetype ::= raisetype */ yytestcase(yyruleno==104);
112444 {yygotominor.yy392 = yymsp[0].minor.yy392;}
112445         break;
112446       case 87: /* conslist_opt ::= */
112447 {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
112448         break;
112449       case 88: /* conslist_opt ::= COMMA conslist */
112450 {yygotominor.yy0 = yymsp[-1].minor.yy0;}
112451         break;
112452       case 91: /* tconscomma ::= COMMA */
112453 {pParse->constraintName.n = 0;}
112454         break;
112455       case 94: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
112456 {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy442,yymsp[0].minor.yy392,yymsp[-2].minor.yy392,0);}
112457         break;
112458       case 95: /* tcons ::= UNIQUE LP idxlist RP onconf */
112459 {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy442,yymsp[0].minor.yy392,0,0,0,0);}
112460         break;
112461       case 96: /* tcons ::= CHECK LP expr RP onconf */
112462 {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy342.pExpr);}
112463         break;
112464       case 97: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
112465 {
112466     sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy442, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy442, yymsp[-1].minor.yy392);
112467     sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy392);
112468 }
112469         break;
112470       case 100: /* onconf ::= */
112471 {yygotominor.yy392 = OE_Default;}
112472         break;
112473       case 102: /* orconf ::= */
112474 {yygotominor.yy258 = OE_Default;}
112475         break;
112476       case 103: /* orconf ::= OR resolvetype */
112477 {yygotominor.yy258 = (u8)yymsp[0].minor.yy392;}
112478         break;
112479       case 105: /* resolvetype ::= IGNORE */
112480 {yygotominor.yy392 = OE_Ignore;}
112481         break;
112482       case 106: /* resolvetype ::= REPLACE */
112483 {yygotominor.yy392 = OE_Replace;}
112484         break;
112485       case 107: /* cmd ::= DROP TABLE ifexists fullname */
112486 {
112487   sqlite3DropTable(pParse, yymsp[0].minor.yy347, 0, yymsp[-1].minor.yy392);
112488 }
112489         break;
112490       case 110: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
112491 {
112492   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);
112493 }
112494         break;
112495       case 111: /* cmd ::= DROP VIEW ifexists fullname */
112496 {
112497   sqlite3DropTable(pParse, yymsp[0].minor.yy347, 1, yymsp[-1].minor.yy392);
112498 }
112499         break;
112500       case 112: /* cmd ::= select */
112501 {
112502   SelectDest dest = {SRT_Output, 0, 0, 0, 0};
112503   sqlite3Select(pParse, yymsp[0].minor.yy159, &dest);
112504   sqlite3ExplainBegin(pParse->pVdbe);
112505   sqlite3ExplainSelect(pParse->pVdbe, yymsp[0].minor.yy159);
112506   sqlite3ExplainFinish(pParse->pVdbe);
112507   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy159);
112508 }
112509         break;
112510       case 113: /* select ::= oneselect */
112511 {yygotominor.yy159 = yymsp[0].minor.yy159;}
112512         break;
112513       case 114: /* select ::= select multiselect_op oneselect */
112514 {
112515   if( yymsp[0].minor.yy159 ){
112516     yymsp[0].minor.yy159->op = (u8)yymsp[-1].minor.yy392;
112517     yymsp[0].minor.yy159->pPrior = yymsp[-2].minor.yy159;
112518   }else{
112519     sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy159);
112520   }
112521   yygotominor.yy159 = yymsp[0].minor.yy159;
112522 }
112523         break;
112524       case 116: /* multiselect_op ::= UNION ALL */
112525 {yygotominor.yy392 = TK_ALL;}
112526         break;
112527       case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
112528 {
112529   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);
112530 }
112531         break;
112532       case 119: /* distinct ::= DISTINCT */
112533 {yygotominor.yy305 = SF_Distinct;}
112534         break;
112535       case 120: /* distinct ::= ALL */
112536       case 121: /* distinct ::= */ yytestcase(yyruleno==121);
112537 {yygotominor.yy305 = 0;}
112538         break;
112539       case 122: /* sclp ::= selcollist COMMA */
112540       case 246: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==246);
112541 {yygotominor.yy442 = yymsp[-1].minor.yy442;}
112542         break;
112543       case 123: /* sclp ::= */
112544       case 151: /* orderby_opt ::= */ yytestcase(yyruleno==151);
112545       case 158: /* groupby_opt ::= */ yytestcase(yyruleno==158);
112546       case 239: /* exprlist ::= */ yytestcase(yyruleno==239);
112547       case 245: /* idxlist_opt ::= */ yytestcase(yyruleno==245);
112548 {yygotominor.yy442 = 0;}
112549         break;
112550       case 124: /* selcollist ::= sclp expr as */
112551 {
112552    yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy442, yymsp[-1].minor.yy342.pExpr);
112553    if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[0].minor.yy0, 1);
112554    sqlite3ExprListSetSpan(pParse,yygotominor.yy442,&yymsp[-1].minor.yy342);
112555 }
112556         break;
112557       case 125: /* selcollist ::= sclp STAR */
112558 {
112559   Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
112560   yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy442, p);
112561 }
112562         break;
112563       case 126: /* selcollist ::= sclp nm DOT STAR */
112564 {
112565   Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
112566   Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
112567   Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
112568   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442, pDot);
112569 }
112570         break;
112571       case 129: /* as ::= */
112572 {yygotominor.yy0.n = 0;}
112573         break;
112574       case 130: /* from ::= */
112575 {yygotominor.yy347 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy347));}
112576         break;
112577       case 131: /* from ::= FROM seltablist */
112578 {
112579   yygotominor.yy347 = yymsp[0].minor.yy347;
112580   sqlite3SrcListShiftJoinType(yygotominor.yy347);
112581 }
112582         break;
112583       case 132: /* stl_prefix ::= seltablist joinop */
112584 {
112585    yygotominor.yy347 = yymsp[-1].minor.yy347;
112586    if( ALWAYS(yygotominor.yy347 && yygotominor.yy347->nSrc>0) ) yygotominor.yy347->a[yygotominor.yy347->nSrc-1].jointype = (u8)yymsp[0].minor.yy392;
112587 }
112588         break;
112589       case 133: /* stl_prefix ::= */
112590 {yygotominor.yy347 = 0;}
112591         break;
112592       case 134: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
112593 {
112594   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);
112595   sqlite3SrcListIndexedBy(pParse, yygotominor.yy347, &yymsp[-2].minor.yy0);
112596 }
112597         break;
112598       case 135: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
112599 {
112600     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);
112601   }
112602         break;
112603       case 136: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
112604 {
112605     if( yymsp[-6].minor.yy347==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy122==0 && yymsp[0].minor.yy180==0 ){
112606       yygotominor.yy347 = yymsp[-4].minor.yy347;
112607     }else if( yymsp[-4].minor.yy347->nSrc==1 ){
112608       yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
112609       if( yygotominor.yy347 ){
112610         struct SrcList_item *pNew = &yygotominor.yy347->a[yygotominor.yy347->nSrc-1];
112611         struct SrcList_item *pOld = yymsp[-4].minor.yy347->a;
112612         pNew->zName = pOld->zName;
112613         pNew->zDatabase = pOld->zDatabase;
112614         pNew->pSelect = pOld->pSelect;
112615         pOld->zName = pOld->zDatabase = 0;
112616         pOld->pSelect = 0;
112617       }
112618       sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy347);
112619     }else{
112620       Select *pSubquery;
112621       sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy347);
112622       pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy347,0,0,0,0,SF_NestedFrom,0,0);
112623       yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
112624     }
112625   }
112626         break;
112627       case 137: /* dbnm ::= */
112628       case 146: /* indexed_opt ::= */ yytestcase(yyruleno==146);
112629 {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
112630         break;
112631       case 139: /* fullname ::= nm dbnm */
112632 {yygotominor.yy347 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
112633         break;
112634       case 140: /* joinop ::= COMMA|JOIN */
112635 { yygotominor.yy392 = JT_INNER; }
112636         break;
112637       case 141: /* joinop ::= JOIN_KW JOIN */
112638 { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
112639         break;
112640       case 142: /* joinop ::= JOIN_KW nm JOIN */
112641 { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
112642         break;
112643       case 143: /* joinop ::= JOIN_KW nm nm JOIN */
112644 { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
112645         break;
112646       case 144: /* on_opt ::= ON expr */
112647       case 161: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==161);
112648       case 168: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==168);
112649       case 234: /* case_else ::= ELSE expr */ yytestcase(yyruleno==234);
112650       case 236: /* case_operand ::= expr */ yytestcase(yyruleno==236);
112651 {yygotominor.yy122 = yymsp[0].minor.yy342.pExpr;}
112652         break;
112653       case 145: /* on_opt ::= */
112654       case 160: /* having_opt ::= */ yytestcase(yyruleno==160);
112655       case 167: /* where_opt ::= */ yytestcase(yyruleno==167);
112656       case 235: /* case_else ::= */ yytestcase(yyruleno==235);
112657       case 237: /* case_operand ::= */ yytestcase(yyruleno==237);
112658 {yygotominor.yy122 = 0;}
112659         break;
112660       case 148: /* indexed_opt ::= NOT INDEXED */
112661 {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
112662         break;
112663       case 149: /* using_opt ::= USING LP inscollist RP */
112664       case 180: /* inscollist_opt ::= LP inscollist RP */ yytestcase(yyruleno==180);
112665 {yygotominor.yy180 = yymsp[-1].minor.yy180;}
112666         break;
112667       case 150: /* using_opt ::= */
112668       case 179: /* inscollist_opt ::= */ yytestcase(yyruleno==179);
112669 {yygotominor.yy180 = 0;}
112670         break;
112671       case 152: /* orderby_opt ::= ORDER BY sortlist */
112672       case 159: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==159);
112673       case 238: /* exprlist ::= nexprlist */ yytestcase(yyruleno==238);
112674 {yygotominor.yy442 = yymsp[0].minor.yy442;}
112675         break;
112676       case 153: /* sortlist ::= sortlist COMMA expr sortorder */
112677 {
112678   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442,yymsp[-1].minor.yy342.pExpr);
112679   if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
112680 }
112681         break;
112682       case 154: /* sortlist ::= expr sortorder */
112683 {
112684   yygotominor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy342.pExpr);
112685   if( yygotominor.yy442 && ALWAYS(yygotominor.yy442->a) ) yygotominor.yy442->a[0].sortOrder = (u8)yymsp[0].minor.yy392;
112686 }
112687         break;
112688       case 155: /* sortorder ::= ASC */
112689       case 157: /* sortorder ::= */ yytestcase(yyruleno==157);
112690 {yygotominor.yy392 = SQLITE_SO_ASC;}
112691         break;
112692       case 156: /* sortorder ::= DESC */
112693 {yygotominor.yy392 = SQLITE_SO_DESC;}
112694         break;
112695       case 162: /* limit_opt ::= */
112696 {yygotominor.yy64.pLimit = 0; yygotominor.yy64.pOffset = 0;}
112697         break;
112698       case 163: /* limit_opt ::= LIMIT expr */
112699 {yygotominor.yy64.pLimit = yymsp[0].minor.yy342.pExpr; yygotominor.yy64.pOffset = 0;}
112700         break;
112701       case 164: /* limit_opt ::= LIMIT expr OFFSET expr */
112702 {yygotominor.yy64.pLimit = yymsp[-2].minor.yy342.pExpr; yygotominor.yy64.pOffset = yymsp[0].minor.yy342.pExpr;}
112703         break;
112704       case 165: /* limit_opt ::= LIMIT expr COMMA expr */
112705 {yygotominor.yy64.pOffset = yymsp[-2].minor.yy342.pExpr; yygotominor.yy64.pLimit = yymsp[0].minor.yy342.pExpr;}
112706         break;
112707       case 166: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
112708 {
112709   sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy347, &yymsp[-1].minor.yy0);
112710   sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy347,yymsp[0].minor.yy122);
112711 }
112712         break;
112713       case 169: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
112714 {
112715   sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy347, &yymsp[-3].minor.yy0);
112716   sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy442,"set list"); 
112717   sqlite3Update(pParse,yymsp[-4].minor.yy347,yymsp[-1].minor.yy442,yymsp[0].minor.yy122,yymsp[-5].minor.yy258);
112718 }
112719         break;
112720       case 170: /* setlist ::= setlist COMMA nm EQ expr */
112721 {
112722   yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy442, yymsp[0].minor.yy342.pExpr);
112723   sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
112724 }
112725         break;
112726       case 171: /* setlist ::= nm EQ expr */
112727 {
112728   yygotominor.yy442 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy342.pExpr);
112729   sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
112730 }
112731         break;
112732       case 172: /* cmd ::= insert_cmd INTO fullname inscollist_opt valuelist */
112733 {sqlite3Insert(pParse, yymsp[-2].minor.yy347, yymsp[0].minor.yy487.pList, yymsp[0].minor.yy487.pSelect, yymsp[-1].minor.yy180, yymsp[-4].minor.yy258);}
112734         break;
112735       case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
112736 {sqlite3Insert(pParse, yymsp[-2].minor.yy347, 0, yymsp[0].minor.yy159, yymsp[-1].minor.yy180, yymsp[-4].minor.yy258);}
112737         break;
112738       case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
112739 {sqlite3Insert(pParse, yymsp[-3].minor.yy347, 0, 0, yymsp[-2].minor.yy180, yymsp[-5].minor.yy258);}
112740         break;
112741       case 175: /* insert_cmd ::= INSERT orconf */
112742 {yygotominor.yy258 = yymsp[0].minor.yy258;}
112743         break;
112744       case 176: /* insert_cmd ::= REPLACE */
112745 {yygotominor.yy258 = OE_Replace;}
112746         break;
112747       case 177: /* valuelist ::= VALUES LP nexprlist RP */
112748 {
112749   yygotominor.yy487.pList = yymsp[-1].minor.yy442;
112750   yygotominor.yy487.pSelect = 0;
112751 }
112752         break;
112753       case 178: /* valuelist ::= valuelist COMMA LP exprlist RP */
112754 {
112755   Select *pRight = sqlite3SelectNew(pParse, yymsp[-1].minor.yy442, 0, 0, 0, 0, 0, 0, 0, 0);
112756   if( yymsp[-4].minor.yy487.pList ){
112757     yymsp[-4].minor.yy487.pSelect = sqlite3SelectNew(pParse, yymsp[-4].minor.yy487.pList, 0, 0, 0, 0, 0, 0, 0, 0);
112758     yymsp[-4].minor.yy487.pList = 0;
112759   }
112760   yygotominor.yy487.pList = 0;
112761   if( yymsp[-4].minor.yy487.pSelect==0 || pRight==0 ){
112762     sqlite3SelectDelete(pParse->db, pRight);
112763     sqlite3SelectDelete(pParse->db, yymsp[-4].minor.yy487.pSelect);
112764     yygotominor.yy487.pSelect = 0;
112765   }else{
112766     pRight->op = TK_ALL;
112767     pRight->pPrior = yymsp[-4].minor.yy487.pSelect;
112768     pRight->selFlags |= SF_Values;
112769     pRight->pPrior->selFlags |= SF_Values;
112770     yygotominor.yy487.pSelect = pRight;
112771   }
112772 }
112773         break;
112774       case 181: /* inscollist ::= inscollist COMMA nm */
112775 {yygotominor.yy180 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy180,&yymsp[0].minor.yy0);}
112776         break;
112777       case 182: /* inscollist ::= nm */
112778 {yygotominor.yy180 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
112779         break;
112780       case 183: /* expr ::= term */
112781 {yygotominor.yy342 = yymsp[0].minor.yy342;}
112782         break;
112783       case 184: /* expr ::= LP expr RP */
112784 {yygotominor.yy342.pExpr = yymsp[-1].minor.yy342.pExpr; spanSet(&yygotominor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
112785         break;
112786       case 185: /* term ::= NULL */
112787       case 190: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==190);
112788       case 191: /* term ::= STRING */ yytestcase(yyruleno==191);
112789 {spanExpr(&yygotominor.yy342, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
112790         break;
112791       case 186: /* expr ::= id */
112792       case 187: /* expr ::= JOIN_KW */ yytestcase(yyruleno==187);
112793 {spanExpr(&yygotominor.yy342, pParse, TK_ID, &yymsp[0].minor.yy0);}
112794         break;
112795       case 188: /* expr ::= nm DOT nm */
112796 {
112797   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
112798   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
112799   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
112800   spanSet(&yygotominor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
112801 }
112802         break;
112803       case 189: /* expr ::= nm DOT nm DOT nm */
112804 {
112805   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
112806   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
112807   Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
112808   Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
112809   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
112810   spanSet(&yygotominor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
112811 }
112812         break;
112813       case 192: /* expr ::= REGISTER */
112814 {
112815   /* When doing a nested parse, one can include terms in an expression
112816   ** that look like this:   #1 #2 ...  These terms refer to registers
112817   ** in the virtual machine.  #N is the N-th register. */
112818   if( pParse->nested==0 ){
112819     sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
112820     yygotominor.yy342.pExpr = 0;
112821   }else{
112822     yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
112823     if( yygotominor.yy342.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy342.pExpr->iTable);
112824   }
112825   spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
112826 }
112827         break;
112828       case 193: /* expr ::= VARIABLE */
112829 {
112830   spanExpr(&yygotominor.yy342, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
112831   sqlite3ExprAssignVarNumber(pParse, yygotominor.yy342.pExpr);
112832   spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
112833 }
112834         break;
112835       case 194: /* expr ::= expr COLLATE ids */
112836 {
112837   yygotominor.yy342.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy342.pExpr, &yymsp[0].minor.yy0);
112838   yygotominor.yy342.zStart = yymsp[-2].minor.yy342.zStart;
112839   yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
112840 }
112841         break;
112842       case 195: /* expr ::= CAST LP expr AS typetoken RP */
112843 {
112844   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy342.pExpr, 0, &yymsp[-1].minor.yy0);
112845   spanSet(&yygotominor.yy342,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
112846 }
112847         break;
112848       case 196: /* expr ::= ID LP distinct exprlist RP */
112849 {
112850   if( yymsp[-1].minor.yy442 && yymsp[-1].minor.yy442->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
112851     sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
112852   }
112853   yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy442, &yymsp[-4].minor.yy0);
112854   spanSet(&yygotominor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
112855   if( yymsp[-2].minor.yy305 && yygotominor.yy342.pExpr ){
112856     yygotominor.yy342.pExpr->flags |= EP_Distinct;
112857   }
112858 }
112859         break;
112860       case 197: /* expr ::= ID LP STAR RP */
112861 {
112862   yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
112863   spanSet(&yygotominor.yy342,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
112864 }
112865         break;
112866       case 198: /* term ::= CTIME_KW */
112867 {
112868   /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
112869   ** treated as functions that return constants */
112870   yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
112871   if( yygotominor.yy342.pExpr ){
112872     yygotominor.yy342.pExpr->op = TK_CONST_FUNC;  
112873   }
112874   spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
112875 }
112876         break;
112877       case 199: /* expr ::= expr AND expr */
112878       case 200: /* expr ::= expr OR expr */ yytestcase(yyruleno==200);
112879       case 201: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==201);
112880       case 202: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==202);
112881       case 203: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==203);
112882       case 204: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==204);
112883       case 205: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==205);
112884       case 206: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==206);
112885 {spanBinaryExpr(&yygotominor.yy342,pParse,yymsp[-1].major,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy342);}
112886         break;
112887       case 207: /* likeop ::= LIKE_KW */
112888       case 209: /* likeop ::= MATCH */ yytestcase(yyruleno==209);
112889 {yygotominor.yy318.eOperator = yymsp[0].minor.yy0; yygotominor.yy318.bNot = 0;}
112890         break;
112891       case 208: /* likeop ::= NOT LIKE_KW */
112892       case 210: /* likeop ::= NOT MATCH */ yytestcase(yyruleno==210);
112893 {yygotominor.yy318.eOperator = yymsp[0].minor.yy0; yygotominor.yy318.bNot = 1;}
112894         break;
112895       case 211: /* expr ::= expr likeop expr */
112896 {
112897   ExprList *pList;
112898   pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy342.pExpr);
112899   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy342.pExpr);
112900   yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy318.eOperator);
112901   if( yymsp[-1].minor.yy318.bNot ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
112902   yygotominor.yy342.zStart = yymsp[-2].minor.yy342.zStart;
112903   yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
112904   if( yygotominor.yy342.pExpr ) yygotominor.yy342.pExpr->flags |= EP_InfixFunc;
112905 }
112906         break;
112907       case 212: /* expr ::= expr likeop expr ESCAPE expr */
112908 {
112909   ExprList *pList;
112910   pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
112911   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy342.pExpr);
112912   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy342.pExpr);
112913   yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy318.eOperator);
112914   if( yymsp[-3].minor.yy318.bNot ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
112915   yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
112916   yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
112917   if( yygotominor.yy342.pExpr ) yygotominor.yy342.pExpr->flags |= EP_InfixFunc;
112918 }
112919         break;
112920       case 213: /* expr ::= expr ISNULL|NOTNULL */
112921 {spanUnaryPostfix(&yygotominor.yy342,pParse,yymsp[0].major,&yymsp[-1].minor.yy342,&yymsp[0].minor.yy0);}
112922         break;
112923       case 214: /* expr ::= expr NOT NULL */
112924 {spanUnaryPostfix(&yygotominor.yy342,pParse,TK_NOTNULL,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy0);}
112925         break;
112926       case 215: /* expr ::= expr IS expr */
112927 {
112928   spanBinaryExpr(&yygotominor.yy342,pParse,TK_IS,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy342);
112929   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy342.pExpr, yygotominor.yy342.pExpr, TK_ISNULL);
112930 }
112931         break;
112932       case 216: /* expr ::= expr IS NOT expr */
112933 {
112934   spanBinaryExpr(&yygotominor.yy342,pParse,TK_ISNOT,&yymsp[-3].minor.yy342,&yymsp[0].minor.yy342);
112935   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy342.pExpr, yygotominor.yy342.pExpr, TK_NOTNULL);
112936 }
112937         break;
112938       case 217: /* expr ::= NOT expr */
112939       case 218: /* expr ::= BITNOT expr */ yytestcase(yyruleno==218);
112940 {spanUnaryPrefix(&yygotominor.yy342,pParse,yymsp[-1].major,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
112941         break;
112942       case 219: /* expr ::= MINUS expr */
112943 {spanUnaryPrefix(&yygotominor.yy342,pParse,TK_UMINUS,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
112944         break;
112945       case 220: /* expr ::= PLUS expr */
112946 {spanUnaryPrefix(&yygotominor.yy342,pParse,TK_UPLUS,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
112947         break;
112948       case 223: /* expr ::= expr between_op expr AND expr */
112949 {
112950   ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
112951   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy342.pExpr);
112952   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy342.pExpr, 0, 0);
112953   if( yygotominor.yy342.pExpr ){
112954     yygotominor.yy342.pExpr->x.pList = pList;
112955   }else{
112956     sqlite3ExprListDelete(pParse->db, pList);
112957   } 
112958   if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
112959   yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
112960   yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
112961 }
112962         break;
112963       case 226: /* expr ::= expr in_op LP exprlist RP */
112964 {
112965     if( yymsp[-1].minor.yy442==0 ){
112966       /* Expressions of the form
112967       **
112968       **      expr1 IN ()
112969       **      expr1 NOT IN ()
112970       **
112971       ** simplify to constants 0 (false) and 1 (true), respectively,
112972       ** regardless of the value of expr1.
112973       */
112974       yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy392]);
112975       sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy342.pExpr);
112976     }else{
112977       yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy342.pExpr, 0, 0);
112978       if( yygotominor.yy342.pExpr ){
112979         yygotominor.yy342.pExpr->x.pList = yymsp[-1].minor.yy442;
112980         sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
112981       }else{
112982         sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy442);
112983       }
112984       if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
112985     }
112986     yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
112987     yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
112988   }
112989         break;
112990       case 227: /* expr ::= LP select RP */
112991 {
112992     yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
112993     if( yygotominor.yy342.pExpr ){
112994       yygotominor.yy342.pExpr->x.pSelect = yymsp[-1].minor.yy159;
112995       ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
112996       sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
112997     }else{
112998       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
112999     }
113000     yygotominor.yy342.zStart = yymsp[-2].minor.yy0.z;
113001     yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
113002   }
113003         break;
113004       case 228: /* expr ::= expr in_op LP select RP */
113005 {
113006     yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy342.pExpr, 0, 0);
113007     if( yygotominor.yy342.pExpr ){
113008       yygotominor.yy342.pExpr->x.pSelect = yymsp[-1].minor.yy159;
113009       ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
113010       sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
113011     }else{
113012       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
113013     }
113014     if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
113015     yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
113016     yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
113017   }
113018         break;
113019       case 229: /* expr ::= expr in_op nm dbnm */
113020 {
113021     SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
113022     yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy342.pExpr, 0, 0);
113023     if( yygotominor.yy342.pExpr ){
113024       yygotominor.yy342.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
113025       ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
113026       sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
113027     }else{
113028       sqlite3SrcListDelete(pParse->db, pSrc);
113029     }
113030     if( yymsp[-2].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
113031     yygotominor.yy342.zStart = yymsp[-3].minor.yy342.zStart;
113032     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];
113033   }
113034         break;
113035       case 230: /* expr ::= EXISTS LP select RP */
113036 {
113037     Expr *p = yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
113038     if( p ){
113039       p->x.pSelect = yymsp[-1].minor.yy159;
113040       ExprSetProperty(p, EP_xIsSelect);
113041       sqlite3ExprSetHeight(pParse, p);
113042     }else{
113043       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
113044     }
113045     yygotominor.yy342.zStart = yymsp[-3].minor.yy0.z;
113046     yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
113047   }
113048         break;
113049       case 231: /* expr ::= CASE case_operand case_exprlist case_else END */
113050 {
113051   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy122, yymsp[-1].minor.yy122, 0);
113052   if( yygotominor.yy342.pExpr ){
113053     yygotominor.yy342.pExpr->x.pList = yymsp[-2].minor.yy442;
113054     sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
113055   }else{
113056     sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy442);
113057   }
113058   yygotominor.yy342.zStart = yymsp[-4].minor.yy0.z;
113059   yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
113060 }
113061         break;
113062       case 232: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
113063 {
113064   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442, yymsp[-2].minor.yy342.pExpr);
113065   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yygotominor.yy442, yymsp[0].minor.yy342.pExpr);
113066 }
113067         break;
113068       case 233: /* case_exprlist ::= WHEN expr THEN expr */
113069 {
113070   yygotominor.yy442 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
113071   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yygotominor.yy442, yymsp[0].minor.yy342.pExpr);
113072 }
113073         break;
113074       case 240: /* nexprlist ::= nexprlist COMMA expr */
113075 {yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy442,yymsp[0].minor.yy342.pExpr);}
113076         break;
113077       case 241: /* nexprlist ::= expr */
113078 {yygotominor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy342.pExpr);}
113079         break;
113080       case 242: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
113081 {
113082   sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0, 
113083                      sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy442, yymsp[-9].minor.yy392,
113084                       &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy392);
113085 }
113086         break;
113087       case 243: /* uniqueflag ::= UNIQUE */
113088       case 296: /* raisetype ::= ABORT */ yytestcase(yyruleno==296);
113089 {yygotominor.yy392 = OE_Abort;}
113090         break;
113091       case 244: /* uniqueflag ::= */
113092 {yygotominor.yy392 = OE_None;}
113093         break;
113094       case 247: /* idxlist ::= idxlist COMMA nm collate sortorder */
113095 {
113096   Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0);
113097   yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442, p);
113098   sqlite3ExprListSetName(pParse,yygotominor.yy442,&yymsp[-2].minor.yy0,1);
113099   sqlite3ExprListCheckLength(pParse, yygotominor.yy442, "index");
113100   if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
113101 }
113102         break;
113103       case 248: /* idxlist ::= nm collate sortorder */
113104 {
113105   Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0);
113106   yygotominor.yy442 = sqlite3ExprListAppend(pParse,0, p);
113107   sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
113108   sqlite3ExprListCheckLength(pParse, yygotominor.yy442, "index");
113109   if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
113110 }
113111         break;
113112       case 249: /* collate ::= */
113113 {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
113114         break;
113115       case 251: /* cmd ::= DROP INDEX ifexists fullname */
113116 {sqlite3DropIndex(pParse, yymsp[0].minor.yy347, yymsp[-1].minor.yy392);}
113117         break;
113118       case 252: /* cmd ::= VACUUM */
113119       case 253: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==253);
113120 {sqlite3Vacuum(pParse);}
113121         break;
113122       case 254: /* cmd ::= PRAGMA nm dbnm */
113123 {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
113124         break;
113125       case 255: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
113126 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
113127         break;
113128       case 256: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
113129 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
113130         break;
113131       case 257: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
113132 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
113133         break;
113134       case 258: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
113135 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
113136         break;
113137       case 268: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
113138 {
113139   Token all;
113140   all.z = yymsp[-3].minor.yy0.z;
113141   all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
113142   sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy327, &all);
113143 }
113144         break;
113145       case 269: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
113146 {
113147   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);
113148   yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
113149 }
113150         break;
113151       case 270: /* trigger_time ::= BEFORE */
113152       case 273: /* trigger_time ::= */ yytestcase(yyruleno==273);
113153 { yygotominor.yy392 = TK_BEFORE; }
113154         break;
113155       case 271: /* trigger_time ::= AFTER */
113156 { yygotominor.yy392 = TK_AFTER;  }
113157         break;
113158       case 272: /* trigger_time ::= INSTEAD OF */
113159 { yygotominor.yy392 = TK_INSTEAD;}
113160         break;
113161       case 274: /* trigger_event ::= DELETE|INSERT */
113162       case 275: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==275);
113163 {yygotominor.yy410.a = yymsp[0].major; yygotominor.yy410.b = 0;}
113164         break;
113165       case 276: /* trigger_event ::= UPDATE OF inscollist */
113166 {yygotominor.yy410.a = TK_UPDATE; yygotominor.yy410.b = yymsp[0].minor.yy180;}
113167         break;
113168       case 279: /* when_clause ::= */
113169       case 301: /* key_opt ::= */ yytestcase(yyruleno==301);
113170 { yygotominor.yy122 = 0; }
113171         break;
113172       case 280: /* when_clause ::= WHEN expr */
113173       case 302: /* key_opt ::= KEY expr */ yytestcase(yyruleno==302);
113174 { yygotominor.yy122 = yymsp[0].minor.yy342.pExpr; }
113175         break;
113176       case 281: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
113177 {
113178   assert( yymsp[-2].minor.yy327!=0 );
113179   yymsp[-2].minor.yy327->pLast->pNext = yymsp[-1].minor.yy327;
113180   yymsp[-2].minor.yy327->pLast = yymsp[-1].minor.yy327;
113181   yygotominor.yy327 = yymsp[-2].minor.yy327;
113182 }
113183         break;
113184       case 282: /* trigger_cmd_list ::= trigger_cmd SEMI */
113185
113186   assert( yymsp[-1].minor.yy327!=0 );
113187   yymsp[-1].minor.yy327->pLast = yymsp[-1].minor.yy327;
113188   yygotominor.yy327 = yymsp[-1].minor.yy327;
113189 }
113190         break;
113191       case 284: /* trnm ::= nm DOT nm */
113192 {
113193   yygotominor.yy0 = yymsp[0].minor.yy0;
113194   sqlite3ErrorMsg(pParse, 
113195         "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
113196         "statements within triggers");
113197 }
113198         break;
113199       case 286: /* tridxby ::= INDEXED BY nm */
113200 {
113201   sqlite3ErrorMsg(pParse,
113202         "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
113203         "within triggers");
113204 }
113205         break;
113206       case 287: /* tridxby ::= NOT INDEXED */
113207 {
113208   sqlite3ErrorMsg(pParse,
113209         "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
113210         "within triggers");
113211 }
113212         break;
113213       case 288: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
113214 { yygotominor.yy327 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy442, yymsp[0].minor.yy122, yymsp[-5].minor.yy258); }
113215         break;
113216       case 289: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt valuelist */
113217 {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);}
113218         break;
113219       case 290: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
113220 {yygotominor.yy327 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy180, 0, yymsp[0].minor.yy159, yymsp[-4].minor.yy258);}
113221         break;
113222       case 291: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
113223 {yygotominor.yy327 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy122);}
113224         break;
113225       case 292: /* trigger_cmd ::= select */
113226 {yygotominor.yy327 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy159); }
113227         break;
113228       case 293: /* expr ::= RAISE LP IGNORE RP */
113229 {
113230   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0); 
113231   if( yygotominor.yy342.pExpr ){
113232     yygotominor.yy342.pExpr->affinity = OE_Ignore;
113233   }
113234   yygotominor.yy342.zStart = yymsp[-3].minor.yy0.z;
113235   yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
113236 }
113237         break;
113238       case 294: /* expr ::= RAISE LP raisetype COMMA nm RP */
113239 {
113240   yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0); 
113241   if( yygotominor.yy342.pExpr ) {
113242     yygotominor.yy342.pExpr->affinity = (char)yymsp[-3].minor.yy392;
113243   }
113244   yygotominor.yy342.zStart = yymsp[-5].minor.yy0.z;
113245   yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
113246 }
113247         break;
113248       case 295: /* raisetype ::= ROLLBACK */
113249 {yygotominor.yy392 = OE_Rollback;}
113250         break;
113251       case 297: /* raisetype ::= FAIL */
113252 {yygotominor.yy392 = OE_Fail;}
113253         break;
113254       case 298: /* cmd ::= DROP TRIGGER ifexists fullname */
113255 {
113256   sqlite3DropTrigger(pParse,yymsp[0].minor.yy347,yymsp[-1].minor.yy392);
113257 }
113258         break;
113259       case 299: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
113260 {
113261   sqlite3Attach(pParse, yymsp[-3].minor.yy342.pExpr, yymsp[-1].minor.yy342.pExpr, yymsp[0].minor.yy122);
113262 }
113263         break;
113264       case 300: /* cmd ::= DETACH database_kw_opt expr */
113265 {
113266   sqlite3Detach(pParse, yymsp[0].minor.yy342.pExpr);
113267 }
113268         break;
113269       case 305: /* cmd ::= REINDEX */
113270 {sqlite3Reindex(pParse, 0, 0);}
113271         break;
113272       case 306: /* cmd ::= REINDEX nm dbnm */
113273 {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
113274         break;
113275       case 307: /* cmd ::= ANALYZE */
113276 {sqlite3Analyze(pParse, 0, 0);}
113277         break;
113278       case 308: /* cmd ::= ANALYZE nm dbnm */
113279 {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
113280         break;
113281       case 309: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
113282 {
113283   sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy347,&yymsp[0].minor.yy0);
113284 }
113285         break;
113286       case 310: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
113287 {
113288   sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
113289 }
113290         break;
113291       case 311: /* add_column_fullname ::= fullname */
113292 {
113293   pParse->db->lookaside.bEnabled = 0;
113294   sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy347);
113295 }
113296         break;
113297       case 314: /* cmd ::= create_vtab */
113298 {sqlite3VtabFinishParse(pParse,0);}
113299         break;
113300       case 315: /* cmd ::= create_vtab LP vtabarglist RP */
113301 {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
113302         break;
113303       case 316: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
113304 {
113305     sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy392);
113306 }
113307         break;
113308       case 319: /* vtabarg ::= */
113309 {sqlite3VtabArgInit(pParse);}
113310         break;
113311       case 321: /* vtabargtoken ::= ANY */
113312       case 322: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==322);
113313       case 323: /* lp ::= LP */ yytestcase(yyruleno==323);
113314 {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
113315         break;
113316       default:
113317       /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
113318       /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
113319       /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
113320       /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
113321       /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
113322       /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
113323       /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
113324       /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
113325       /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
113326       /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
113327       /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
113328       /* (34) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==34);
113329       /* (35) columnlist ::= column */ yytestcase(yyruleno==35);
113330       /* (44) type ::= */ yytestcase(yyruleno==44);
113331       /* (51) signed ::= plus_num */ yytestcase(yyruleno==51);
113332       /* (52) signed ::= minus_num */ yytestcase(yyruleno==52);
113333       /* (53) carglist ::= carglist ccons */ yytestcase(yyruleno==53);
113334       /* (54) carglist ::= */ yytestcase(yyruleno==54);
113335       /* (61) ccons ::= NULL onconf */ yytestcase(yyruleno==61);
113336       /* (89) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==89);
113337       /* (90) conslist ::= tcons */ yytestcase(yyruleno==90);
113338       /* (92) tconscomma ::= */ yytestcase(yyruleno==92);
113339       /* (277) foreach_clause ::= */ yytestcase(yyruleno==277);
113340       /* (278) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==278);
113341       /* (285) tridxby ::= */ yytestcase(yyruleno==285);
113342       /* (303) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==303);
113343       /* (304) database_kw_opt ::= */ yytestcase(yyruleno==304);
113344       /* (312) kwcolumn_opt ::= */ yytestcase(yyruleno==312);
113345       /* (313) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==313);
113346       /* (317) vtabarglist ::= vtabarg */ yytestcase(yyruleno==317);
113347       /* (318) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==318);
113348       /* (320) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==320);
113349       /* (324) anylist ::= */ yytestcase(yyruleno==324);
113350       /* (325) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==325);
113351       /* (326) anylist ::= anylist ANY */ yytestcase(yyruleno==326);
113352         break;
113353   };
113354   assert( yyruleno>=0 && yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) );
113355   yygoto = yyRuleInfo[yyruleno].lhs;
113356   yysize = yyRuleInfo[yyruleno].nrhs;
113357   yypParser->yyidx -= yysize;
113358   yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
113359   if( yyact < YYNSTATE ){
113360 #ifdef NDEBUG
113361     /* If we are not debugging and the reduce action popped at least
113362     ** one element off the stack, then we can push the new element back
113363     ** onto the stack here, and skip the stack overflow test in yy_shift().
113364     ** That gives a significant speed improvement. */
113365     if( yysize ){
113366       yypParser->yyidx++;
113367       yymsp -= yysize-1;
113368       yymsp->stateno = (YYACTIONTYPE)yyact;
113369       yymsp->major = (YYCODETYPE)yygoto;
113370       yymsp->minor = yygotominor;
113371     }else
113372 #endif
113373     {
113374       yy_shift(yypParser,yyact,yygoto,&yygotominor);
113375     }
113376   }else{
113377     assert( yyact == YYNSTATE + YYNRULE + 1 );
113378     yy_accept(yypParser);
113379   }
113380 }
113381
113382 /*
113383 ** The following code executes when the parse fails
113384 */
113385 #ifndef YYNOERRORRECOVERY
113386 static void yy_parse_failed(
113387   yyParser *yypParser           /* The parser */
113388 ){
113389   sqlite3ParserARG_FETCH;
113390 #ifndef NDEBUG
113391   if( yyTraceFILE ){
113392     fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
113393   }
113394 #endif
113395   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
113396   /* Here code is inserted which will be executed whenever the
113397   ** parser fails */
113398   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
113399 }
113400 #endif /* YYNOERRORRECOVERY */
113401
113402 /*
113403 ** The following code executes when a syntax error first occurs.
113404 */
113405 static void yy_syntax_error(
113406   yyParser *yypParser,           /* The parser */
113407   int yymajor,                   /* The major type of the error token */
113408   YYMINORTYPE yyminor            /* The minor type of the error token */
113409 ){
113410   sqlite3ParserARG_FETCH;
113411 #define TOKEN (yyminor.yy0)
113412
113413   UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
113414   assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
113415   sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
113416   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
113417 }
113418
113419 /*
113420 ** The following is executed when the parser accepts
113421 */
113422 static void yy_accept(
113423   yyParser *yypParser           /* The parser */
113424 ){
113425   sqlite3ParserARG_FETCH;
113426 #ifndef NDEBUG
113427   if( yyTraceFILE ){
113428     fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
113429   }
113430 #endif
113431   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
113432   /* Here code is inserted which will be executed whenever the
113433   ** parser accepts */
113434   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
113435 }
113436
113437 /* The main parser program.
113438 ** The first argument is a pointer to a structure obtained from
113439 ** "sqlite3ParserAlloc" which describes the current state of the parser.
113440 ** The second argument is the major token number.  The third is
113441 ** the minor token.  The fourth optional argument is whatever the
113442 ** user wants (and specified in the grammar) and is available for
113443 ** use by the action routines.
113444 **
113445 ** Inputs:
113446 ** <ul>
113447 ** <li> A pointer to the parser (an opaque structure.)
113448 ** <li> The major token number.
113449 ** <li> The minor token number.
113450 ** <li> An option argument of a grammar-specified type.
113451 ** </ul>
113452 **
113453 ** Outputs:
113454 ** None.
113455 */
113456 SQLITE_PRIVATE void sqlite3Parser(
113457   void *yyp,                   /* The parser */
113458   int yymajor,                 /* The major token code number */
113459   sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
113460   sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
113461 ){
113462   YYMINORTYPE yyminorunion;
113463   int yyact;            /* The parser action. */
113464 #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
113465   int yyendofinput;     /* True if we are at the end of input */
113466 #endif
113467 #ifdef YYERRORSYMBOL
113468   int yyerrorhit = 0;   /* True if yymajor has invoked an error */
113469 #endif
113470   yyParser *yypParser;  /* The parser */
113471
113472   /* (re)initialize the parser, if necessary */
113473   yypParser = (yyParser*)yyp;
113474   if( yypParser->yyidx<0 ){
113475 #if YYSTACKDEPTH<=0
113476     if( yypParser->yystksz <=0 ){
113477       /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
113478       yyminorunion = yyzerominor;
113479       yyStackOverflow(yypParser, &yyminorunion);
113480       return;
113481     }
113482 #endif
113483     yypParser->yyidx = 0;
113484     yypParser->yyerrcnt = -1;
113485     yypParser->yystack[0].stateno = 0;
113486     yypParser->yystack[0].major = 0;
113487   }
113488   yyminorunion.yy0 = yyminor;
113489 #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
113490   yyendofinput = (yymajor==0);
113491 #endif
113492   sqlite3ParserARG_STORE;
113493
113494 #ifndef NDEBUG
113495   if( yyTraceFILE ){
113496     fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
113497   }
113498 #endif
113499
113500   do{
113501     yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
113502     if( yyact<YYNSTATE ){
113503       yy_shift(yypParser,yyact,yymajor,&yyminorunion);
113504       yypParser->yyerrcnt--;
113505       yymajor = YYNOCODE;
113506     }else if( yyact < YYNSTATE + YYNRULE ){
113507       yy_reduce(yypParser,yyact-YYNSTATE);
113508     }else{
113509       assert( yyact == YY_ERROR_ACTION );
113510 #ifdef YYERRORSYMBOL
113511       int yymx;
113512 #endif
113513 #ifndef NDEBUG
113514       if( yyTraceFILE ){
113515         fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
113516       }
113517 #endif
113518 #ifdef YYERRORSYMBOL
113519       /* A syntax error has occurred.
113520       ** The response to an error depends upon whether or not the
113521       ** grammar defines an error token "ERROR".  
113522       **
113523       ** This is what we do if the grammar does define ERROR:
113524       **
113525       **  * Call the %syntax_error function.
113526       **
113527       **  * Begin popping the stack until we enter a state where
113528       **    it is legal to shift the error symbol, then shift
113529       **    the error symbol.
113530       **
113531       **  * Set the error count to three.
113532       **
113533       **  * Begin accepting and shifting new tokens.  No new error
113534       **    processing will occur until three tokens have been
113535       **    shifted successfully.
113536       **
113537       */
113538       if( yypParser->yyerrcnt<0 ){
113539         yy_syntax_error(yypParser,yymajor,yyminorunion);
113540       }
113541       yymx = yypParser->yystack[yypParser->yyidx].major;
113542       if( yymx==YYERRORSYMBOL || yyerrorhit ){
113543 #ifndef NDEBUG
113544         if( yyTraceFILE ){
113545           fprintf(yyTraceFILE,"%sDiscard input token %s\n",
113546              yyTracePrompt,yyTokenName[yymajor]);
113547         }
113548 #endif
113549         yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
113550         yymajor = YYNOCODE;
113551       }else{
113552          while(
113553           yypParser->yyidx >= 0 &&
113554           yymx != YYERRORSYMBOL &&
113555           (yyact = yy_find_reduce_action(
113556                         yypParser->yystack[yypParser->yyidx].stateno,
113557                         YYERRORSYMBOL)) >= YYNSTATE
113558         ){
113559           yy_pop_parser_stack(yypParser);
113560         }
113561         if( yypParser->yyidx < 0 || yymajor==0 ){
113562           yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
113563           yy_parse_failed(yypParser);
113564           yymajor = YYNOCODE;
113565         }else if( yymx!=YYERRORSYMBOL ){
113566           YYMINORTYPE u2;
113567           u2.YYERRSYMDT = 0;
113568           yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
113569         }
113570       }
113571       yypParser->yyerrcnt = 3;
113572       yyerrorhit = 1;
113573 #elif defined(YYNOERRORRECOVERY)
113574       /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
113575       ** do any kind of error recovery.  Instead, simply invoke the syntax
113576       ** error routine and continue going as if nothing had happened.
113577       **
113578       ** Applications can set this macro (for example inside %include) if
113579       ** they intend to abandon the parse upon the first syntax error seen.
113580       */
113581       yy_syntax_error(yypParser,yymajor,yyminorunion);
113582       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
113583       yymajor = YYNOCODE;
113584       
113585 #else  /* YYERRORSYMBOL is not defined */
113586       /* This is what we do if the grammar does not define ERROR:
113587       **
113588       **  * Report an error message, and throw away the input token.
113589       **
113590       **  * If the input token is $, then fail the parse.
113591       **
113592       ** As before, subsequent error messages are suppressed until
113593       ** three input tokens have been successfully shifted.
113594       */
113595       if( yypParser->yyerrcnt<=0 ){
113596         yy_syntax_error(yypParser,yymajor,yyminorunion);
113597       }
113598       yypParser->yyerrcnt = 3;
113599       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
113600       if( yyendofinput ){
113601         yy_parse_failed(yypParser);
113602       }
113603       yymajor = YYNOCODE;
113604 #endif
113605     }
113606   }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
113607   return;
113608 }
113609
113610 /************** End of parse.c ***********************************************/
113611 /************** Begin file tokenize.c ****************************************/
113612 /*
113613 ** 2001 September 15
113614 **
113615 ** The author disclaims copyright to this source code.  In place of
113616 ** a legal notice, here is a blessing:
113617 **
113618 **    May you do good and not evil.
113619 **    May you find forgiveness for yourself and forgive others.
113620 **    May you share freely, never taking more than you give.
113621 **
113622 *************************************************************************
113623 ** An tokenizer for SQL
113624 **
113625 ** This file contains C code that splits an SQL input string up into
113626 ** individual tokens and sends those tokens one-by-one over to the
113627 ** parser for analysis.
113628 */
113629 /* #include <stdlib.h> */
113630
113631 /*
113632 ** The charMap() macro maps alphabetic characters into their
113633 ** lower-case ASCII equivalent.  On ASCII machines, this is just
113634 ** an upper-to-lower case map.  On EBCDIC machines we also need
113635 ** to adjust the encoding.  Only alphabetic characters and underscores
113636 ** need to be translated.
113637 */
113638 #ifdef SQLITE_ASCII
113639 # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
113640 #endif
113641 #ifdef SQLITE_EBCDIC
113642 # define charMap(X) ebcdicToAscii[(unsigned char)X]
113643 const unsigned char ebcdicToAscii[] = {
113644 /* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
113645    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
113646    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
113647    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
113648    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
113649    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
113650    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
113651    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
113652    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
113653    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
113654    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
113655    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
113656    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
113657    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
113658    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
113659    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
113660    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
113661 };
113662 #endif
113663
113664 /*
113665 ** The sqlite3KeywordCode function looks up an identifier to determine if
113666 ** it is a keyword.  If it is a keyword, the token code of that keyword is 
113667 ** returned.  If the input is not a keyword, TK_ID is returned.
113668 **
113669 ** The implementation of this routine was generated by a program,
113670 ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
113671 ** The output of the mkkeywordhash.c program is written into a file
113672 ** named keywordhash.h and then included into this source file by
113673 ** the #include below.
113674 */
113675 /************** Include keywordhash.h in the middle of tokenize.c ************/
113676 /************** Begin file keywordhash.h *************************************/
113677 /***** This file contains automatically generated code ******
113678 **
113679 ** The code in this file has been automatically generated by
113680 **
113681 **   sqlite/tool/mkkeywordhash.c
113682 **
113683 ** The code in this file implements a function that determines whether
113684 ** or not a given identifier is really an SQL keyword.  The same thing
113685 ** might be implemented more directly using a hand-written hash table.
113686 ** But by using this automatically generated code, the size of the code
113687 ** is substantially reduced.  This is important for embedded applications
113688 ** on platforms with limited memory.
113689 */
113690 /* Hash score: 175 */
113691 static int keywordCode(const char *z, int n){
113692   /* zText[] encodes 811 bytes of keywords in 541 bytes */
113693   /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
113694   /*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */
113695   /*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */
113696   /*   UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE          */
113697   /*   CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN        */
113698   /*   SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME         */
113699   /*   AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS     */
113700   /*   CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF      */
113701   /*   ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW         */
113702   /*   INITIALLY                                                          */
113703   static const char zText[540] = {
113704     'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
113705     'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
113706     'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
113707     'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
113708     'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
113709     'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
113710     'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
113711     'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
113712     'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
113713     'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
113714     'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',
113715     'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',
113716     'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',
113717     'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
113718     'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
113719     'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
113720     'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',
113721     'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
113722     'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',
113723     'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',
113724     'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',
113725     'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',
113726     'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',
113727     'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',
113728     'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',
113729     'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',
113730     'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',
113731     'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',
113732     'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',
113733     'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',
113734   };
113735   static const unsigned char aHash[127] = {
113736       72, 101, 114,  70,   0,  45,   0,   0,  78,   0,  73,   0,   0,
113737       42,  12,  74,  15,   0, 113,  81,  50, 108,   0,  19,   0,   0,
113738      118,   0, 116, 111,   0,  22,  89,   0,   9,   0,   0,  66,  67,
113739        0,  65,   6,   0,  48,  86,  98,   0, 115,  97,   0,   0,  44,
113740        0,  99,  24,   0,  17,   0, 119,  49,  23,   0,   5, 106,  25,
113741       92,   0,   0, 121, 102,  56, 120,  53,  28,  51,   0,  87,   0,
113742       96,  26,   0,  95,   0,   0,   0,  91,  88,  93,  84, 105,  14,
113743       39, 104,   0,  77,   0,  18,  85, 107,  32,   0, 117,  76, 109,
113744       58,  46,  80,   0,   0,  90,  40,   0, 112,   0,  36,   0,   0,
113745       29,   0,  82,  59,  60,   0,  20,  57,   0,  52,
113746   };
113747   static const unsigned char aNext[121] = {
113748        0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
113749        0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
113750        0,   7,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
113751        0,   0,   0,   0,  33,   0,  21,   0,   0,   0,  43,   3,  47,
113752        0,   0,   0,   0,  30,   0,  54,   0,  38,   0,   0,   0,   1,
113753       62,   0,   0,  63,   0,  41,   0,   0,   0,   0,   0,   0,   0,
113754       61,   0,   0,   0,   0,  31,  55,  16,  34,  10,   0,   0,   0,
113755        0,   0,   0,   0,  11,  68,  75,   0,   8,   0, 100,  94,   0,
113756      103,   0,  83,   0,  71,   0,   0, 110,  27,  37,  69,  79,   0,
113757       35,  64,   0,   0,
113758   };
113759   static const unsigned char aLen[121] = {
113760        7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
113761        7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
113762       11,   6,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,
113763        4,   6,   2,   3,   9,   4,   2,   6,   5,   6,   6,   5,   6,
113764        5,   5,   7,   7,   7,   3,   2,   4,   4,   7,   3,   6,   4,
113765        7,   6,  12,   6,   9,   4,   6,   5,   4,   7,   6,   5,   6,
113766        7,   5,   4,   5,   6,   5,   7,   3,   7,  13,   2,   2,   4,
113767        6,   6,   8,   5,  17,  12,   7,   8,   8,   2,   4,   4,   4,
113768        4,   4,   2,   2,   6,   5,   8,   5,   5,   8,   3,   5,   5,
113769        6,   4,   9,   3,
113770   };
113771   static const unsigned short int aOffset[121] = {
113772        0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
113773       36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
113774       86,  91,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
113775      159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197,
113776      203, 206, 210, 217, 223, 223, 223, 226, 229, 233, 234, 238, 244,
113777      248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320,
113778      326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383,
113779      387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458,
113780      462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516,
113781      521, 527, 531, 536,
113782   };
113783   static const unsigned char aCode[121] = {
113784     TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,     
113785     TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,    
113786     TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,    
113787     TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,      
113788     TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,       
113789     TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,    
113790     TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,  
113791     TK_INTERSECT,  TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,       
113792     TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,       
113793     TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_ATTACH,     TK_HAVING,     
113794     TK_GROUP,      TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RELEASE,    
113795     TK_BETWEEN,    TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,       
113796     TK_LIKE_KW,    TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,       
113797     TK_COLLATE,    TK_CREATE,     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,  
113798     TK_JOIN,       TK_INSERT,     TK_MATCH,      TK_PLAN,       TK_ANALYZE,    
113799     TK_PRAGMA,     TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,      
113800     TK_WHEN,       TK_WHERE,      TK_RENAME,     TK_AFTER,      TK_REPLACE,    
113801     TK_AND,        TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         TK_IN,         
113802     TK_CAST,       TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,    
113803     TK_CTIME_KW,   TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,   
113804     TK_IS,         TK_DROP,       TK_FAIL,       TK_FROM,       TK_JOIN_KW,    
113805     TK_LIKE_KW,    TK_BY,         TK_IF,         TK_ISNULL,     TK_ORDER,      
113806     TK_RESTRICT,   TK_JOIN_KW,    TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,        
113807     TK_UNION,      TK_USING,      TK_VACUUM,     TK_VIEW,       TK_INITIALLY,  
113808     TK_ALL,        
113809   };
113810   int h, i;
113811   if( n<2 ) return TK_ID;
113812   h = ((charMap(z[0])*4) ^
113813       (charMap(z[n-1])*3) ^
113814       n) % 127;
113815   for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
113816     if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
113817       testcase( i==0 ); /* REINDEX */
113818       testcase( i==1 ); /* INDEXED */
113819       testcase( i==2 ); /* INDEX */
113820       testcase( i==3 ); /* DESC */
113821       testcase( i==4 ); /* ESCAPE */
113822       testcase( i==5 ); /* EACH */
113823       testcase( i==6 ); /* CHECK */
113824       testcase( i==7 ); /* KEY */
113825       testcase( i==8 ); /* BEFORE */
113826       testcase( i==9 ); /* FOREIGN */
113827       testcase( i==10 ); /* FOR */
113828       testcase( i==11 ); /* IGNORE */
113829       testcase( i==12 ); /* REGEXP */
113830       testcase( i==13 ); /* EXPLAIN */
113831       testcase( i==14 ); /* INSTEAD */
113832       testcase( i==15 ); /* ADD */
113833       testcase( i==16 ); /* DATABASE */
113834       testcase( i==17 ); /* AS */
113835       testcase( i==18 ); /* SELECT */
113836       testcase( i==19 ); /* TABLE */
113837       testcase( i==20 ); /* LEFT */
113838       testcase( i==21 ); /* THEN */
113839       testcase( i==22 ); /* END */
113840       testcase( i==23 ); /* DEFERRABLE */
113841       testcase( i==24 ); /* ELSE */
113842       testcase( i==25 ); /* EXCEPT */
113843       testcase( i==26 ); /* TRANSACTION */
113844       testcase( i==27 ); /* ACTION */
113845       testcase( i==28 ); /* ON */
113846       testcase( i==29 ); /* NATURAL */
113847       testcase( i==30 ); /* ALTER */
113848       testcase( i==31 ); /* RAISE */
113849       testcase( i==32 ); /* EXCLUSIVE */
113850       testcase( i==33 ); /* EXISTS */
113851       testcase( i==34 ); /* SAVEPOINT */
113852       testcase( i==35 ); /* INTERSECT */
113853       testcase( i==36 ); /* TRIGGER */
113854       testcase( i==37 ); /* REFERENCES */
113855       testcase( i==38 ); /* CONSTRAINT */
113856       testcase( i==39 ); /* INTO */
113857       testcase( i==40 ); /* OFFSET */
113858       testcase( i==41 ); /* OF */
113859       testcase( i==42 ); /* SET */
113860       testcase( i==43 ); /* TEMPORARY */
113861       testcase( i==44 ); /* TEMP */
113862       testcase( i==45 ); /* OR */
113863       testcase( i==46 ); /* UNIQUE */
113864       testcase( i==47 ); /* QUERY */
113865       testcase( i==48 ); /* ATTACH */
113866       testcase( i==49 ); /* HAVING */
113867       testcase( i==50 ); /* GROUP */
113868       testcase( i==51 ); /* UPDATE */
113869       testcase( i==52 ); /* BEGIN */
113870       testcase( i==53 ); /* INNER */
113871       testcase( i==54 ); /* RELEASE */
113872       testcase( i==55 ); /* BETWEEN */
113873       testcase( i==56 ); /* NOTNULL */
113874       testcase( i==57 ); /* NOT */
113875       testcase( i==58 ); /* NO */
113876       testcase( i==59 ); /* NULL */
113877       testcase( i==60 ); /* LIKE */
113878       testcase( i==61 ); /* CASCADE */
113879       testcase( i==62 ); /* ASC */
113880       testcase( i==63 ); /* DELETE */
113881       testcase( i==64 ); /* CASE */
113882       testcase( i==65 ); /* COLLATE */
113883       testcase( i==66 ); /* CREATE */
113884       testcase( i==67 ); /* CURRENT_DATE */
113885       testcase( i==68 ); /* DETACH */
113886       testcase( i==69 ); /* IMMEDIATE */
113887       testcase( i==70 ); /* JOIN */
113888       testcase( i==71 ); /* INSERT */
113889       testcase( i==72 ); /* MATCH */
113890       testcase( i==73 ); /* PLAN */
113891       testcase( i==74 ); /* ANALYZE */
113892       testcase( i==75 ); /* PRAGMA */
113893       testcase( i==76 ); /* ABORT */
113894       testcase( i==77 ); /* VALUES */
113895       testcase( i==78 ); /* VIRTUAL */
113896       testcase( i==79 ); /* LIMIT */
113897       testcase( i==80 ); /* WHEN */
113898       testcase( i==81 ); /* WHERE */
113899       testcase( i==82 ); /* RENAME */
113900       testcase( i==83 ); /* AFTER */
113901       testcase( i==84 ); /* REPLACE */
113902       testcase( i==85 ); /* AND */
113903       testcase( i==86 ); /* DEFAULT */
113904       testcase( i==87 ); /* AUTOINCREMENT */
113905       testcase( i==88 ); /* TO */
113906       testcase( i==89 ); /* IN */
113907       testcase( i==90 ); /* CAST */
113908       testcase( i==91 ); /* COLUMN */
113909       testcase( i==92 ); /* COMMIT */
113910       testcase( i==93 ); /* CONFLICT */
113911       testcase( i==94 ); /* CROSS */
113912       testcase( i==95 ); /* CURRENT_TIMESTAMP */
113913       testcase( i==96 ); /* CURRENT_TIME */
113914       testcase( i==97 ); /* PRIMARY */
113915       testcase( i==98 ); /* DEFERRED */
113916       testcase( i==99 ); /* DISTINCT */
113917       testcase( i==100 ); /* IS */
113918       testcase( i==101 ); /* DROP */
113919       testcase( i==102 ); /* FAIL */
113920       testcase( i==103 ); /* FROM */
113921       testcase( i==104 ); /* FULL */
113922       testcase( i==105 ); /* GLOB */
113923       testcase( i==106 ); /* BY */
113924       testcase( i==107 ); /* IF */
113925       testcase( i==108 ); /* ISNULL */
113926       testcase( i==109 ); /* ORDER */
113927       testcase( i==110 ); /* RESTRICT */
113928       testcase( i==111 ); /* OUTER */
113929       testcase( i==112 ); /* RIGHT */
113930       testcase( i==113 ); /* ROLLBACK */
113931       testcase( i==114 ); /* ROW */
113932       testcase( i==115 ); /* UNION */
113933       testcase( i==116 ); /* USING */
113934       testcase( i==117 ); /* VACUUM */
113935       testcase( i==118 ); /* VIEW */
113936       testcase( i==119 ); /* INITIALLY */
113937       testcase( i==120 ); /* ALL */
113938       return aCode[i];
113939     }
113940   }
113941   return TK_ID;
113942 }
113943 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
113944   return keywordCode((char*)z, n);
113945 }
113946 #define SQLITE_N_KEYWORD 121
113947
113948 /************** End of keywordhash.h *****************************************/
113949 /************** Continuing where we left off in tokenize.c *******************/
113950
113951
113952 /*
113953 ** If X is a character that can be used in an identifier then
113954 ** IdChar(X) will be true.  Otherwise it is false.
113955 **
113956 ** For ASCII, any character with the high-order bit set is
113957 ** allowed in an identifier.  For 7-bit characters, 
113958 ** sqlite3IsIdChar[X] must be 1.
113959 **
113960 ** For EBCDIC, the rules are more complex but have the same
113961 ** end result.
113962 **
113963 ** Ticket #1066.  the SQL standard does not allow '$' in the
113964 ** middle of identfiers.  But many SQL implementations do. 
113965 ** SQLite will allow '$' in identifiers for compatibility.
113966 ** But the feature is undocumented.
113967 */
113968 #ifdef SQLITE_ASCII
113969 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
113970 #endif
113971 #ifdef SQLITE_EBCDIC
113972 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
113973 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
113974     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
113975     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
113976     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
113977     0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
113978     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
113979     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
113980     1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
113981     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
113982     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
113983     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
113984     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
113985     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
113986 };
113987 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
113988 #endif
113989
113990
113991 /*
113992 ** Return the length of the token that begins at z[0]. 
113993 ** Store the token type in *tokenType before returning.
113994 */
113995 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
113996   int i, c;
113997   switch( *z ){
113998     case ' ': case '\t': case '\n': case '\f': case '\r': {
113999       testcase( z[0]==' ' );
114000       testcase( z[0]=='\t' );
114001       testcase( z[0]=='\n' );
114002       testcase( z[0]=='\f' );
114003       testcase( z[0]=='\r' );
114004       for(i=1; sqlite3Isspace(z[i]); i++){}
114005       *tokenType = TK_SPACE;
114006       return i;
114007     }
114008     case '-': {
114009       if( z[1]=='-' ){
114010         /* IMP: R-50417-27976 -- syntax diagram for comments */
114011         for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
114012         *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
114013         return i;
114014       }
114015       *tokenType = TK_MINUS;
114016       return 1;
114017     }
114018     case '(': {
114019       *tokenType = TK_LP;
114020       return 1;
114021     }
114022     case ')': {
114023       *tokenType = TK_RP;
114024       return 1;
114025     }
114026     case ';': {
114027       *tokenType = TK_SEMI;
114028       return 1;
114029     }
114030     case '+': {
114031       *tokenType = TK_PLUS;
114032       return 1;
114033     }
114034     case '*': {
114035       *tokenType = TK_STAR;
114036       return 1;
114037     }
114038     case '/': {
114039       if( z[1]!='*' || z[2]==0 ){
114040         *tokenType = TK_SLASH;
114041         return 1;
114042       }
114043       /* IMP: R-50417-27976 -- syntax diagram for comments */
114044       for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
114045       if( c ) i++;
114046       *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
114047       return i;
114048     }
114049     case '%': {
114050       *tokenType = TK_REM;
114051       return 1;
114052     }
114053     case '=': {
114054       *tokenType = TK_EQ;
114055       return 1 + (z[1]=='=');
114056     }
114057     case '<': {
114058       if( (c=z[1])=='=' ){
114059         *tokenType = TK_LE;
114060         return 2;
114061       }else if( c=='>' ){
114062         *tokenType = TK_NE;
114063         return 2;
114064       }else if( c=='<' ){
114065         *tokenType = TK_LSHIFT;
114066         return 2;
114067       }else{
114068         *tokenType = TK_LT;
114069         return 1;
114070       }
114071     }
114072     case '>': {
114073       if( (c=z[1])=='=' ){
114074         *tokenType = TK_GE;
114075         return 2;
114076       }else if( c=='>' ){
114077         *tokenType = TK_RSHIFT;
114078         return 2;
114079       }else{
114080         *tokenType = TK_GT;
114081         return 1;
114082       }
114083     }
114084     case '!': {
114085       if( z[1]!='=' ){
114086         *tokenType = TK_ILLEGAL;
114087         return 2;
114088       }else{
114089         *tokenType = TK_NE;
114090         return 2;
114091       }
114092     }
114093     case '|': {
114094       if( z[1]!='|' ){
114095         *tokenType = TK_BITOR;
114096         return 1;
114097       }else{
114098         *tokenType = TK_CONCAT;
114099         return 2;
114100       }
114101     }
114102     case ',': {
114103       *tokenType = TK_COMMA;
114104       return 1;
114105     }
114106     case '&': {
114107       *tokenType = TK_BITAND;
114108       return 1;
114109     }
114110     case '~': {
114111       *tokenType = TK_BITNOT;
114112       return 1;
114113     }
114114     case '`':
114115     case '\'':
114116     case '"': {
114117       int delim = z[0];
114118       testcase( delim=='`' );
114119       testcase( delim=='\'' );
114120       testcase( delim=='"' );
114121       for(i=1; (c=z[i])!=0; i++){
114122         if( c==delim ){
114123           if( z[i+1]==delim ){
114124             i++;
114125           }else{
114126             break;
114127           }
114128         }
114129       }
114130       if( c=='\'' ){
114131         *tokenType = TK_STRING;
114132         return i+1;
114133       }else if( c!=0 ){
114134         *tokenType = TK_ID;
114135         return i+1;
114136       }else{
114137         *tokenType = TK_ILLEGAL;
114138         return i;
114139       }
114140     }
114141     case '.': {
114142 #ifndef SQLITE_OMIT_FLOATING_POINT
114143       if( !sqlite3Isdigit(z[1]) )
114144 #endif
114145       {
114146         *tokenType = TK_DOT;
114147         return 1;
114148       }
114149       /* If the next character is a digit, this is a floating point
114150       ** number that begins with ".".  Fall thru into the next case */
114151     }
114152     case '0': case '1': case '2': case '3': case '4':
114153     case '5': case '6': case '7': case '8': case '9': {
114154       testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
114155       testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
114156       testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
114157       testcase( z[0]=='9' );
114158       *tokenType = TK_INTEGER;
114159       for(i=0; sqlite3Isdigit(z[i]); i++){}
114160 #ifndef SQLITE_OMIT_FLOATING_POINT
114161       if( z[i]=='.' ){
114162         i++;
114163         while( sqlite3Isdigit(z[i]) ){ i++; }
114164         *tokenType = TK_FLOAT;
114165       }
114166       if( (z[i]=='e' || z[i]=='E') &&
114167            ( sqlite3Isdigit(z[i+1]) 
114168             || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
114169            )
114170       ){
114171         i += 2;
114172         while( sqlite3Isdigit(z[i]) ){ i++; }
114173         *tokenType = TK_FLOAT;
114174       }
114175 #endif
114176       while( IdChar(z[i]) ){
114177         *tokenType = TK_ILLEGAL;
114178         i++;
114179       }
114180       return i;
114181     }
114182     case '[': {
114183       for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
114184       *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
114185       return i;
114186     }
114187     case '?': {
114188       *tokenType = TK_VARIABLE;
114189       for(i=1; sqlite3Isdigit(z[i]); i++){}
114190       return i;
114191     }
114192     case '#': {
114193       for(i=1; sqlite3Isdigit(z[i]); i++){}
114194       if( i>1 ){
114195         /* Parameters of the form #NNN (where NNN is a number) are used
114196         ** internally by sqlite3NestedParse.  */
114197         *tokenType = TK_REGISTER;
114198         return i;
114199       }
114200       /* Fall through into the next case if the '#' is not followed by
114201       ** a digit. Try to match #AAAA where AAAA is a parameter name. */
114202     }
114203 #ifndef SQLITE_OMIT_TCL_VARIABLE
114204     case '$':
114205 #endif
114206     case '@':  /* For compatibility with MS SQL Server */
114207     case ':': {
114208       int n = 0;
114209       testcase( z[0]=='$' );  testcase( z[0]=='@' );  testcase( z[0]==':' );
114210       *tokenType = TK_VARIABLE;
114211       for(i=1; (c=z[i])!=0; i++){
114212         if( IdChar(c) ){
114213           n++;
114214 #ifndef SQLITE_OMIT_TCL_VARIABLE
114215         }else if( c=='(' && n>0 ){
114216           do{
114217             i++;
114218           }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
114219           if( c==')' ){
114220             i++;
114221           }else{
114222             *tokenType = TK_ILLEGAL;
114223           }
114224           break;
114225         }else if( c==':' && z[i+1]==':' ){
114226           i++;
114227 #endif
114228         }else{
114229           break;
114230         }
114231       }
114232       if( n==0 ) *tokenType = TK_ILLEGAL;
114233       return i;
114234     }
114235 #ifndef SQLITE_OMIT_BLOB_LITERAL
114236     case 'x': case 'X': {
114237       testcase( z[0]=='x' ); testcase( z[0]=='X' );
114238       if( z[1]=='\'' ){
114239         *tokenType = TK_BLOB;
114240         for(i=2; sqlite3Isxdigit(z[i]); i++){}
114241         if( z[i]!='\'' || i%2 ){
114242           *tokenType = TK_ILLEGAL;
114243           while( z[i] && z[i]!='\'' ){ i++; }
114244         }
114245         if( z[i] ) i++;
114246         return i;
114247       }
114248       /* Otherwise fall through to the next case */
114249     }
114250 #endif
114251     default: {
114252       if( !IdChar(*z) ){
114253         break;
114254       }
114255       for(i=1; IdChar(z[i]); i++){}
114256       *tokenType = keywordCode((char*)z, i);
114257       return i;
114258     }
114259   }
114260   *tokenType = TK_ILLEGAL;
114261   return 1;
114262 }
114263
114264 /*
114265 ** Run the parser on the given SQL string.  The parser structure is
114266 ** passed in.  An SQLITE_ status code is returned.  If an error occurs
114267 ** then an and attempt is made to write an error message into 
114268 ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
114269 ** error message.
114270 */
114271 SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
114272   int nErr = 0;                   /* Number of errors encountered */
114273   int i;                          /* Loop counter */
114274   void *pEngine;                  /* The LEMON-generated LALR(1) parser */
114275   int tokenType;                  /* type of the next token */
114276   int lastTokenParsed = -1;       /* type of the previous token */
114277   u8 enableLookaside;             /* Saved value of db->lookaside.bEnabled */
114278   sqlite3 *db = pParse->db;       /* The database connection */
114279   int mxSqlLen;                   /* Max length of an SQL string */
114280
114281
114282   mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
114283   if( db->activeVdbeCnt==0 ){
114284     db->u1.isInterrupted = 0;
114285   }
114286   pParse->rc = SQLITE_OK;
114287   pParse->zTail = zSql;
114288   i = 0;
114289   assert( pzErrMsg!=0 );
114290   pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
114291   if( pEngine==0 ){
114292     db->mallocFailed = 1;
114293     return SQLITE_NOMEM;
114294   }
114295   assert( pParse->pNewTable==0 );
114296   assert( pParse->pNewTrigger==0 );
114297   assert( pParse->nVar==0 );
114298   assert( pParse->nzVar==0 );
114299   assert( pParse->azVar==0 );
114300   enableLookaside = db->lookaside.bEnabled;
114301   if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
114302   while( !db->mallocFailed && zSql[i]!=0 ){
114303     assert( i>=0 );
114304     pParse->sLastToken.z = &zSql[i];
114305     pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
114306     i += pParse->sLastToken.n;
114307     if( i>mxSqlLen ){
114308       pParse->rc = SQLITE_TOOBIG;
114309       break;
114310     }
114311     switch( tokenType ){
114312       case TK_SPACE: {
114313         if( db->u1.isInterrupted ){
114314           sqlite3ErrorMsg(pParse, "interrupt");
114315           pParse->rc = SQLITE_INTERRUPT;
114316           goto abort_parse;
114317         }
114318         break;
114319       }
114320       case TK_ILLEGAL: {
114321         sqlite3DbFree(db, *pzErrMsg);
114322         *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
114323                         &pParse->sLastToken);
114324         nErr++;
114325         goto abort_parse;
114326       }
114327       case TK_SEMI: {
114328         pParse->zTail = &zSql[i];
114329         /* Fall thru into the default case */
114330       }
114331       default: {
114332         sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
114333         lastTokenParsed = tokenType;
114334         if( pParse->rc!=SQLITE_OK ){
114335           goto abort_parse;
114336         }
114337         break;
114338       }
114339     }
114340   }
114341 abort_parse:
114342   if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
114343     if( lastTokenParsed!=TK_SEMI ){
114344       sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
114345       pParse->zTail = &zSql[i];
114346     }
114347     sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
114348   }
114349 #ifdef YYTRACKMAXSTACKDEPTH
114350   sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
114351       sqlite3ParserStackPeak(pEngine)
114352   );
114353 #endif /* YYDEBUG */
114354   sqlite3ParserFree(pEngine, sqlite3_free);
114355   db->lookaside.bEnabled = enableLookaside;
114356   if( db->mallocFailed ){
114357     pParse->rc = SQLITE_NOMEM;
114358   }
114359   if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
114360     sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
114361   }
114362   assert( pzErrMsg!=0 );
114363   if( pParse->zErrMsg ){
114364     *pzErrMsg = pParse->zErrMsg;
114365     sqlite3_log(pParse->rc, "%s", *pzErrMsg);
114366     pParse->zErrMsg = 0;
114367     nErr++;
114368   }
114369   if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
114370     sqlite3VdbeDelete(pParse->pVdbe);
114371     pParse->pVdbe = 0;
114372   }
114373 #ifndef SQLITE_OMIT_SHARED_CACHE
114374   if( pParse->nested==0 ){
114375     sqlite3DbFree(db, pParse->aTableLock);
114376     pParse->aTableLock = 0;
114377     pParse->nTableLock = 0;
114378   }
114379 #endif
114380 #ifndef SQLITE_OMIT_VIRTUALTABLE
114381   sqlite3_free(pParse->apVtabLock);
114382 #endif
114383
114384   if( !IN_DECLARE_VTAB ){
114385     /* If the pParse->declareVtab flag is set, do not delete any table 
114386     ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
114387     ** will take responsibility for freeing the Table structure.
114388     */
114389     sqlite3DeleteTable(db, pParse->pNewTable);
114390   }
114391
114392   sqlite3DeleteTrigger(db, pParse->pNewTrigger);
114393   for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);
114394   sqlite3DbFree(db, pParse->azVar);
114395   sqlite3DbFree(db, pParse->aAlias);
114396   while( pParse->pAinc ){
114397     AutoincInfo *p = pParse->pAinc;
114398     pParse->pAinc = p->pNext;
114399     sqlite3DbFree(db, p);
114400   }
114401   while( pParse->pZombieTab ){
114402     Table *p = pParse->pZombieTab;
114403     pParse->pZombieTab = p->pNextZombie;
114404     sqlite3DeleteTable(db, p);
114405   }
114406   if( nErr>0 && pParse->rc==SQLITE_OK ){
114407     pParse->rc = SQLITE_ERROR;
114408   }
114409   return nErr;
114410 }
114411
114412 /************** End of tokenize.c ********************************************/
114413 /************** Begin file complete.c ****************************************/
114414 /*
114415 ** 2001 September 15
114416 **
114417 ** The author disclaims copyright to this source code.  In place of
114418 ** a legal notice, here is a blessing:
114419 **
114420 **    May you do good and not evil.
114421 **    May you find forgiveness for yourself and forgive others.
114422 **    May you share freely, never taking more than you give.
114423 **
114424 *************************************************************************
114425 ** An tokenizer for SQL
114426 **
114427 ** This file contains C code that implements the sqlite3_complete() API.
114428 ** This code used to be part of the tokenizer.c source file.  But by
114429 ** separating it out, the code will be automatically omitted from
114430 ** static links that do not use it.
114431 */
114432 #ifndef SQLITE_OMIT_COMPLETE
114433
114434 /*
114435 ** This is defined in tokenize.c.  We just have to import the definition.
114436 */
114437 #ifndef SQLITE_AMALGAMATION
114438 #ifdef SQLITE_ASCII
114439 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
114440 #endif
114441 #ifdef SQLITE_EBCDIC
114442 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
114443 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
114444 #endif
114445 #endif /* SQLITE_AMALGAMATION */
114446
114447
114448 /*
114449 ** Token types used by the sqlite3_complete() routine.  See the header
114450 ** comments on that procedure for additional information.
114451 */
114452 #define tkSEMI    0
114453 #define tkWS      1
114454 #define tkOTHER   2
114455 #ifndef SQLITE_OMIT_TRIGGER
114456 #define tkEXPLAIN 3
114457 #define tkCREATE  4
114458 #define tkTEMP    5
114459 #define tkTRIGGER 6
114460 #define tkEND     7
114461 #endif
114462
114463 /*
114464 ** Return TRUE if the given SQL string ends in a semicolon.
114465 **
114466 ** Special handling is require for CREATE TRIGGER statements.
114467 ** Whenever the CREATE TRIGGER keywords are seen, the statement
114468 ** must end with ";END;".
114469 **
114470 ** This implementation uses a state machine with 8 states:
114471 **
114472 **   (0) INVALID   We have not yet seen a non-whitespace character.
114473 **
114474 **   (1) START     At the beginning or end of an SQL statement.  This routine
114475 **                 returns 1 if it ends in the START state and 0 if it ends
114476 **                 in any other state.
114477 **
114478 **   (2) NORMAL    We are in the middle of statement which ends with a single
114479 **                 semicolon.
114480 **
114481 **   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of 
114482 **                 a statement.
114483 **
114484 **   (4) CREATE    The keyword CREATE has been seen at the beginning of a
114485 **                 statement, possibly preceeded by EXPLAIN and/or followed by
114486 **                 TEMP or TEMPORARY
114487 **
114488 **   (5) TRIGGER   We are in the middle of a trigger definition that must be
114489 **                 ended by a semicolon, the keyword END, and another semicolon.
114490 **
114491 **   (6) SEMI      We've seen the first semicolon in the ";END;" that occurs at
114492 **                 the end of a trigger definition.
114493 **
114494 **   (7) END       We've seen the ";END" of the ";END;" that occurs at the end
114495 **                 of a trigger difinition.
114496 **
114497 ** Transitions between states above are determined by tokens extracted
114498 ** from the input.  The following tokens are significant:
114499 **
114500 **   (0) tkSEMI      A semicolon.
114501 **   (1) tkWS        Whitespace.
114502 **   (2) tkOTHER     Any other SQL token.
114503 **   (3) tkEXPLAIN   The "explain" keyword.
114504 **   (4) tkCREATE    The "create" keyword.
114505 **   (5) tkTEMP      The "temp" or "temporary" keyword.
114506 **   (6) tkTRIGGER   The "trigger" keyword.
114507 **   (7) tkEND       The "end" keyword.
114508 **
114509 ** Whitespace never causes a state transition and is always ignored.
114510 ** This means that a SQL string of all whitespace is invalid.
114511 **
114512 ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
114513 ** to recognize the end of a trigger can be omitted.  All we have to do
114514 ** is look for a semicolon that is not part of an string or comment.
114515 */
114516 SQLITE_API int sqlite3_complete(const char *zSql){
114517   u8 state = 0;   /* Current state, using numbers defined in header comment */
114518   u8 token;       /* Value of the next token */
114519
114520 #ifndef SQLITE_OMIT_TRIGGER
114521   /* A complex statement machine used to detect the end of a CREATE TRIGGER
114522   ** statement.  This is the normal case.
114523   */
114524   static const u8 trans[8][8] = {
114525                      /* Token:                                                */
114526      /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */
114527      /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },
114528      /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },
114529      /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },
114530      /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },
114531      /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },
114532      /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },
114533      /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },
114534      /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },
114535   };
114536 #else
114537   /* If triggers are not supported by this compile then the statement machine
114538   ** used to detect the end of a statement is much simplier
114539   */
114540   static const u8 trans[3][3] = {
114541                      /* Token:           */
114542      /* State:       **  SEMI  WS  OTHER */
114543      /* 0 INVALID: */ {    1,  0,     2, },
114544      /* 1   START: */ {    1,  1,     2, },
114545      /* 2  NORMAL: */ {    1,  2,     2, },
114546   };
114547 #endif /* SQLITE_OMIT_TRIGGER */
114548
114549   while( *zSql ){
114550     switch( *zSql ){
114551       case ';': {  /* A semicolon */
114552         token = tkSEMI;
114553         break;
114554       }
114555       case ' ':
114556       case '\r':
114557       case '\t':
114558       case '\n':
114559       case '\f': {  /* White space is ignored */
114560         token = tkWS;
114561         break;
114562       }
114563       case '/': {   /* C-style comments */
114564         if( zSql[1]!='*' ){
114565           token = tkOTHER;
114566           break;
114567         }
114568         zSql += 2;
114569         while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
114570         if( zSql[0]==0 ) return 0;
114571         zSql++;
114572         token = tkWS;
114573         break;
114574       }
114575       case '-': {   /* SQL-style comments from "--" to end of line */
114576         if( zSql[1]!='-' ){
114577           token = tkOTHER;
114578           break;
114579         }
114580         while( *zSql && *zSql!='\n' ){ zSql++; }
114581         if( *zSql==0 ) return state==1;
114582         token = tkWS;
114583         break;
114584       }
114585       case '[': {   /* Microsoft-style identifiers in [...] */
114586         zSql++;
114587         while( *zSql && *zSql!=']' ){ zSql++; }
114588         if( *zSql==0 ) return 0;
114589         token = tkOTHER;
114590         break;
114591       }
114592       case '`':     /* Grave-accent quoted symbols used by MySQL */
114593       case '"':     /* single- and double-quoted strings */
114594       case '\'': {
114595         int c = *zSql;
114596         zSql++;
114597         while( *zSql && *zSql!=c ){ zSql++; }
114598         if( *zSql==0 ) return 0;
114599         token = tkOTHER;
114600         break;
114601       }
114602       default: {
114603 #ifdef SQLITE_EBCDIC
114604         unsigned char c;
114605 #endif
114606         if( IdChar((u8)*zSql) ){
114607           /* Keywords and unquoted identifiers */
114608           int nId;
114609           for(nId=1; IdChar(zSql[nId]); nId++){}
114610 #ifdef SQLITE_OMIT_TRIGGER
114611           token = tkOTHER;
114612 #else
114613           switch( *zSql ){
114614             case 'c': case 'C': {
114615               if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
114616                 token = tkCREATE;
114617               }else{
114618                 token = tkOTHER;
114619               }
114620               break;
114621             }
114622             case 't': case 'T': {
114623               if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
114624                 token = tkTRIGGER;
114625               }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
114626                 token = tkTEMP;
114627               }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
114628                 token = tkTEMP;
114629               }else{
114630                 token = tkOTHER;
114631               }
114632               break;
114633             }
114634             case 'e':  case 'E': {
114635               if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
114636                 token = tkEND;
114637               }else
114638 #ifndef SQLITE_OMIT_EXPLAIN
114639               if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
114640                 token = tkEXPLAIN;
114641               }else
114642 #endif
114643               {
114644                 token = tkOTHER;
114645               }
114646               break;
114647             }
114648             default: {
114649               token = tkOTHER;
114650               break;
114651             }
114652           }
114653 #endif /* SQLITE_OMIT_TRIGGER */
114654           zSql += nId-1;
114655         }else{
114656           /* Operators and special symbols */
114657           token = tkOTHER;
114658         }
114659         break;
114660       }
114661     }
114662     state = trans[state][token];
114663     zSql++;
114664   }
114665   return state==1;
114666 }
114667
114668 #ifndef SQLITE_OMIT_UTF16
114669 /*
114670 ** This routine is the same as the sqlite3_complete() routine described
114671 ** above, except that the parameter is required to be UTF-16 encoded, not
114672 ** UTF-8.
114673 */
114674 SQLITE_API int sqlite3_complete16(const void *zSql){
114675   sqlite3_value *pVal;
114676   char const *zSql8;
114677   int rc = SQLITE_NOMEM;
114678
114679 #ifndef SQLITE_OMIT_AUTOINIT
114680   rc = sqlite3_initialize();
114681   if( rc ) return rc;
114682 #endif
114683   pVal = sqlite3ValueNew(0);
114684   sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
114685   zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
114686   if( zSql8 ){
114687     rc = sqlite3_complete(zSql8);
114688   }else{
114689     rc = SQLITE_NOMEM;
114690   }
114691   sqlite3ValueFree(pVal);
114692   return sqlite3ApiExit(0, rc);
114693 }
114694 #endif /* SQLITE_OMIT_UTF16 */
114695 #endif /* SQLITE_OMIT_COMPLETE */
114696
114697 /************** End of complete.c ********************************************/
114698 /************** Begin file main.c ********************************************/
114699 /*
114700 ** 2001 September 15
114701 **
114702 ** The author disclaims copyright to this source code.  In place of
114703 ** a legal notice, here is a blessing:
114704 **
114705 **    May you do good and not evil.
114706 **    May you find forgiveness for yourself and forgive others.
114707 **    May you share freely, never taking more than you give.
114708 **
114709 *************************************************************************
114710 ** Main file for the SQLite library.  The routines in this file
114711 ** implement the programmer interface to the library.  Routines in
114712 ** other files are for internal use by SQLite and should not be
114713 ** accessed by users of the library.
114714 */
114715
114716 #ifdef SQLITE_ENABLE_FTS3
114717 /************** Include fts3.h in the middle of main.c ***********************/
114718 /************** Begin file fts3.h ********************************************/
114719 /*
114720 ** 2006 Oct 10
114721 **
114722 ** The author disclaims copyright to this source code.  In place of
114723 ** a legal notice, here is a blessing:
114724 **
114725 **    May you do good and not evil.
114726 **    May you find forgiveness for yourself and forgive others.
114727 **    May you share freely, never taking more than you give.
114728 **
114729 ******************************************************************************
114730 **
114731 ** This header file is used by programs that want to link against the
114732 ** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
114733 */
114734
114735 #if 0
114736 extern "C" {
114737 #endif  /* __cplusplus */
114738
114739 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
114740
114741 #if 0
114742 }  /* extern "C" */
114743 #endif  /* __cplusplus */
114744
114745 /************** End of fts3.h ************************************************/
114746 /************** Continuing where we left off in main.c ***********************/
114747 #endif
114748 #ifdef SQLITE_ENABLE_RTREE
114749 /************** Include rtree.h in the middle of main.c **********************/
114750 /************** Begin file rtree.h *******************************************/
114751 /*
114752 ** 2008 May 26
114753 **
114754 ** The author disclaims copyright to this source code.  In place of
114755 ** a legal notice, here is a blessing:
114756 **
114757 **    May you do good and not evil.
114758 **    May you find forgiveness for yourself and forgive others.
114759 **    May you share freely, never taking more than you give.
114760 **
114761 ******************************************************************************
114762 **
114763 ** This header file is used by programs that want to link against the
114764 ** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
114765 */
114766
114767 #if 0
114768 extern "C" {
114769 #endif  /* __cplusplus */
114770
114771 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
114772
114773 #if 0
114774 }  /* extern "C" */
114775 #endif  /* __cplusplus */
114776
114777 /************** End of rtree.h ***********************************************/
114778 /************** Continuing where we left off in main.c ***********************/
114779 #endif
114780 #ifdef SQLITE_ENABLE_ICU
114781 /************** Include sqliteicu.h in the middle of main.c ******************/
114782 /************** Begin file sqliteicu.h ***************************************/
114783 /*
114784 ** 2008 May 26
114785 **
114786 ** The author disclaims copyright to this source code.  In place of
114787 ** a legal notice, here is a blessing:
114788 **
114789 **    May you do good and not evil.
114790 **    May you find forgiveness for yourself and forgive others.
114791 **    May you share freely, never taking more than you give.
114792 **
114793 ******************************************************************************
114794 **
114795 ** This header file is used by programs that want to link against the
114796 ** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
114797 */
114798
114799 #if 0
114800 extern "C" {
114801 #endif  /* __cplusplus */
114802
114803 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
114804
114805 #if 0
114806 }  /* extern "C" */
114807 #endif  /* __cplusplus */
114808
114809
114810 /************** End of sqliteicu.h *******************************************/
114811 /************** Continuing where we left off in main.c ***********************/
114812 #endif
114813
114814 #ifndef SQLITE_AMALGAMATION
114815 /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
114816 ** contains the text of SQLITE_VERSION macro. 
114817 */
114818 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
114819 #endif
114820
114821 /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
114822 ** a pointer to the to the sqlite3_version[] string constant. 
114823 */
114824 SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
114825
114826 /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
114827 ** pointer to a string constant whose value is the same as the
114828 ** SQLITE_SOURCE_ID C preprocessor macro. 
114829 */
114830 SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
114831
114832 /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
114833 ** returns an integer equal to SQLITE_VERSION_NUMBER.
114834 */
114835 SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
114836
114837 /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
114838 ** zero if and only if SQLite was compiled with mutexing code omitted due to
114839 ** the SQLITE_THREADSAFE compile-time option being set to 0.
114840 */
114841 SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
114842
114843 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
114844 /*
114845 ** If the following function pointer is not NULL and if
114846 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
114847 ** I/O active are written using this function.  These messages
114848 ** are intended for debugging activity only.
114849 */
114850 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
114851 #endif
114852
114853 /*
114854 ** If the following global variable points to a string which is the
114855 ** name of a directory, then that directory will be used to store
114856 ** temporary files.
114857 **
114858 ** See also the "PRAGMA temp_store_directory" SQL command.
114859 */
114860 SQLITE_API char *sqlite3_temp_directory = 0;
114861
114862 /*
114863 ** If the following global variable points to a string which is the
114864 ** name of a directory, then that directory will be used to store
114865 ** all database files specified with a relative pathname.
114866 **
114867 ** See also the "PRAGMA data_store_directory" SQL command.
114868 */
114869 SQLITE_API char *sqlite3_data_directory = 0;
114870
114871 /*
114872 ** Initialize SQLite.  
114873 **
114874 ** This routine must be called to initialize the memory allocation,
114875 ** VFS, and mutex subsystems prior to doing any serious work with
114876 ** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
114877 ** this routine will be called automatically by key routines such as
114878 ** sqlite3_open().  
114879 **
114880 ** This routine is a no-op except on its very first call for the process,
114881 ** or for the first call after a call to sqlite3_shutdown.
114882 **
114883 ** The first thread to call this routine runs the initialization to
114884 ** completion.  If subsequent threads call this routine before the first
114885 ** thread has finished the initialization process, then the subsequent
114886 ** threads must block until the first thread finishes with the initialization.
114887 **
114888 ** The first thread might call this routine recursively.  Recursive
114889 ** calls to this routine should not block, of course.  Otherwise the
114890 ** initialization process would never complete.
114891 **
114892 ** Let X be the first thread to enter this routine.  Let Y be some other
114893 ** thread.  Then while the initial invocation of this routine by X is
114894 ** incomplete, it is required that:
114895 **
114896 **    *  Calls to this routine from Y must block until the outer-most
114897 **       call by X completes.
114898 **
114899 **    *  Recursive calls to this routine from thread X return immediately
114900 **       without blocking.
114901 */
114902 SQLITE_API int sqlite3_initialize(void){
114903   MUTEX_LOGIC( sqlite3_mutex *pMaster; )       /* The main static mutex */
114904   int rc;                                      /* Result code */
114905
114906 #ifdef SQLITE_OMIT_WSD
114907   rc = sqlite3_wsd_init(4096, 24);
114908   if( rc!=SQLITE_OK ){
114909     return rc;
114910   }
114911 #endif
114912
114913   /* If SQLite is already completely initialized, then this call
114914   ** to sqlite3_initialize() should be a no-op.  But the initialization
114915   ** must be complete.  So isInit must not be set until the very end
114916   ** of this routine.
114917   */
114918   if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
114919
114920 #ifdef SQLITE_ENABLE_SQLLOG
114921   {
114922     extern void sqlite3_init_sqllog(void);
114923     sqlite3_init_sqllog();
114924   }
114925 #endif
114926
114927   /* Make sure the mutex subsystem is initialized.  If unable to 
114928   ** initialize the mutex subsystem, return early with the error.
114929   ** If the system is so sick that we are unable to allocate a mutex,
114930   ** there is not much SQLite is going to be able to do.
114931   **
114932   ** The mutex subsystem must take care of serializing its own
114933   ** initialization.
114934   */
114935   rc = sqlite3MutexInit();
114936   if( rc ) return rc;
114937
114938   /* Initialize the malloc() system and the recursive pInitMutex mutex.
114939   ** This operation is protected by the STATIC_MASTER mutex.  Note that
114940   ** MutexAlloc() is called for a static mutex prior to initializing the
114941   ** malloc subsystem - this implies that the allocation of a static
114942   ** mutex must not require support from the malloc subsystem.
114943   */
114944   MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
114945   sqlite3_mutex_enter(pMaster);
114946   sqlite3GlobalConfig.isMutexInit = 1;
114947   if( !sqlite3GlobalConfig.isMallocInit ){
114948     rc = sqlite3MallocInit();
114949   }
114950   if( rc==SQLITE_OK ){
114951     sqlite3GlobalConfig.isMallocInit = 1;
114952     if( !sqlite3GlobalConfig.pInitMutex ){
114953       sqlite3GlobalConfig.pInitMutex =
114954            sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
114955       if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
114956         rc = SQLITE_NOMEM;
114957       }
114958     }
114959   }
114960   if( rc==SQLITE_OK ){
114961     sqlite3GlobalConfig.nRefInitMutex++;
114962   }
114963   sqlite3_mutex_leave(pMaster);
114964
114965   /* If rc is not SQLITE_OK at this point, then either the malloc
114966   ** subsystem could not be initialized or the system failed to allocate
114967   ** the pInitMutex mutex. Return an error in either case.  */
114968   if( rc!=SQLITE_OK ){
114969     return rc;
114970   }
114971
114972   /* Do the rest of the initialization under the recursive mutex so
114973   ** that we will be able to handle recursive calls into
114974   ** sqlite3_initialize().  The recursive calls normally come through
114975   ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
114976   ** recursive calls might also be possible.
114977   **
114978   ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
114979   ** to the xInit method, so the xInit method need not be threadsafe.
114980   **
114981   ** The following mutex is what serializes access to the appdef pcache xInit
114982   ** methods.  The sqlite3_pcache_methods.xInit() all is embedded in the
114983   ** call to sqlite3PcacheInitialize().
114984   */
114985   sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
114986   if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
114987     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
114988     sqlite3GlobalConfig.inProgress = 1;
114989     memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
114990     sqlite3RegisterGlobalFunctions();
114991     if( sqlite3GlobalConfig.isPCacheInit==0 ){
114992       rc = sqlite3PcacheInitialize();
114993     }
114994     if( rc==SQLITE_OK ){
114995       sqlite3GlobalConfig.isPCacheInit = 1;
114996       rc = sqlite3OsInit();
114997     }
114998     if( rc==SQLITE_OK ){
114999       sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage, 
115000           sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
115001       sqlite3GlobalConfig.isInit = 1;
115002     }
115003     sqlite3GlobalConfig.inProgress = 0;
115004   }
115005   sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
115006
115007   /* Go back under the static mutex and clean up the recursive
115008   ** mutex to prevent a resource leak.
115009   */
115010   sqlite3_mutex_enter(pMaster);
115011   sqlite3GlobalConfig.nRefInitMutex--;
115012   if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
115013     assert( sqlite3GlobalConfig.nRefInitMutex==0 );
115014     sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
115015     sqlite3GlobalConfig.pInitMutex = 0;
115016   }
115017   sqlite3_mutex_leave(pMaster);
115018
115019   /* The following is just a sanity check to make sure SQLite has
115020   ** been compiled correctly.  It is important to run this code, but
115021   ** we don't want to run it too often and soak up CPU cycles for no
115022   ** reason.  So we run it once during initialization.
115023   */
115024 #ifndef NDEBUG
115025 #ifndef SQLITE_OMIT_FLOATING_POINT
115026   /* This section of code's only "output" is via assert() statements. */
115027   if ( rc==SQLITE_OK ){
115028     u64 x = (((u64)1)<<63)-1;
115029     double y;
115030     assert(sizeof(x)==8);
115031     assert(sizeof(x)==sizeof(y));
115032     memcpy(&y, &x, 8);
115033     assert( sqlite3IsNaN(y) );
115034   }
115035 #endif
115036 #endif
115037
115038   /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
115039   ** compile-time option.
115040   */
115041 #ifdef SQLITE_EXTRA_INIT
115042   if( rc==SQLITE_OK && sqlite3GlobalConfig.isInit ){
115043     int SQLITE_EXTRA_INIT(const char*);
115044     rc = SQLITE_EXTRA_INIT(0);
115045   }
115046 #endif
115047
115048   return rc;
115049 }
115050
115051 /*
115052 ** Undo the effects of sqlite3_initialize().  Must not be called while
115053 ** there are outstanding database connections or memory allocations or
115054 ** while any part of SQLite is otherwise in use in any thread.  This
115055 ** routine is not threadsafe.  But it is safe to invoke this routine
115056 ** on when SQLite is already shut down.  If SQLite is already shut down
115057 ** when this routine is invoked, then this routine is a harmless no-op.
115058 */
115059 SQLITE_API int sqlite3_shutdown(void){
115060   if( sqlite3GlobalConfig.isInit ){
115061 #ifdef SQLITE_EXTRA_SHUTDOWN
115062     void SQLITE_EXTRA_SHUTDOWN(void);
115063     SQLITE_EXTRA_SHUTDOWN();
115064 #endif
115065     sqlite3_os_end();
115066     sqlite3_reset_auto_extension();
115067     sqlite3GlobalConfig.isInit = 0;
115068   }
115069   if( sqlite3GlobalConfig.isPCacheInit ){
115070     sqlite3PcacheShutdown();
115071     sqlite3GlobalConfig.isPCacheInit = 0;
115072   }
115073   if( sqlite3GlobalConfig.isMallocInit ){
115074     sqlite3MallocEnd();
115075     sqlite3GlobalConfig.isMallocInit = 0;
115076
115077 #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
115078     /* The heap subsystem has now been shutdown and these values are supposed
115079     ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
115080     ** which would rely on that heap subsystem; therefore, make sure these
115081     ** values cannot refer to heap memory that was just invalidated when the
115082     ** heap subsystem was shutdown.  This is only done if the current call to
115083     ** this function resulted in the heap subsystem actually being shutdown.
115084     */
115085     sqlite3_data_directory = 0;
115086     sqlite3_temp_directory = 0;
115087 #endif
115088   }
115089   if( sqlite3GlobalConfig.isMutexInit ){
115090     sqlite3MutexEnd();
115091     sqlite3GlobalConfig.isMutexInit = 0;
115092   }
115093
115094   return SQLITE_OK;
115095 }
115096
115097 /*
115098 ** This API allows applications to modify the global configuration of
115099 ** the SQLite library at run-time.
115100 **
115101 ** This routine should only be called when there are no outstanding
115102 ** database connections or memory allocations.  This routine is not
115103 ** threadsafe.  Failure to heed these warnings can lead to unpredictable
115104 ** behavior.
115105 */
115106 SQLITE_API int sqlite3_config(int op, ...){
115107   va_list ap;
115108   int rc = SQLITE_OK;
115109
115110   /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
115111   ** the SQLite library is in use. */
115112   if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
115113
115114   va_start(ap, op);
115115   switch( op ){
115116
115117     /* Mutex configuration options are only available in a threadsafe
115118     ** compile. 
115119     */
115120 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
115121     case SQLITE_CONFIG_SINGLETHREAD: {
115122       /* Disable all mutexing */
115123       sqlite3GlobalConfig.bCoreMutex = 0;
115124       sqlite3GlobalConfig.bFullMutex = 0;
115125       break;
115126     }
115127     case SQLITE_CONFIG_MULTITHREAD: {
115128       /* Disable mutexing of database connections */
115129       /* Enable mutexing of core data structures */
115130       sqlite3GlobalConfig.bCoreMutex = 1;
115131       sqlite3GlobalConfig.bFullMutex = 0;
115132       break;
115133     }
115134     case SQLITE_CONFIG_SERIALIZED: {
115135       /* Enable all mutexing */
115136       sqlite3GlobalConfig.bCoreMutex = 1;
115137       sqlite3GlobalConfig.bFullMutex = 1;
115138       break;
115139     }
115140     case SQLITE_CONFIG_MUTEX: {
115141       /* Specify an alternative mutex implementation */
115142       sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
115143       break;
115144     }
115145     case SQLITE_CONFIG_GETMUTEX: {
115146       /* Retrieve the current mutex implementation */
115147       *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
115148       break;
115149     }
115150 #endif
115151
115152
115153     case SQLITE_CONFIG_MALLOC: {
115154       /* Specify an alternative malloc implementation */
115155       sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
115156       break;
115157     }
115158     case SQLITE_CONFIG_GETMALLOC: {
115159       /* Retrieve the current malloc() implementation */
115160       if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
115161       *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
115162       break;
115163     }
115164     case SQLITE_CONFIG_MEMSTATUS: {
115165       /* Enable or disable the malloc status collection */
115166       sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
115167       break;
115168     }
115169     case SQLITE_CONFIG_SCRATCH: {
115170       /* Designate a buffer for scratch memory space */
115171       sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
115172       sqlite3GlobalConfig.szScratch = va_arg(ap, int);
115173       sqlite3GlobalConfig.nScratch = va_arg(ap, int);
115174       break;
115175     }
115176     case SQLITE_CONFIG_PAGECACHE: {
115177       /* Designate a buffer for page cache memory space */
115178       sqlite3GlobalConfig.pPage = va_arg(ap, void*);
115179       sqlite3GlobalConfig.szPage = va_arg(ap, int);
115180       sqlite3GlobalConfig.nPage = va_arg(ap, int);
115181       break;
115182     }
115183
115184     case SQLITE_CONFIG_PCACHE: {
115185       /* no-op */
115186       break;
115187     }
115188     case SQLITE_CONFIG_GETPCACHE: {
115189       /* now an error */
115190       rc = SQLITE_ERROR;
115191       break;
115192     }
115193
115194     case SQLITE_CONFIG_PCACHE2: {
115195       /* Specify an alternative page cache implementation */
115196       sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
115197       break;
115198     }
115199     case SQLITE_CONFIG_GETPCACHE2: {
115200       if( sqlite3GlobalConfig.pcache2.xInit==0 ){
115201         sqlite3PCacheSetDefault();
115202       }
115203       *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
115204       break;
115205     }
115206
115207 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
115208     case SQLITE_CONFIG_HEAP: {
115209       /* Designate a buffer for heap memory space */
115210       sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
115211       sqlite3GlobalConfig.nHeap = va_arg(ap, int);
115212       sqlite3GlobalConfig.mnReq = va_arg(ap, int);
115213
115214       if( sqlite3GlobalConfig.mnReq<1 ){
115215         sqlite3GlobalConfig.mnReq = 1;
115216       }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
115217         /* cap min request size at 2^12 */
115218         sqlite3GlobalConfig.mnReq = (1<<12);
115219       }
115220
115221       if( sqlite3GlobalConfig.pHeap==0 ){
115222         /* If the heap pointer is NULL, then restore the malloc implementation
115223         ** back to NULL pointers too.  This will cause the malloc to go
115224         ** back to its default implementation when sqlite3_initialize() is
115225         ** run.
115226         */
115227         memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
115228       }else{
115229         /* The heap pointer is not NULL, then install one of the
115230         ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor
115231         ** ENABLE_MEMSYS5 is defined, return an error.
115232         */
115233 #ifdef SQLITE_ENABLE_MEMSYS3
115234         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
115235 #endif
115236 #ifdef SQLITE_ENABLE_MEMSYS5
115237         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
115238 #endif
115239       }
115240       break;
115241     }
115242 #endif
115243
115244     case SQLITE_CONFIG_LOOKASIDE: {
115245       sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
115246       sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
115247       break;
115248     }
115249     
115250     /* Record a pointer to the logger funcction and its first argument.
115251     ** The default is NULL.  Logging is disabled if the function pointer is
115252     ** NULL.
115253     */
115254     case SQLITE_CONFIG_LOG: {
115255       /* MSVC is picky about pulling func ptrs from va lists.
115256       ** http://support.microsoft.com/kb/47961
115257       ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
115258       */
115259       typedef void(*LOGFUNC_t)(void*,int,const char*);
115260       sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
115261       sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
115262       break;
115263     }
115264
115265     case SQLITE_CONFIG_URI: {
115266       sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
115267       break;
115268     }
115269
115270     case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
115271       sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
115272       break;
115273     }
115274
115275 #ifdef SQLITE_ENABLE_SQLLOG
115276     case SQLITE_CONFIG_SQLLOG: {
115277       typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
115278       sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
115279       sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
115280       break;
115281     }
115282 #endif
115283
115284     case SQLITE_CONFIG_MMAP_SIZE: {
115285       sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
115286       sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
115287       if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
115288         mxMmap = SQLITE_MAX_MMAP_SIZE;
115289       }
115290       sqlite3GlobalConfig.mxMmap = mxMmap;
115291       if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
115292       if( szMmap>mxMmap) szMmap = mxMmap;
115293       sqlite3GlobalConfig.szMmap = szMmap;
115294       break;
115295     }
115296
115297     default: {
115298       rc = SQLITE_ERROR;
115299       break;
115300     }
115301   }
115302   va_end(ap);
115303   return rc;
115304 }
115305
115306 /*
115307 ** Set up the lookaside buffers for a database connection.
115308 ** Return SQLITE_OK on success.  
115309 ** If lookaside is already active, return SQLITE_BUSY.
115310 **
115311 ** The sz parameter is the number of bytes in each lookaside slot.
115312 ** The cnt parameter is the number of slots.  If pStart is NULL the
115313 ** space for the lookaside memory is obtained from sqlite3_malloc().
115314 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
115315 ** the lookaside memory.
115316 */
115317 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
115318   void *pStart;
115319   if( db->lookaside.nOut ){
115320     return SQLITE_BUSY;
115321   }
115322   /* Free any existing lookaside buffer for this handle before
115323   ** allocating a new one so we don't have to have space for 
115324   ** both at the same time.
115325   */
115326   if( db->lookaside.bMalloced ){
115327     sqlite3_free(db->lookaside.pStart);
115328   }
115329   /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
115330   ** than a pointer to be useful.
115331   */
115332   sz = ROUNDDOWN8(sz);  /* IMP: R-33038-09382 */
115333   if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
115334   if( cnt<0 ) cnt = 0;
115335   if( sz==0 || cnt==0 ){
115336     sz = 0;
115337     pStart = 0;
115338   }else if( pBuf==0 ){
115339     sqlite3BeginBenignMalloc();
115340     pStart = sqlite3Malloc( sz*cnt );  /* IMP: R-61949-35727 */
115341     sqlite3EndBenignMalloc();
115342     if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
115343   }else{
115344     pStart = pBuf;
115345   }
115346   db->lookaside.pStart = pStart;
115347   db->lookaside.pFree = 0;
115348   db->lookaside.sz = (u16)sz;
115349   if( pStart ){
115350     int i;
115351     LookasideSlot *p;
115352     assert( sz > (int)sizeof(LookasideSlot*) );
115353     p = (LookasideSlot*)pStart;
115354     for(i=cnt-1; i>=0; i--){
115355       p->pNext = db->lookaside.pFree;
115356       db->lookaside.pFree = p;
115357       p = (LookasideSlot*)&((u8*)p)[sz];
115358     }
115359     db->lookaside.pEnd = p;
115360     db->lookaside.bEnabled = 1;
115361     db->lookaside.bMalloced = pBuf==0 ?1:0;
115362   }else{
115363     db->lookaside.pEnd = 0;
115364     db->lookaside.bEnabled = 0;
115365     db->lookaside.bMalloced = 0;
115366   }
115367   return SQLITE_OK;
115368 }
115369
115370 /*
115371 ** Return the mutex associated with a database connection.
115372 */
115373 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
115374   return db->mutex;
115375 }
115376
115377 /*
115378 ** Free up as much memory as we can from the given database
115379 ** connection.
115380 */
115381 SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){
115382   int i;
115383   sqlite3_mutex_enter(db->mutex);
115384   sqlite3BtreeEnterAll(db);
115385   for(i=0; i<db->nDb; i++){
115386     Btree *pBt = db->aDb[i].pBt;
115387     if( pBt ){
115388       Pager *pPager = sqlite3BtreePager(pBt);
115389       sqlite3PagerShrink(pPager);
115390     }
115391   }
115392   sqlite3BtreeLeaveAll(db);
115393   sqlite3_mutex_leave(db->mutex);
115394   return SQLITE_OK;
115395 }
115396
115397 /*
115398 ** Configuration settings for an individual database connection
115399 */
115400 SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
115401   va_list ap;
115402   int rc;
115403   va_start(ap, op);
115404   switch( op ){
115405     case SQLITE_DBCONFIG_LOOKASIDE: {
115406       void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
115407       int sz = va_arg(ap, int);       /* IMP: R-47871-25994 */
115408       int cnt = va_arg(ap, int);      /* IMP: R-04460-53386 */
115409       rc = setupLookaside(db, pBuf, sz, cnt);
115410       break;
115411     }
115412     default: {
115413       static const struct {
115414         int op;      /* The opcode */
115415         u32 mask;    /* Mask of the bit in sqlite3.flags to set/clear */
115416       } aFlagOp[] = {
115417         { SQLITE_DBCONFIG_ENABLE_FKEY,    SQLITE_ForeignKeys    },
115418         { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger  },
115419       };
115420       unsigned int i;
115421       rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
115422       for(i=0; i<ArraySize(aFlagOp); i++){
115423         if( aFlagOp[i].op==op ){
115424           int onoff = va_arg(ap, int);
115425           int *pRes = va_arg(ap, int*);
115426           int oldFlags = db->flags;
115427           if( onoff>0 ){
115428             db->flags |= aFlagOp[i].mask;
115429           }else if( onoff==0 ){
115430             db->flags &= ~aFlagOp[i].mask;
115431           }
115432           if( oldFlags!=db->flags ){
115433             sqlite3ExpirePreparedStatements(db);
115434           }
115435           if( pRes ){
115436             *pRes = (db->flags & aFlagOp[i].mask)!=0;
115437           }
115438           rc = SQLITE_OK;
115439           break;
115440         }
115441       }
115442       break;
115443     }
115444   }
115445   va_end(ap);
115446   return rc;
115447 }
115448
115449
115450 /*
115451 ** Return true if the buffer z[0..n-1] contains all spaces.
115452 */
115453 static int allSpaces(const char *z, int n){
115454   while( n>0 && z[n-1]==' ' ){ n--; }
115455   return n==0;
115456 }
115457
115458 /*
115459 ** This is the default collating function named "BINARY" which is always
115460 ** available.
115461 **
115462 ** If the padFlag argument is not NULL then space padding at the end
115463 ** of strings is ignored.  This implements the RTRIM collation.
115464 */
115465 static int binCollFunc(
115466   void *padFlag,
115467   int nKey1, const void *pKey1,
115468   int nKey2, const void *pKey2
115469 ){
115470   int rc, n;
115471   n = nKey1<nKey2 ? nKey1 : nKey2;
115472   rc = memcmp(pKey1, pKey2, n);
115473   if( rc==0 ){
115474     if( padFlag
115475      && allSpaces(((char*)pKey1)+n, nKey1-n)
115476      && allSpaces(((char*)pKey2)+n, nKey2-n)
115477     ){
115478       /* Leave rc unchanged at 0 */
115479     }else{
115480       rc = nKey1 - nKey2;
115481     }
115482   }
115483   return rc;
115484 }
115485
115486 /*
115487 ** Another built-in collating sequence: NOCASE. 
115488 **
115489 ** This collating sequence is intended to be used for "case independant
115490 ** comparison". SQLite's knowledge of upper and lower case equivalents
115491 ** extends only to the 26 characters used in the English language.
115492 **
115493 ** At the moment there is only a UTF-8 implementation.
115494 */
115495 static int nocaseCollatingFunc(
115496   void *NotUsed,
115497   int nKey1, const void *pKey1,
115498   int nKey2, const void *pKey2
115499 ){
115500   int r = sqlite3StrNICmp(
115501       (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
115502   UNUSED_PARAMETER(NotUsed);
115503   if( 0==r ){
115504     r = nKey1-nKey2;
115505   }
115506   return r;
115507 }
115508
115509 /*
115510 ** Return the ROWID of the most recent insert
115511 */
115512 SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
115513   return db->lastRowid;
115514 }
115515
115516 /*
115517 ** Return the number of changes in the most recent call to sqlite3_exec().
115518 */
115519 SQLITE_API int sqlite3_changes(sqlite3 *db){
115520   return db->nChange;
115521 }
115522
115523 /*
115524 ** Return the number of changes since the database handle was opened.
115525 */
115526 SQLITE_API int sqlite3_total_changes(sqlite3 *db){
115527   return db->nTotalChange;
115528 }
115529
115530 /*
115531 ** Close all open savepoints. This function only manipulates fields of the
115532 ** database handle object, it does not close any savepoints that may be open
115533 ** at the b-tree/pager level.
115534 */
115535 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
115536   while( db->pSavepoint ){
115537     Savepoint *pTmp = db->pSavepoint;
115538     db->pSavepoint = pTmp->pNext;
115539     sqlite3DbFree(db, pTmp);
115540   }
115541   db->nSavepoint = 0;
115542   db->nStatement = 0;
115543   db->isTransactionSavepoint = 0;
115544 }
115545
115546 /*
115547 ** Invoke the destructor function associated with FuncDef p, if any. Except,
115548 ** if this is not the last copy of the function, do not invoke it. Multiple
115549 ** copies of a single function are created when create_function() is called
115550 ** with SQLITE_ANY as the encoding.
115551 */
115552 static void functionDestroy(sqlite3 *db, FuncDef *p){
115553   FuncDestructor *pDestructor = p->pDestructor;
115554   if( pDestructor ){
115555     pDestructor->nRef--;
115556     if( pDestructor->nRef==0 ){
115557       pDestructor->xDestroy(pDestructor->pUserData);
115558       sqlite3DbFree(db, pDestructor);
115559     }
115560   }
115561 }
115562
115563 /*
115564 ** Disconnect all sqlite3_vtab objects that belong to database connection
115565 ** db. This is called when db is being closed.
115566 */
115567 static void disconnectAllVtab(sqlite3 *db){
115568 #ifndef SQLITE_OMIT_VIRTUALTABLE
115569   int i;
115570   sqlite3BtreeEnterAll(db);
115571   for(i=0; i<db->nDb; i++){
115572     Schema *pSchema = db->aDb[i].pSchema;
115573     if( db->aDb[i].pSchema ){
115574       HashElem *p;
115575       for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
115576         Table *pTab = (Table *)sqliteHashData(p);
115577         if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
115578       }
115579     }
115580   }
115581   sqlite3BtreeLeaveAll(db);
115582 #else
115583   UNUSED_PARAMETER(db);
115584 #endif
115585 }
115586
115587 /*
115588 ** Return TRUE if database connection db has unfinalized prepared
115589 ** statements or unfinished sqlite3_backup objects.  
115590 */
115591 static int connectionIsBusy(sqlite3 *db){
115592   int j;
115593   assert( sqlite3_mutex_held(db->mutex) );
115594   if( db->pVdbe ) return 1;
115595   for(j=0; j<db->nDb; j++){
115596     Btree *pBt = db->aDb[j].pBt;
115597     if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
115598   }
115599   return 0;
115600 }
115601
115602 /*
115603 ** Close an existing SQLite database
115604 */
115605 static int sqlite3Close(sqlite3 *db, int forceZombie){
115606   if( !db ){
115607     return SQLITE_OK;
115608   }
115609   if( !sqlite3SafetyCheckSickOrOk(db) ){
115610     return SQLITE_MISUSE_BKPT;
115611   }
115612   sqlite3_mutex_enter(db->mutex);
115613
115614   /* Force xDisconnect calls on all virtual tables */
115615   disconnectAllVtab(db);
115616
115617   /* If a transaction is open, the disconnectAllVtab() call above
115618   ** will not have called the xDisconnect() method on any virtual
115619   ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
115620   ** call will do so. We need to do this before the check for active
115621   ** SQL statements below, as the v-table implementation may be storing
115622   ** some prepared statements internally.
115623   */
115624   sqlite3VtabRollback(db);
115625
115626   /* Legacy behavior (sqlite3_close() behavior) is to return
115627   ** SQLITE_BUSY if the connection can not be closed immediately.
115628   */
115629   if( !forceZombie && connectionIsBusy(db) ){
115630     sqlite3Error(db, SQLITE_BUSY, "unable to close due to unfinalized "
115631        "statements or unfinished backups");
115632     sqlite3_mutex_leave(db->mutex);
115633     return SQLITE_BUSY;
115634   }
115635
115636 #ifdef SQLITE_ENABLE_SQLLOG
115637   if( sqlite3GlobalConfig.xSqllog ){
115638     /* Closing the handle. Fourth parameter is passed the value 2. */
115639     sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
115640   }
115641 #endif
115642
115643   /* Convert the connection into a zombie and then close it.
115644   */
115645   db->magic = SQLITE_MAGIC_ZOMBIE;
115646   sqlite3LeaveMutexAndCloseZombie(db);
115647   return SQLITE_OK;
115648 }
115649
115650 /*
115651 ** Two variations on the public interface for closing a database
115652 ** connection. The sqlite3_close() version returns SQLITE_BUSY and
115653 ** leaves the connection option if there are unfinalized prepared
115654 ** statements or unfinished sqlite3_backups.  The sqlite3_close_v2()
115655 ** version forces the connection to become a zombie if there are
115656 ** unclosed resources, and arranges for deallocation when the last
115657 ** prepare statement or sqlite3_backup closes.
115658 */
115659 SQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
115660 SQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
115661
115662
115663 /*
115664 ** Close the mutex on database connection db.
115665 **
115666 ** Furthermore, if database connection db is a zombie (meaning that there
115667 ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
115668 ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
115669 ** finished, then free all resources.
115670 */
115671 SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
115672   HashElem *i;                    /* Hash table iterator */
115673   int j;
115674
115675   /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
115676   ** or if the connection has not yet been closed by sqlite3_close_v2(),
115677   ** then just leave the mutex and return.
115678   */
115679   if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
115680     sqlite3_mutex_leave(db->mutex);
115681     return;
115682   }
115683
115684   /* If we reach this point, it means that the database connection has
115685   ** closed all sqlite3_stmt and sqlite3_backup objects and has been
115686   ** passed to sqlite3_close (meaning that it is a zombie).  Therefore,
115687   ** go ahead and free all resources.
115688   */
115689
115690   /* If a transaction is open, roll it back. This also ensures that if
115691   ** any database schemas have been modified by an uncommitted transaction
115692   ** they are reset. And that the required b-tree mutex is held to make
115693   ** the pager rollback and schema reset an atomic operation. */
115694   sqlite3RollbackAll(db, SQLITE_OK);
115695
115696   /* Free any outstanding Savepoint structures. */
115697   sqlite3CloseSavepoints(db);
115698
115699   /* Close all database connections */
115700   for(j=0; j<db->nDb; j++){
115701     struct Db *pDb = &db->aDb[j];
115702     if( pDb->pBt ){
115703       sqlite3BtreeClose(pDb->pBt);
115704       pDb->pBt = 0;
115705       if( j!=1 ){
115706         pDb->pSchema = 0;
115707       }
115708     }
115709   }
115710   /* Clear the TEMP schema separately and last */
115711   if( db->aDb[1].pSchema ){
115712     sqlite3SchemaClear(db->aDb[1].pSchema);
115713   }
115714   sqlite3VtabUnlockList(db);
115715
115716   /* Free up the array of auxiliary databases */
115717   sqlite3CollapseDatabaseArray(db);
115718   assert( db->nDb<=2 );
115719   assert( db->aDb==db->aDbStatic );
115720
115721   /* Tell the code in notify.c that the connection no longer holds any
115722   ** locks and does not require any further unlock-notify callbacks.
115723   */
115724   sqlite3ConnectionClosed(db);
115725
115726   for(j=0; j<ArraySize(db->aFunc.a); j++){
115727     FuncDef *pNext, *pHash, *p;
115728     for(p=db->aFunc.a[j]; p; p=pHash){
115729       pHash = p->pHash;
115730       while( p ){
115731         functionDestroy(db, p);
115732         pNext = p->pNext;
115733         sqlite3DbFree(db, p);
115734         p = pNext;
115735       }
115736     }
115737   }
115738   for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
115739     CollSeq *pColl = (CollSeq *)sqliteHashData(i);
115740     /* Invoke any destructors registered for collation sequence user data. */
115741     for(j=0; j<3; j++){
115742       if( pColl[j].xDel ){
115743         pColl[j].xDel(pColl[j].pUser);
115744       }
115745     }
115746     sqlite3DbFree(db, pColl);
115747   }
115748   sqlite3HashClear(&db->aCollSeq);
115749 #ifndef SQLITE_OMIT_VIRTUALTABLE
115750   for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
115751     Module *pMod = (Module *)sqliteHashData(i);
115752     if( pMod->xDestroy ){
115753       pMod->xDestroy(pMod->pAux);
115754     }
115755     sqlite3DbFree(db, pMod);
115756   }
115757   sqlite3HashClear(&db->aModule);
115758 #endif
115759
115760   sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
115761   if( db->pErr ){
115762     sqlite3ValueFree(db->pErr);
115763   }
115764   sqlite3CloseExtensions(db);
115765
115766   db->magic = SQLITE_MAGIC_ERROR;
115767
115768   /* The temp-database schema is allocated differently from the other schema
115769   ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
115770   ** So it needs to be freed here. Todo: Why not roll the temp schema into
115771   ** the same sqliteMalloc() as the one that allocates the database 
115772   ** structure?
115773   */
115774   sqlite3DbFree(db, db->aDb[1].pSchema);
115775   sqlite3_mutex_leave(db->mutex);
115776   db->magic = SQLITE_MAGIC_CLOSED;
115777   sqlite3_mutex_free(db->mutex);
115778   assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
115779   if( db->lookaside.bMalloced ){
115780     sqlite3_free(db->lookaside.pStart);
115781   }
115782   sqlite3_free(db);
115783 }
115784
115785 /*
115786 ** Rollback all database files.  If tripCode is not SQLITE_OK, then
115787 ** any open cursors are invalidated ("tripped" - as in "tripping a circuit
115788 ** breaker") and made to return tripCode if there are any further
115789 ** attempts to use that cursor.
115790 */
115791 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
115792   int i;
115793   int inTrans = 0;
115794   assert( sqlite3_mutex_held(db->mutex) );
115795   sqlite3BeginBenignMalloc();
115796
115797   /* Obtain all b-tree mutexes before making any calls to BtreeRollback(). 
115798   ** This is important in case the transaction being rolled back has
115799   ** modified the database schema. If the b-tree mutexes are not taken
115800   ** here, then another shared-cache connection might sneak in between
115801   ** the database rollback and schema reset, which can cause false
115802   ** corruption reports in some cases.  */
115803   sqlite3BtreeEnterAll(db);
115804
115805   for(i=0; i<db->nDb; i++){
115806     Btree *p = db->aDb[i].pBt;
115807     if( p ){
115808       if( sqlite3BtreeIsInTrans(p) ){
115809         inTrans = 1;
115810       }
115811       sqlite3BtreeRollback(p, tripCode);
115812       db->aDb[i].inTrans = 0;
115813     }
115814   }
115815   sqlite3VtabRollback(db);
115816   sqlite3EndBenignMalloc();
115817
115818   if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){
115819     sqlite3ExpirePreparedStatements(db);
115820     sqlite3ResetAllSchemasOfConnection(db);
115821   }
115822   sqlite3BtreeLeaveAll(db);
115823
115824   /* Any deferred constraint violations have now been resolved. */
115825   db->nDeferredCons = 0;
115826
115827   /* If one has been configured, invoke the rollback-hook callback */
115828   if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
115829     db->xRollbackCallback(db->pRollbackArg);
115830   }
115831 }
115832
115833 /*
115834 ** Return a static string containing the name corresponding to the error code
115835 ** specified in the argument.
115836 */
115837 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) || \
115838     defined(SQLITE_DEBUG_OS_TRACE)
115839 SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
115840   const char *zName = 0;
115841   int i, origRc = rc;
115842   for(i=0; i<2 && zName==0; i++, rc &= 0xff){
115843     switch( rc ){
115844       case SQLITE_OK:                 zName = "SQLITE_OK";                break;
115845       case SQLITE_ERROR:              zName = "SQLITE_ERROR";             break;
115846       case SQLITE_INTERNAL:           zName = "SQLITE_INTERNAL";          break;
115847       case SQLITE_PERM:               zName = "SQLITE_PERM";              break;
115848       case SQLITE_ABORT:              zName = "SQLITE_ABORT";             break;
115849       case SQLITE_ABORT_ROLLBACK:     zName = "SQLITE_ABORT_ROLLBACK";    break;
115850       case SQLITE_BUSY:               zName = "SQLITE_BUSY";              break;
115851       case SQLITE_BUSY_RECOVERY:      zName = "SQLITE_BUSY_RECOVERY";     break;
115852       case SQLITE_LOCKED:             zName = "SQLITE_LOCKED";            break;
115853       case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
115854       case SQLITE_NOMEM:              zName = "SQLITE_NOMEM";             break;
115855       case SQLITE_READONLY:           zName = "SQLITE_READONLY";          break;
115856       case SQLITE_READONLY_RECOVERY:  zName = "SQLITE_READONLY_RECOVERY"; break;
115857       case SQLITE_READONLY_CANTLOCK:  zName = "SQLITE_READONLY_CANTLOCK"; break;
115858       case SQLITE_READONLY_ROLLBACK:  zName = "SQLITE_READONLY_ROLLBACK"; break;
115859       case SQLITE_INTERRUPT:          zName = "SQLITE_INTERRUPT";         break;
115860       case SQLITE_IOERR:              zName = "SQLITE_IOERR";             break;
115861       case SQLITE_IOERR_READ:         zName = "SQLITE_IOERR_READ";        break;
115862       case SQLITE_IOERR_SHORT_READ:   zName = "SQLITE_IOERR_SHORT_READ";  break;
115863       case SQLITE_IOERR_WRITE:        zName = "SQLITE_IOERR_WRITE";       break;
115864       case SQLITE_IOERR_FSYNC:        zName = "SQLITE_IOERR_FSYNC";       break;
115865       case SQLITE_IOERR_DIR_FSYNC:    zName = "SQLITE_IOERR_DIR_FSYNC";   break;
115866       case SQLITE_IOERR_TRUNCATE:     zName = "SQLITE_IOERR_TRUNCATE";    break;
115867       case SQLITE_IOERR_FSTAT:        zName = "SQLITE_IOERR_FSTAT";       break;
115868       case SQLITE_IOERR_UNLOCK:       zName = "SQLITE_IOERR_UNLOCK";      break;
115869       case SQLITE_IOERR_RDLOCK:       zName = "SQLITE_IOERR_RDLOCK";      break;
115870       case SQLITE_IOERR_DELETE:       zName = "SQLITE_IOERR_DELETE";      break;
115871       case SQLITE_IOERR_BLOCKED:      zName = "SQLITE_IOERR_BLOCKED";     break;
115872       case SQLITE_IOERR_NOMEM:        zName = "SQLITE_IOERR_NOMEM";       break;
115873       case SQLITE_IOERR_ACCESS:       zName = "SQLITE_IOERR_ACCESS";      break;
115874       case SQLITE_IOERR_CHECKRESERVEDLOCK:
115875                                 zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
115876       case SQLITE_IOERR_LOCK:         zName = "SQLITE_IOERR_LOCK";        break;
115877       case SQLITE_IOERR_CLOSE:        zName = "SQLITE_IOERR_CLOSE";       break;
115878       case SQLITE_IOERR_DIR_CLOSE:    zName = "SQLITE_IOERR_DIR_CLOSE";   break;
115879       case SQLITE_IOERR_SHMOPEN:      zName = "SQLITE_IOERR_SHMOPEN";     break;
115880       case SQLITE_IOERR_SHMSIZE:      zName = "SQLITE_IOERR_SHMSIZE";     break;
115881       case SQLITE_IOERR_SHMLOCK:      zName = "SQLITE_IOERR_SHMLOCK";     break;
115882       case SQLITE_IOERR_SHMMAP:       zName = "SQLITE_IOERR_SHMMAP";      break;
115883       case SQLITE_IOERR_SEEK:         zName = "SQLITE_IOERR_SEEK";        break;
115884       case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
115885       case SQLITE_IOERR_MMAP:         zName = "SQLITE_IOERR_MMAP";        break;
115886       case SQLITE_CORRUPT:            zName = "SQLITE_CORRUPT";           break;
115887       case SQLITE_CORRUPT_VTAB:       zName = "SQLITE_CORRUPT_VTAB";      break;
115888       case SQLITE_NOTFOUND:           zName = "SQLITE_NOTFOUND";          break;
115889       case SQLITE_FULL:               zName = "SQLITE_FULL";              break;
115890       case SQLITE_CANTOPEN:           zName = "SQLITE_CANTOPEN";          break;
115891       case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
115892       case SQLITE_CANTOPEN_ISDIR:     zName = "SQLITE_CANTOPEN_ISDIR";    break;
115893       case SQLITE_CANTOPEN_FULLPATH:  zName = "SQLITE_CANTOPEN_FULLPATH"; break;
115894       case SQLITE_PROTOCOL:           zName = "SQLITE_PROTOCOL";          break;
115895       case SQLITE_EMPTY:              zName = "SQLITE_EMPTY";             break;
115896       case SQLITE_SCHEMA:             zName = "SQLITE_SCHEMA";            break;
115897       case SQLITE_TOOBIG:             zName = "SQLITE_TOOBIG";            break;
115898       case SQLITE_CONSTRAINT:         zName = "SQLITE_CONSTRAINT";        break;
115899       case SQLITE_CONSTRAINT_UNIQUE:  zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
115900       case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
115901       case SQLITE_CONSTRAINT_FOREIGNKEY:
115902                                 zName = "SQLITE_CONSTRAINT_FOREIGNKEY";   break;
115903       case SQLITE_CONSTRAINT_CHECK:   zName = "SQLITE_CONSTRAINT_CHECK";  break;
115904       case SQLITE_CONSTRAINT_PRIMARYKEY:
115905                                 zName = "SQLITE_CONSTRAINT_PRIMARYKEY";   break;
115906       case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
115907       case SQLITE_CONSTRAINT_COMMITHOOK:
115908                                 zName = "SQLITE_CONSTRAINT_COMMITHOOK";   break;
115909       case SQLITE_CONSTRAINT_VTAB:    zName = "SQLITE_CONSTRAINT_VTAB";   break;
115910       case SQLITE_CONSTRAINT_FUNCTION:
115911                                 zName = "SQLITE_CONSTRAINT_FUNCTION";     break;
115912       case SQLITE_MISMATCH:           zName = "SQLITE_MISMATCH";          break;
115913       case SQLITE_MISUSE:             zName = "SQLITE_MISUSE";            break;
115914       case SQLITE_NOLFS:              zName = "SQLITE_NOLFS";             break;
115915       case SQLITE_AUTH:               zName = "SQLITE_AUTH";              break;
115916       case SQLITE_FORMAT:             zName = "SQLITE_FORMAT";            break;
115917       case SQLITE_RANGE:              zName = "SQLITE_RANGE";             break;
115918       case SQLITE_NOTADB:             zName = "SQLITE_NOTADB";            break;
115919       case SQLITE_ROW:                zName = "SQLITE_ROW";               break;
115920       case SQLITE_NOTICE:             zName = "SQLITE_NOTICE";            break;
115921       case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
115922       case SQLITE_NOTICE_RECOVER_ROLLBACK:
115923                                 zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
115924       case SQLITE_WARNING:            zName = "SQLITE_WARNING";           break;
115925       case SQLITE_DONE:               zName = "SQLITE_DONE";              break;
115926     }
115927   }
115928   if( zName==0 ){
115929     static char zBuf[50];
115930     sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
115931     zName = zBuf;
115932   }
115933   return zName;
115934 }
115935 #endif
115936
115937 /*
115938 ** Return a static string that describes the kind of error specified in the
115939 ** argument.
115940 */
115941 SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
115942   static const char* const aMsg[] = {
115943     /* SQLITE_OK          */ "not an error",
115944     /* SQLITE_ERROR       */ "SQL logic error or missing database",
115945     /* SQLITE_INTERNAL    */ 0,
115946     /* SQLITE_PERM        */ "access permission denied",
115947     /* SQLITE_ABORT       */ "callback requested query abort",
115948     /* SQLITE_BUSY        */ "database is locked",
115949     /* SQLITE_LOCKED      */ "database table is locked",
115950     /* SQLITE_NOMEM       */ "out of memory",
115951     /* SQLITE_READONLY    */ "attempt to write a readonly database",
115952     /* SQLITE_INTERRUPT   */ "interrupted",
115953     /* SQLITE_IOERR       */ "disk I/O error",
115954     /* SQLITE_CORRUPT     */ "database disk image is malformed",
115955     /* SQLITE_NOTFOUND    */ "unknown operation",
115956     /* SQLITE_FULL        */ "database or disk is full",
115957     /* SQLITE_CANTOPEN    */ "unable to open database file",
115958     /* SQLITE_PROTOCOL    */ "locking protocol",
115959     /* SQLITE_EMPTY       */ "table contains no data",
115960     /* SQLITE_SCHEMA      */ "database schema has changed",
115961     /* SQLITE_TOOBIG      */ "string or blob too big",
115962     /* SQLITE_CONSTRAINT  */ "constraint failed",
115963     /* SQLITE_MISMATCH    */ "datatype mismatch",
115964     /* SQLITE_MISUSE      */ "library routine called out of sequence",
115965     /* SQLITE_NOLFS       */ "large file support is disabled",
115966     /* SQLITE_AUTH        */ "authorization denied",
115967     /* SQLITE_FORMAT      */ "auxiliary database format error",
115968     /* SQLITE_RANGE       */ "bind or column index out of range",
115969     /* SQLITE_NOTADB      */ "file is encrypted or is not a database",
115970   };
115971   const char *zErr = "unknown error";
115972   switch( rc ){
115973     case SQLITE_ABORT_ROLLBACK: {
115974       zErr = "abort due to ROLLBACK";
115975       break;
115976     }
115977     default: {
115978       rc &= 0xff;
115979       if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
115980         zErr = aMsg[rc];
115981       }
115982       break;
115983     }
115984   }
115985   return zErr;
115986 }
115987
115988 /*
115989 ** This routine implements a busy callback that sleeps and tries
115990 ** again until a timeout value is reached.  The timeout value is
115991 ** an integer number of milliseconds passed in as the first
115992 ** argument.
115993 */
115994 static int sqliteDefaultBusyCallback(
115995  void *ptr,               /* Database connection */
115996  int count                /* Number of times table has been busy */
115997 ){
115998 #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
115999   static const u8 delays[] =
116000      { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
116001   static const u8 totals[] =
116002      { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
116003 # define NDELAY ArraySize(delays)
116004   sqlite3 *db = (sqlite3 *)ptr;
116005   int timeout = db->busyTimeout;
116006   int delay, prior;
116007
116008   assert( count>=0 );
116009   if( count < NDELAY ){
116010     delay = delays[count];
116011     prior = totals[count];
116012   }else{
116013     delay = delays[NDELAY-1];
116014     prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
116015   }
116016   if( prior + delay > timeout ){
116017     delay = timeout - prior;
116018     if( delay<=0 ) return 0;
116019   }
116020   sqlite3OsSleep(db->pVfs, delay*1000);
116021   return 1;
116022 #else
116023   sqlite3 *db = (sqlite3 *)ptr;
116024   int timeout = ((sqlite3 *)ptr)->busyTimeout;
116025   if( (count+1)*1000 > timeout ){
116026     return 0;
116027   }
116028   sqlite3OsSleep(db->pVfs, 1000000);
116029   return 1;
116030 #endif
116031 }
116032
116033 /*
116034 ** Invoke the given busy handler.
116035 **
116036 ** This routine is called when an operation failed with a lock.
116037 ** If this routine returns non-zero, the lock is retried.  If it
116038 ** returns 0, the operation aborts with an SQLITE_BUSY error.
116039 */
116040 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
116041   int rc;
116042   if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
116043   rc = p->xFunc(p->pArg, p->nBusy);
116044   if( rc==0 ){
116045     p->nBusy = -1;
116046   }else{
116047     p->nBusy++;
116048   }
116049   return rc; 
116050 }
116051
116052 /*
116053 ** This routine sets the busy callback for an Sqlite database to the
116054 ** given callback function with the given argument.
116055 */
116056 SQLITE_API int sqlite3_busy_handler(
116057   sqlite3 *db,
116058   int (*xBusy)(void*,int),
116059   void *pArg
116060 ){
116061   sqlite3_mutex_enter(db->mutex);
116062   db->busyHandler.xFunc = xBusy;
116063   db->busyHandler.pArg = pArg;
116064   db->busyHandler.nBusy = 0;
116065   db->busyTimeout = 0;
116066   sqlite3_mutex_leave(db->mutex);
116067   return SQLITE_OK;
116068 }
116069
116070 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
116071 /*
116072 ** This routine sets the progress callback for an Sqlite database to the
116073 ** given callback function with the given argument. The progress callback will
116074 ** be invoked every nOps opcodes.
116075 */
116076 SQLITE_API void sqlite3_progress_handler(
116077   sqlite3 *db, 
116078   int nOps,
116079   int (*xProgress)(void*), 
116080   void *pArg
116081 ){
116082   sqlite3_mutex_enter(db->mutex);
116083   if( nOps>0 ){
116084     db->xProgress = xProgress;
116085     db->nProgressOps = nOps;
116086     db->pProgressArg = pArg;
116087   }else{
116088     db->xProgress = 0;
116089     db->nProgressOps = 0;
116090     db->pProgressArg = 0;
116091   }
116092   sqlite3_mutex_leave(db->mutex);
116093 }
116094 #endif
116095
116096
116097 /*
116098 ** This routine installs a default busy handler that waits for the
116099 ** specified number of milliseconds before returning 0.
116100 */
116101 SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
116102   if( ms>0 ){
116103     sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
116104     db->busyTimeout = ms;
116105   }else{
116106     sqlite3_busy_handler(db, 0, 0);
116107   }
116108   return SQLITE_OK;
116109 }
116110
116111 /*
116112 ** Cause any pending operation to stop at its earliest opportunity.
116113 */
116114 SQLITE_API void sqlite3_interrupt(sqlite3 *db){
116115   db->u1.isInterrupted = 1;
116116 }
116117
116118
116119 /*
116120 ** This function is exactly the same as sqlite3_create_function(), except
116121 ** that it is designed to be called by internal code. The difference is
116122 ** that if a malloc() fails in sqlite3_create_function(), an error code
116123 ** is returned and the mallocFailed flag cleared. 
116124 */
116125 SQLITE_PRIVATE int sqlite3CreateFunc(
116126   sqlite3 *db,
116127   const char *zFunctionName,
116128   int nArg,
116129   int enc,
116130   void *pUserData,
116131   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
116132   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
116133   void (*xFinal)(sqlite3_context*),
116134   FuncDestructor *pDestructor
116135 ){
116136   FuncDef *p;
116137   int nName;
116138
116139   assert( sqlite3_mutex_held(db->mutex) );
116140   if( zFunctionName==0 ||
116141       (xFunc && (xFinal || xStep)) || 
116142       (!xFunc && (xFinal && !xStep)) ||
116143       (!xFunc && (!xFinal && xStep)) ||
116144       (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
116145       (255<(nName = sqlite3Strlen30( zFunctionName))) ){
116146     return SQLITE_MISUSE_BKPT;
116147   }
116148   
116149 #ifndef SQLITE_OMIT_UTF16
116150   /* If SQLITE_UTF16 is specified as the encoding type, transform this
116151   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
116152   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
116153   **
116154   ** If SQLITE_ANY is specified, add three versions of the function
116155   ** to the hash table.
116156   */
116157   if( enc==SQLITE_UTF16 ){
116158     enc = SQLITE_UTF16NATIVE;
116159   }else if( enc==SQLITE_ANY ){
116160     int rc;
116161     rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
116162          pUserData, xFunc, xStep, xFinal, pDestructor);
116163     if( rc==SQLITE_OK ){
116164       rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
116165           pUserData, xFunc, xStep, xFinal, pDestructor);
116166     }
116167     if( rc!=SQLITE_OK ){
116168       return rc;
116169     }
116170     enc = SQLITE_UTF16BE;
116171   }
116172 #else
116173   enc = SQLITE_UTF8;
116174 #endif
116175   
116176   /* Check if an existing function is being overridden or deleted. If so,
116177   ** and there are active VMs, then return SQLITE_BUSY. If a function
116178   ** is being overridden/deleted but there are no active VMs, allow the
116179   ** operation to continue but invalidate all precompiled statements.
116180   */
116181   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
116182   if( p && p->iPrefEnc==enc && p->nArg==nArg ){
116183     if( db->activeVdbeCnt ){
116184       sqlite3Error(db, SQLITE_BUSY, 
116185         "unable to delete/modify user-function due to active statements");
116186       assert( !db->mallocFailed );
116187       return SQLITE_BUSY;
116188     }else{
116189       sqlite3ExpirePreparedStatements(db);
116190     }
116191   }
116192
116193   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
116194   assert(p || db->mallocFailed);
116195   if( !p ){
116196     return SQLITE_NOMEM;
116197   }
116198
116199   /* If an older version of the function with a configured destructor is
116200   ** being replaced invoke the destructor function here. */
116201   functionDestroy(db, p);
116202
116203   if( pDestructor ){
116204     pDestructor->nRef++;
116205   }
116206   p->pDestructor = pDestructor;
116207   p->flags = 0;
116208   p->xFunc = xFunc;
116209   p->xStep = xStep;
116210   p->xFinalize = xFinal;
116211   p->pUserData = pUserData;
116212   p->nArg = (u16)nArg;
116213   return SQLITE_OK;
116214 }
116215
116216 /*
116217 ** Create new user functions.
116218 */
116219 SQLITE_API int sqlite3_create_function(
116220   sqlite3 *db,
116221   const char *zFunc,
116222   int nArg,
116223   int enc,
116224   void *p,
116225   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
116226   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
116227   void (*xFinal)(sqlite3_context*)
116228 ){
116229   return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
116230                                     xFinal, 0);
116231 }
116232
116233 SQLITE_API int sqlite3_create_function_v2(
116234   sqlite3 *db,
116235   const char *zFunc,
116236   int nArg,
116237   int enc,
116238   void *p,
116239   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
116240   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
116241   void (*xFinal)(sqlite3_context*),
116242   void (*xDestroy)(void *)
116243 ){
116244   int rc = SQLITE_ERROR;
116245   FuncDestructor *pArg = 0;
116246   sqlite3_mutex_enter(db->mutex);
116247   if( xDestroy ){
116248     pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
116249     if( !pArg ){
116250       xDestroy(p);
116251       goto out;
116252     }
116253     pArg->xDestroy = xDestroy;
116254     pArg->pUserData = p;
116255   }
116256   rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
116257   if( pArg && pArg->nRef==0 ){
116258     assert( rc!=SQLITE_OK );
116259     xDestroy(p);
116260     sqlite3DbFree(db, pArg);
116261   }
116262
116263  out:
116264   rc = sqlite3ApiExit(db, rc);
116265   sqlite3_mutex_leave(db->mutex);
116266   return rc;
116267 }
116268
116269 #ifndef SQLITE_OMIT_UTF16
116270 SQLITE_API int sqlite3_create_function16(
116271   sqlite3 *db,
116272   const void *zFunctionName,
116273   int nArg,
116274   int eTextRep,
116275   void *p,
116276   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
116277   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
116278   void (*xFinal)(sqlite3_context*)
116279 ){
116280   int rc;
116281   char *zFunc8;
116282   sqlite3_mutex_enter(db->mutex);
116283   assert( !db->mallocFailed );
116284   zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
116285   rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
116286   sqlite3DbFree(db, zFunc8);
116287   rc = sqlite3ApiExit(db, rc);
116288   sqlite3_mutex_leave(db->mutex);
116289   return rc;
116290 }
116291 #endif
116292
116293
116294 /*
116295 ** Declare that a function has been overloaded by a virtual table.
116296 **
116297 ** If the function already exists as a regular global function, then
116298 ** this routine is a no-op.  If the function does not exist, then create
116299 ** a new one that always throws a run-time error.  
116300 **
116301 ** When virtual tables intend to provide an overloaded function, they
116302 ** should call this routine to make sure the global function exists.
116303 ** A global function must exist in order for name resolution to work
116304 ** properly.
116305 */
116306 SQLITE_API int sqlite3_overload_function(
116307   sqlite3 *db,
116308   const char *zName,
116309   int nArg
116310 ){
116311   int nName = sqlite3Strlen30(zName);
116312   int rc = SQLITE_OK;
116313   sqlite3_mutex_enter(db->mutex);
116314   if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
116315     rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
116316                            0, sqlite3InvalidFunction, 0, 0, 0);
116317   }
116318   rc = sqlite3ApiExit(db, rc);
116319   sqlite3_mutex_leave(db->mutex);
116320   return rc;
116321 }
116322
116323 #ifndef SQLITE_OMIT_TRACE
116324 /*
116325 ** Register a trace function.  The pArg from the previously registered trace
116326 ** is returned.  
116327 **
116328 ** A NULL trace function means that no tracing is executes.  A non-NULL
116329 ** trace is a pointer to a function that is invoked at the start of each
116330 ** SQL statement.
116331 */
116332 SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
116333   void *pOld;
116334   sqlite3_mutex_enter(db->mutex);
116335   pOld = db->pTraceArg;
116336   db->xTrace = xTrace;
116337   db->pTraceArg = pArg;
116338   sqlite3_mutex_leave(db->mutex);
116339   return pOld;
116340 }
116341 /*
116342 ** Register a profile function.  The pArg from the previously registered 
116343 ** profile function is returned.  
116344 **
116345 ** A NULL profile function means that no profiling is executes.  A non-NULL
116346 ** profile is a pointer to a function that is invoked at the conclusion of
116347 ** each SQL statement that is run.
116348 */
116349 SQLITE_API void *sqlite3_profile(
116350   sqlite3 *db,
116351   void (*xProfile)(void*,const char*,sqlite_uint64),
116352   void *pArg
116353 ){
116354   void *pOld;
116355   sqlite3_mutex_enter(db->mutex);
116356   pOld = db->pProfileArg;
116357   db->xProfile = xProfile;
116358   db->pProfileArg = pArg;
116359   sqlite3_mutex_leave(db->mutex);
116360   return pOld;
116361 }
116362 #endif /* SQLITE_OMIT_TRACE */
116363
116364 /*
116365 ** Register a function to be invoked when a transaction commits.
116366 ** If the invoked function returns non-zero, then the commit becomes a
116367 ** rollback.
116368 */
116369 SQLITE_API void *sqlite3_commit_hook(
116370   sqlite3 *db,              /* Attach the hook to this database */
116371   int (*xCallback)(void*),  /* Function to invoke on each commit */
116372   void *pArg                /* Argument to the function */
116373 ){
116374   void *pOld;
116375   sqlite3_mutex_enter(db->mutex);
116376   pOld = db->pCommitArg;
116377   db->xCommitCallback = xCallback;
116378   db->pCommitArg = pArg;
116379   sqlite3_mutex_leave(db->mutex);
116380   return pOld;
116381 }
116382
116383 /*
116384 ** Register a callback to be invoked each time a row is updated,
116385 ** inserted or deleted using this database connection.
116386 */
116387 SQLITE_API void *sqlite3_update_hook(
116388   sqlite3 *db,              /* Attach the hook to this database */
116389   void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
116390   void *pArg                /* Argument to the function */
116391 ){
116392   void *pRet;
116393   sqlite3_mutex_enter(db->mutex);
116394   pRet = db->pUpdateArg;
116395   db->xUpdateCallback = xCallback;
116396   db->pUpdateArg = pArg;
116397   sqlite3_mutex_leave(db->mutex);
116398   return pRet;
116399 }
116400
116401 /*
116402 ** Register a callback to be invoked each time a transaction is rolled
116403 ** back by this database connection.
116404 */
116405 SQLITE_API void *sqlite3_rollback_hook(
116406   sqlite3 *db,              /* Attach the hook to this database */
116407   void (*xCallback)(void*), /* Callback function */
116408   void *pArg                /* Argument to the function */
116409 ){
116410   void *pRet;
116411   sqlite3_mutex_enter(db->mutex);
116412   pRet = db->pRollbackArg;
116413   db->xRollbackCallback = xCallback;
116414   db->pRollbackArg = pArg;
116415   sqlite3_mutex_leave(db->mutex);
116416   return pRet;
116417 }
116418
116419 #ifndef SQLITE_OMIT_WAL
116420 /*
116421 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
116422 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
116423 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
116424 ** wal_autocheckpoint()).
116425 */ 
116426 SQLITE_PRIVATE int sqlite3WalDefaultHook(
116427   void *pClientData,     /* Argument */
116428   sqlite3 *db,           /* Connection */
116429   const char *zDb,       /* Database */
116430   int nFrame             /* Size of WAL */
116431 ){
116432   if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
116433     sqlite3BeginBenignMalloc();
116434     sqlite3_wal_checkpoint(db, zDb);
116435     sqlite3EndBenignMalloc();
116436   }
116437   return SQLITE_OK;
116438 }
116439 #endif /* SQLITE_OMIT_WAL */
116440
116441 /*
116442 ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
116443 ** a database after committing a transaction if there are nFrame or
116444 ** more frames in the log file. Passing zero or a negative value as the
116445 ** nFrame parameter disables automatic checkpoints entirely.
116446 **
116447 ** The callback registered by this function replaces any existing callback
116448 ** registered using sqlite3_wal_hook(). Likewise, registering a callback
116449 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
116450 ** configured by this function.
116451 */
116452 SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
116453 #ifdef SQLITE_OMIT_WAL
116454   UNUSED_PARAMETER(db);
116455   UNUSED_PARAMETER(nFrame);
116456 #else
116457   if( nFrame>0 ){
116458     sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
116459   }else{
116460     sqlite3_wal_hook(db, 0, 0);
116461   }
116462 #endif
116463   return SQLITE_OK;
116464 }
116465
116466 /*
116467 ** Register a callback to be invoked each time a transaction is written
116468 ** into the write-ahead-log by this database connection.
116469 */
116470 SQLITE_API void *sqlite3_wal_hook(
116471   sqlite3 *db,                    /* Attach the hook to this db handle */
116472   int(*xCallback)(void *, sqlite3*, const char*, int),
116473   void *pArg                      /* First argument passed to xCallback() */
116474 ){
116475 #ifndef SQLITE_OMIT_WAL
116476   void *pRet;
116477   sqlite3_mutex_enter(db->mutex);
116478   pRet = db->pWalArg;
116479   db->xWalCallback = xCallback;
116480   db->pWalArg = pArg;
116481   sqlite3_mutex_leave(db->mutex);
116482   return pRet;
116483 #else
116484   return 0;
116485 #endif
116486 }
116487
116488 /*
116489 ** Checkpoint database zDb.
116490 */
116491 SQLITE_API int sqlite3_wal_checkpoint_v2(
116492   sqlite3 *db,                    /* Database handle */
116493   const char *zDb,                /* Name of attached database (or NULL) */
116494   int eMode,                      /* SQLITE_CHECKPOINT_* value */
116495   int *pnLog,                     /* OUT: Size of WAL log in frames */
116496   int *pnCkpt                     /* OUT: Total number of frames checkpointed */
116497 ){
116498 #ifdef SQLITE_OMIT_WAL
116499   return SQLITE_OK;
116500 #else
116501   int rc;                         /* Return code */
116502   int iDb = SQLITE_MAX_ATTACHED;  /* sqlite3.aDb[] index of db to checkpoint */
116503
116504   /* Initialize the output variables to -1 in case an error occurs. */
116505   if( pnLog ) *pnLog = -1;
116506   if( pnCkpt ) *pnCkpt = -1;
116507
116508   assert( SQLITE_CHECKPOINT_FULL>SQLITE_CHECKPOINT_PASSIVE );
116509   assert( SQLITE_CHECKPOINT_FULL<SQLITE_CHECKPOINT_RESTART );
116510   assert( SQLITE_CHECKPOINT_PASSIVE+2==SQLITE_CHECKPOINT_RESTART );
116511   if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_RESTART ){
116512     return SQLITE_MISUSE;
116513   }
116514
116515   sqlite3_mutex_enter(db->mutex);
116516   if( zDb && zDb[0] ){
116517     iDb = sqlite3FindDbName(db, zDb);
116518   }
116519   if( iDb<0 ){
116520     rc = SQLITE_ERROR;
116521     sqlite3Error(db, SQLITE_ERROR, "unknown database: %s", zDb);
116522   }else{
116523     rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
116524     sqlite3Error(db, rc, 0);
116525   }
116526   rc = sqlite3ApiExit(db, rc);
116527   sqlite3_mutex_leave(db->mutex);
116528   return rc;
116529 #endif
116530 }
116531
116532
116533 /*
116534 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
116535 ** to contains a zero-length string, all attached databases are 
116536 ** checkpointed.
116537 */
116538 SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
116539   return sqlite3_wal_checkpoint_v2(db, zDb, SQLITE_CHECKPOINT_PASSIVE, 0, 0);
116540 }
116541
116542 #ifndef SQLITE_OMIT_WAL
116543 /*
116544 ** Run a checkpoint on database iDb. This is a no-op if database iDb is
116545 ** not currently open in WAL mode.
116546 **
116547 ** If a transaction is open on the database being checkpointed, this 
116548 ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If 
116549 ** an error occurs while running the checkpoint, an SQLite error code is 
116550 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
116551 **
116552 ** The mutex on database handle db should be held by the caller. The mutex
116553 ** associated with the specific b-tree being checkpointed is taken by
116554 ** this function while the checkpoint is running.
116555 **
116556 ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
116557 ** checkpointed. If an error is encountered it is returned immediately -
116558 ** no attempt is made to checkpoint any remaining databases.
116559 **
116560 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
116561 */
116562 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
116563   int rc = SQLITE_OK;             /* Return code */
116564   int i;                          /* Used to iterate through attached dbs */
116565   int bBusy = 0;                  /* True if SQLITE_BUSY has been encountered */
116566
116567   assert( sqlite3_mutex_held(db->mutex) );
116568   assert( !pnLog || *pnLog==-1 );
116569   assert( !pnCkpt || *pnCkpt==-1 );
116570
116571   for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
116572     if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
116573       rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
116574       pnLog = 0;
116575       pnCkpt = 0;
116576       if( rc==SQLITE_BUSY ){
116577         bBusy = 1;
116578         rc = SQLITE_OK;
116579       }
116580     }
116581   }
116582
116583   return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
116584 }
116585 #endif /* SQLITE_OMIT_WAL */
116586
116587 /*
116588 ** This function returns true if main-memory should be used instead of
116589 ** a temporary file for transient pager files and statement journals.
116590 ** The value returned depends on the value of db->temp_store (runtime
116591 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
116592 ** following table describes the relationship between these two values
116593 ** and this functions return value.
116594 **
116595 **   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
116596 **   -----------------     --------------     ------------------------------
116597 **   0                     any                file      (return 0)
116598 **   1                     1                  file      (return 0)
116599 **   1                     2                  memory    (return 1)
116600 **   1                     0                  file      (return 0)
116601 **   2                     1                  file      (return 0)
116602 **   2                     2                  memory    (return 1)
116603 **   2                     0                  memory    (return 1)
116604 **   3                     any                memory    (return 1)
116605 */
116606 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
116607 #if SQLITE_TEMP_STORE==1
116608   return ( db->temp_store==2 );
116609 #endif
116610 #if SQLITE_TEMP_STORE==2
116611   return ( db->temp_store!=1 );
116612 #endif
116613 #if SQLITE_TEMP_STORE==3
116614   return 1;
116615 #endif
116616 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
116617   return 0;
116618 #endif
116619 }
116620
116621 /*
116622 ** Return UTF-8 encoded English language explanation of the most recent
116623 ** error.
116624 */
116625 SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
116626   const char *z;
116627   if( !db ){
116628     return sqlite3ErrStr(SQLITE_NOMEM);
116629   }
116630   if( !sqlite3SafetyCheckSickOrOk(db) ){
116631     return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
116632   }
116633   sqlite3_mutex_enter(db->mutex);
116634   if( db->mallocFailed ){
116635     z = sqlite3ErrStr(SQLITE_NOMEM);
116636   }else{
116637     z = (char*)sqlite3_value_text(db->pErr);
116638     assert( !db->mallocFailed );
116639     if( z==0 ){
116640       z = sqlite3ErrStr(db->errCode);
116641     }
116642   }
116643   sqlite3_mutex_leave(db->mutex);
116644   return z;
116645 }
116646
116647 #ifndef SQLITE_OMIT_UTF16
116648 /*
116649 ** Return UTF-16 encoded English language explanation of the most recent
116650 ** error.
116651 */
116652 SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
116653   static const u16 outOfMem[] = {
116654     'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
116655   };
116656   static const u16 misuse[] = {
116657     'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ', 
116658     'r', 'o', 'u', 't', 'i', 'n', 'e', ' ', 
116659     'c', 'a', 'l', 'l', 'e', 'd', ' ', 
116660     'o', 'u', 't', ' ', 
116661     'o', 'f', ' ', 
116662     's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
116663   };
116664
116665   const void *z;
116666   if( !db ){
116667     return (void *)outOfMem;
116668   }
116669   if( !sqlite3SafetyCheckSickOrOk(db) ){
116670     return (void *)misuse;
116671   }
116672   sqlite3_mutex_enter(db->mutex);
116673   if( db->mallocFailed ){
116674     z = (void *)outOfMem;
116675   }else{
116676     z = sqlite3_value_text16(db->pErr);
116677     if( z==0 ){
116678       sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
116679            SQLITE_UTF8, SQLITE_STATIC);
116680       z = sqlite3_value_text16(db->pErr);
116681     }
116682     /* A malloc() may have failed within the call to sqlite3_value_text16()
116683     ** above. If this is the case, then the db->mallocFailed flag needs to
116684     ** be cleared before returning. Do this directly, instead of via
116685     ** sqlite3ApiExit(), to avoid setting the database handle error message.
116686     */
116687     db->mallocFailed = 0;
116688   }
116689   sqlite3_mutex_leave(db->mutex);
116690   return z;
116691 }
116692 #endif /* SQLITE_OMIT_UTF16 */
116693
116694 /*
116695 ** Return the most recent error code generated by an SQLite routine. If NULL is
116696 ** passed to this function, we assume a malloc() failed during sqlite3_open().
116697 */
116698 SQLITE_API int sqlite3_errcode(sqlite3 *db){
116699   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
116700     return SQLITE_MISUSE_BKPT;
116701   }
116702   if( !db || db->mallocFailed ){
116703     return SQLITE_NOMEM;
116704   }
116705   return db->errCode & db->errMask;
116706 }
116707 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
116708   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
116709     return SQLITE_MISUSE_BKPT;
116710   }
116711   if( !db || db->mallocFailed ){
116712     return SQLITE_NOMEM;
116713   }
116714   return db->errCode;
116715 }
116716
116717 /*
116718 ** Return a string that describes the kind of error specified in the
116719 ** argument.  For now, this simply calls the internal sqlite3ErrStr()
116720 ** function.
116721 */
116722 SQLITE_API const char *sqlite3_errstr(int rc){
116723   return sqlite3ErrStr(rc);
116724 }
116725
116726 /*
116727 ** Create a new collating function for database "db".  The name is zName
116728 ** and the encoding is enc.
116729 */
116730 static int createCollation(
116731   sqlite3* db,
116732   const char *zName, 
116733   u8 enc,
116734   void* pCtx,
116735   int(*xCompare)(void*,int,const void*,int,const void*),
116736   void(*xDel)(void*)
116737 ){
116738   CollSeq *pColl;
116739   int enc2;
116740   int nName = sqlite3Strlen30(zName);
116741   
116742   assert( sqlite3_mutex_held(db->mutex) );
116743
116744   /* If SQLITE_UTF16 is specified as the encoding type, transform this
116745   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
116746   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
116747   */
116748   enc2 = enc;
116749   testcase( enc2==SQLITE_UTF16 );
116750   testcase( enc2==SQLITE_UTF16_ALIGNED );
116751   if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
116752     enc2 = SQLITE_UTF16NATIVE;
116753   }
116754   if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
116755     return SQLITE_MISUSE_BKPT;
116756   }
116757
116758   /* Check if this call is removing or replacing an existing collation 
116759   ** sequence. If so, and there are active VMs, return busy. If there
116760   ** are no active VMs, invalidate any pre-compiled statements.
116761   */
116762   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
116763   if( pColl && pColl->xCmp ){
116764     if( db->activeVdbeCnt ){
116765       sqlite3Error(db, SQLITE_BUSY, 
116766         "unable to delete/modify collation sequence due to active statements");
116767       return SQLITE_BUSY;
116768     }
116769     sqlite3ExpirePreparedStatements(db);
116770
116771     /* If collation sequence pColl was created directly by a call to
116772     ** sqlite3_create_collation, and not generated by synthCollSeq(),
116773     ** then any copies made by synthCollSeq() need to be invalidated.
116774     ** Also, collation destructor - CollSeq.xDel() - function may need
116775     ** to be called.
116776     */ 
116777     if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
116778       CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
116779       int j;
116780       for(j=0; j<3; j++){
116781         CollSeq *p = &aColl[j];
116782         if( p->enc==pColl->enc ){
116783           if( p->xDel ){
116784             p->xDel(p->pUser);
116785           }
116786           p->xCmp = 0;
116787         }
116788       }
116789     }
116790   }
116791
116792   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
116793   if( pColl==0 ) return SQLITE_NOMEM;
116794   pColl->xCmp = xCompare;
116795   pColl->pUser = pCtx;
116796   pColl->xDel = xDel;
116797   pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
116798   sqlite3Error(db, SQLITE_OK, 0);
116799   return SQLITE_OK;
116800 }
116801
116802
116803 /*
116804 ** This array defines hard upper bounds on limit values.  The
116805 ** initializer must be kept in sync with the SQLITE_LIMIT_*
116806 ** #defines in sqlite3.h.
116807 */
116808 static const int aHardLimit[] = {
116809   SQLITE_MAX_LENGTH,
116810   SQLITE_MAX_SQL_LENGTH,
116811   SQLITE_MAX_COLUMN,
116812   SQLITE_MAX_EXPR_DEPTH,
116813   SQLITE_MAX_COMPOUND_SELECT,
116814   SQLITE_MAX_VDBE_OP,
116815   SQLITE_MAX_FUNCTION_ARG,
116816   SQLITE_MAX_ATTACHED,
116817   SQLITE_MAX_LIKE_PATTERN_LENGTH,
116818   SQLITE_MAX_VARIABLE_NUMBER,
116819   SQLITE_MAX_TRIGGER_DEPTH,
116820 };
116821
116822 /*
116823 ** Make sure the hard limits are set to reasonable values
116824 */
116825 #if SQLITE_MAX_LENGTH<100
116826 # error SQLITE_MAX_LENGTH must be at least 100
116827 #endif
116828 #if SQLITE_MAX_SQL_LENGTH<100
116829 # error SQLITE_MAX_SQL_LENGTH must be at least 100
116830 #endif
116831 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
116832 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
116833 #endif
116834 #if SQLITE_MAX_COMPOUND_SELECT<2
116835 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
116836 #endif
116837 #if SQLITE_MAX_VDBE_OP<40
116838 # error SQLITE_MAX_VDBE_OP must be at least 40
116839 #endif
116840 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
116841 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
116842 #endif
116843 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>62
116844 # error SQLITE_MAX_ATTACHED must be between 0 and 62
116845 #endif
116846 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
116847 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
116848 #endif
116849 #if SQLITE_MAX_COLUMN>32767
116850 # error SQLITE_MAX_COLUMN must not exceed 32767
116851 #endif
116852 #if SQLITE_MAX_TRIGGER_DEPTH<1
116853 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
116854 #endif
116855
116856
116857 /*
116858 ** Change the value of a limit.  Report the old value.
116859 ** If an invalid limit index is supplied, report -1.
116860 ** Make no changes but still report the old value if the
116861 ** new limit is negative.
116862 **
116863 ** A new lower limit does not shrink existing constructs.
116864 ** It merely prevents new constructs that exceed the limit
116865 ** from forming.
116866 */
116867 SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
116868   int oldLimit;
116869
116870
116871   /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
116872   ** there is a hard upper bound set at compile-time by a C preprocessor
116873   ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
116874   ** "_MAX_".)
116875   */
116876   assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
116877   assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
116878   assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
116879   assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
116880   assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
116881   assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
116882   assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
116883   assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
116884   assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
116885                                                SQLITE_MAX_LIKE_PATTERN_LENGTH );
116886   assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
116887   assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
116888   assert( SQLITE_LIMIT_TRIGGER_DEPTH==(SQLITE_N_LIMIT-1) );
116889
116890
116891   if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
116892     return -1;
116893   }
116894   oldLimit = db->aLimit[limitId];
116895   if( newLimit>=0 ){                   /* IMP: R-52476-28732 */
116896     if( newLimit>aHardLimit[limitId] ){
116897       newLimit = aHardLimit[limitId];  /* IMP: R-51463-25634 */
116898     }
116899     db->aLimit[limitId] = newLimit;
116900   }
116901   return oldLimit;                     /* IMP: R-53341-35419 */
116902 }
116903
116904 /*
116905 ** This function is used to parse both URIs and non-URI filenames passed by the
116906 ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
116907 ** URIs specified as part of ATTACH statements.
116908 **
116909 ** The first argument to this function is the name of the VFS to use (or
116910 ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
116911 ** query parameter. The second argument contains the URI (or non-URI filename)
116912 ** itself. When this function is called the *pFlags variable should contain
116913 ** the default flags to open the database handle with. The value stored in
116914 ** *pFlags may be updated before returning if the URI filename contains 
116915 ** "cache=xxx" or "mode=xxx" query parameters.
116916 **
116917 ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
116918 ** the VFS that should be used to open the database file. *pzFile is set to
116919 ** point to a buffer containing the name of the file to open. It is the 
116920 ** responsibility of the caller to eventually call sqlite3_free() to release
116921 ** this buffer.
116922 **
116923 ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
116924 ** may be set to point to a buffer containing an English language error 
116925 ** message. It is the responsibility of the caller to eventually release
116926 ** this buffer by calling sqlite3_free().
116927 */
116928 SQLITE_PRIVATE int sqlite3ParseUri(
116929   const char *zDefaultVfs,        /* VFS to use if no "vfs=xxx" query option */
116930   const char *zUri,               /* Nul-terminated URI to parse */
116931   unsigned int *pFlags,           /* IN/OUT: SQLITE_OPEN_XXX flags */
116932   sqlite3_vfs **ppVfs,            /* OUT: VFS to use */ 
116933   char **pzFile,                  /* OUT: Filename component of URI */
116934   char **pzErrMsg                 /* OUT: Error message (if rc!=SQLITE_OK) */
116935 ){
116936   int rc = SQLITE_OK;
116937   unsigned int flags = *pFlags;
116938   const char *zVfs = zDefaultVfs;
116939   char *zFile;
116940   char c;
116941   int nUri = sqlite3Strlen30(zUri);
116942
116943   assert( *pzErrMsg==0 );
116944
116945   if( ((flags & SQLITE_OPEN_URI) || sqlite3GlobalConfig.bOpenUri) 
116946    && nUri>=5 && memcmp(zUri, "file:", 5)==0 
116947   ){
116948     char *zOpt;
116949     int eState;                   /* Parser state when parsing URI */
116950     int iIn;                      /* Input character index */
116951     int iOut = 0;                 /* Output character index */
116952     int nByte = nUri+2;           /* Bytes of space to allocate */
116953
116954     /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen 
116955     ** method that there may be extra parameters following the file-name.  */
116956     flags |= SQLITE_OPEN_URI;
116957
116958     for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
116959     zFile = sqlite3_malloc(nByte);
116960     if( !zFile ) return SQLITE_NOMEM;
116961
116962     /* Discard the scheme and authority segments of the URI. */
116963     if( zUri[5]=='/' && zUri[6]=='/' ){
116964       iIn = 7;
116965       while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
116966
116967       if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
116968         *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s", 
116969             iIn-7, &zUri[7]);
116970         rc = SQLITE_ERROR;
116971         goto parse_uri_out;
116972       }
116973     }else{
116974       iIn = 5;
116975     }
116976
116977     /* Copy the filename and any query parameters into the zFile buffer. 
116978     ** Decode %HH escape codes along the way. 
116979     **
116980     ** Within this loop, variable eState may be set to 0, 1 or 2, depending
116981     ** on the parsing context. As follows:
116982     **
116983     **   0: Parsing file-name.
116984     **   1: Parsing name section of a name=value query parameter.
116985     **   2: Parsing value section of a name=value query parameter.
116986     */
116987     eState = 0;
116988     while( (c = zUri[iIn])!=0 && c!='#' ){
116989       iIn++;
116990       if( c=='%' 
116991        && sqlite3Isxdigit(zUri[iIn]) 
116992        && sqlite3Isxdigit(zUri[iIn+1]) 
116993       ){
116994         int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
116995         octet += sqlite3HexToInt(zUri[iIn++]);
116996
116997         assert( octet>=0 && octet<256 );
116998         if( octet==0 ){
116999           /* This branch is taken when "%00" appears within the URI. In this
117000           ** case we ignore all text in the remainder of the path, name or
117001           ** value currently being parsed. So ignore the current character
117002           ** and skip to the next "?", "=" or "&", as appropriate. */
117003           while( (c = zUri[iIn])!=0 && c!='#' 
117004               && (eState!=0 || c!='?')
117005               && (eState!=1 || (c!='=' && c!='&'))
117006               && (eState!=2 || c!='&')
117007           ){
117008             iIn++;
117009           }
117010           continue;
117011         }
117012         c = octet;
117013       }else if( eState==1 && (c=='&' || c=='=') ){
117014         if( zFile[iOut-1]==0 ){
117015           /* An empty option name. Ignore this option altogether. */
117016           while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
117017           continue;
117018         }
117019         if( c=='&' ){
117020           zFile[iOut++] = '\0';
117021         }else{
117022           eState = 2;
117023         }
117024         c = 0;
117025       }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
117026         c = 0;
117027         eState = 1;
117028       }
117029       zFile[iOut++] = c;
117030     }
117031     if( eState==1 ) zFile[iOut++] = '\0';
117032     zFile[iOut++] = '\0';
117033     zFile[iOut++] = '\0';
117034
117035     /* Check if there were any options specified that should be interpreted 
117036     ** here. Options that are interpreted here include "vfs" and those that
117037     ** correspond to flags that may be passed to the sqlite3_open_v2()
117038     ** method. */
117039     zOpt = &zFile[sqlite3Strlen30(zFile)+1];
117040     while( zOpt[0] ){
117041       int nOpt = sqlite3Strlen30(zOpt);
117042       char *zVal = &zOpt[nOpt+1];
117043       int nVal = sqlite3Strlen30(zVal);
117044
117045       if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
117046         zVfs = zVal;
117047       }else{
117048         struct OpenMode {
117049           const char *z;
117050           int mode;
117051         } *aMode = 0;
117052         char *zModeType = 0;
117053         int mask = 0;
117054         int limit = 0;
117055
117056         if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
117057           static struct OpenMode aCacheMode[] = {
117058             { "shared",  SQLITE_OPEN_SHAREDCACHE },
117059             { "private", SQLITE_OPEN_PRIVATECACHE },
117060             { 0, 0 }
117061           };
117062
117063           mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
117064           aMode = aCacheMode;
117065           limit = mask;
117066           zModeType = "cache";
117067         }
117068         if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
117069           static struct OpenMode aOpenMode[] = {
117070             { "ro",  SQLITE_OPEN_READONLY },
117071             { "rw",  SQLITE_OPEN_READWRITE }, 
117072             { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
117073             { "memory", SQLITE_OPEN_MEMORY },
117074             { 0, 0 }
117075           };
117076
117077           mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
117078                    | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
117079           aMode = aOpenMode;
117080           limit = mask & flags;
117081           zModeType = "access";
117082         }
117083
117084         if( aMode ){
117085           int i;
117086           int mode = 0;
117087           for(i=0; aMode[i].z; i++){
117088             const char *z = aMode[i].z;
117089             if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
117090               mode = aMode[i].mode;
117091               break;
117092             }
117093           }
117094           if( mode==0 ){
117095             *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
117096             rc = SQLITE_ERROR;
117097             goto parse_uri_out;
117098           }
117099           if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
117100             *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
117101                                         zModeType, zVal);
117102             rc = SQLITE_PERM;
117103             goto parse_uri_out;
117104           }
117105           flags = (flags & ~mask) | mode;
117106         }
117107       }
117108
117109       zOpt = &zVal[nVal+1];
117110     }
117111
117112   }else{
117113     zFile = sqlite3_malloc(nUri+2);
117114     if( !zFile ) return SQLITE_NOMEM;
117115     memcpy(zFile, zUri, nUri);
117116     zFile[nUri] = '\0';
117117     zFile[nUri+1] = '\0';
117118     flags &= ~SQLITE_OPEN_URI;
117119   }
117120
117121   *ppVfs = sqlite3_vfs_find(zVfs);
117122   if( *ppVfs==0 ){
117123     *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
117124     rc = SQLITE_ERROR;
117125   }
117126  parse_uri_out:
117127   if( rc!=SQLITE_OK ){
117128     sqlite3_free(zFile);
117129     zFile = 0;
117130   }
117131   *pFlags = flags;
117132   *pzFile = zFile;
117133   return rc;
117134 }
117135
117136
117137 /*
117138 ** This routine does the work of opening a database on behalf of
117139 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"  
117140 ** is UTF-8 encoded.
117141 */
117142 static int openDatabase(
117143   const char *zFilename, /* Database filename UTF-8 encoded */
117144   sqlite3 **ppDb,        /* OUT: Returned database handle */
117145   unsigned int flags,    /* Operational flags */
117146   const char *zVfs       /* Name of the VFS to use */
117147 ){
117148   sqlite3 *db;                    /* Store allocated handle here */
117149   int rc;                         /* Return code */
117150   int isThreadsafe;               /* True for threadsafe connections */
117151   char *zOpen = 0;                /* Filename argument to pass to BtreeOpen() */
117152   char *zErrMsg = 0;              /* Error message from sqlite3ParseUri() */
117153
117154   *ppDb = 0;
117155 #ifndef SQLITE_OMIT_AUTOINIT
117156   rc = sqlite3_initialize();
117157   if( rc ) return rc;
117158 #endif
117159
117160   /* Only allow sensible combinations of bits in the flags argument.  
117161   ** Throw an error if any non-sense combination is used.  If we
117162   ** do not block illegal combinations here, it could trigger
117163   ** assert() statements in deeper layers.  Sensible combinations
117164   ** are:
117165   **
117166   **  1:  SQLITE_OPEN_READONLY
117167   **  2:  SQLITE_OPEN_READWRITE
117168   **  6:  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
117169   */
117170   assert( SQLITE_OPEN_READONLY  == 0x01 );
117171   assert( SQLITE_OPEN_READWRITE == 0x02 );
117172   assert( SQLITE_OPEN_CREATE    == 0x04 );
117173   testcase( (1<<(flags&7))==0x02 ); /* READONLY */
117174   testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
117175   testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
117176   if( ((1<<(flags&7)) & 0x46)==0 ) return SQLITE_MISUSE_BKPT;
117177
117178   if( sqlite3GlobalConfig.bCoreMutex==0 ){
117179     isThreadsafe = 0;
117180   }else if( flags & SQLITE_OPEN_NOMUTEX ){
117181     isThreadsafe = 0;
117182   }else if( flags & SQLITE_OPEN_FULLMUTEX ){
117183     isThreadsafe = 1;
117184   }else{
117185     isThreadsafe = sqlite3GlobalConfig.bFullMutex;
117186   }
117187   if( flags & SQLITE_OPEN_PRIVATECACHE ){
117188     flags &= ~SQLITE_OPEN_SHAREDCACHE;
117189   }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
117190     flags |= SQLITE_OPEN_SHAREDCACHE;
117191   }
117192
117193   /* Remove harmful bits from the flags parameter
117194   **
117195   ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
117196   ** dealt with in the previous code block.  Besides these, the only
117197   ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
117198   ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
117199   ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits.  Silently mask
117200   ** off all other flags.
117201   */
117202   flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
117203                SQLITE_OPEN_EXCLUSIVE |
117204                SQLITE_OPEN_MAIN_DB |
117205                SQLITE_OPEN_TEMP_DB | 
117206                SQLITE_OPEN_TRANSIENT_DB | 
117207                SQLITE_OPEN_MAIN_JOURNAL | 
117208                SQLITE_OPEN_TEMP_JOURNAL | 
117209                SQLITE_OPEN_SUBJOURNAL | 
117210                SQLITE_OPEN_MASTER_JOURNAL |
117211                SQLITE_OPEN_NOMUTEX |
117212                SQLITE_OPEN_FULLMUTEX |
117213                SQLITE_OPEN_WAL
117214              );
117215
117216   /* Allocate the sqlite data structure */
117217   db = sqlite3MallocZero( sizeof(sqlite3) );
117218   if( db==0 ) goto opendb_out;
117219   if( isThreadsafe ){
117220     db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
117221     if( db->mutex==0 ){
117222       sqlite3_free(db);
117223       db = 0;
117224       goto opendb_out;
117225     }
117226   }
117227   sqlite3_mutex_enter(db->mutex);
117228   db->errMask = 0xff;
117229   db->nDb = 2;
117230   db->magic = SQLITE_MAGIC_BUSY;
117231   db->aDb = db->aDbStatic;
117232
117233   assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
117234   memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
117235   db->autoCommit = 1;
117236   db->nextAutovac = -1;
117237   db->szMmap = sqlite3GlobalConfig.szMmap;
117238   db->nextPagesize = 0;
117239   db->flags |= SQLITE_ShortColNames | SQLITE_AutoIndex | SQLITE_EnableTrigger
117240 #if SQLITE_DEFAULT_FILE_FORMAT<4
117241                  | SQLITE_LegacyFileFmt
117242 #endif
117243 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
117244                  | SQLITE_LoadExtension
117245 #endif
117246 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
117247                  | SQLITE_RecTriggers
117248 #endif
117249 #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
117250                  | SQLITE_ForeignKeys
117251 #endif
117252       ;
117253   sqlite3HashInit(&db->aCollSeq);
117254 #ifndef SQLITE_OMIT_VIRTUALTABLE
117255   sqlite3HashInit(&db->aModule);
117256 #endif
117257
117258   /* Add the default collation sequence BINARY. BINARY works for both UTF-8
117259   ** and UTF-16, so add a version for each to avoid any unnecessary
117260   ** conversions. The only error that can occur here is a malloc() failure.
117261   */
117262   createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
117263   createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
117264   createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
117265   createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
117266   if( db->mallocFailed ){
117267     goto opendb_out;
117268   }
117269   db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
117270   assert( db->pDfltColl!=0 );
117271
117272   /* Also add a UTF-8 case-insensitive collation sequence. */
117273   createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
117274
117275   /* Parse the filename/URI argument. */
117276   db->openFlags = flags;
117277   rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
117278   if( rc!=SQLITE_OK ){
117279     if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
117280     sqlite3Error(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
117281     sqlite3_free(zErrMsg);
117282     goto opendb_out;
117283   }
117284
117285   /* Open the backend database driver */
117286   rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
117287                         flags | SQLITE_OPEN_MAIN_DB);
117288   if( rc!=SQLITE_OK ){
117289     if( rc==SQLITE_IOERR_NOMEM ){
117290       rc = SQLITE_NOMEM;
117291     }
117292     sqlite3Error(db, rc, 0);
117293     goto opendb_out;
117294   }
117295   db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
117296   db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
117297
117298
117299   /* The default safety_level for the main database is 'full'; for the temp
117300   ** database it is 'NONE'. This matches the pager layer defaults.  
117301   */
117302   db->aDb[0].zName = "main";
117303   db->aDb[0].safety_level = 3;
117304   db->aDb[1].zName = "temp";
117305   db->aDb[1].safety_level = 1;
117306
117307   db->magic = SQLITE_MAGIC_OPEN;
117308   if( db->mallocFailed ){
117309     goto opendb_out;
117310   }
117311
117312   /* Register all built-in functions, but do not attempt to read the
117313   ** database schema yet. This is delayed until the first time the database
117314   ** is accessed.
117315   */
117316   sqlite3Error(db, SQLITE_OK, 0);
117317   sqlite3RegisterBuiltinFunctions(db);
117318
117319   /* Load automatic extensions - extensions that have been registered
117320   ** using the sqlite3_automatic_extension() API.
117321   */
117322   rc = sqlite3_errcode(db);
117323   if( rc==SQLITE_OK ){
117324     sqlite3AutoLoadExtensions(db);
117325     rc = sqlite3_errcode(db);
117326     if( rc!=SQLITE_OK ){
117327       goto opendb_out;
117328     }
117329   }
117330
117331 #ifdef SQLITE_ENABLE_FTS1
117332   if( !db->mallocFailed ){
117333     extern int sqlite3Fts1Init(sqlite3*);
117334     rc = sqlite3Fts1Init(db);
117335   }
117336 #endif
117337
117338 #ifdef SQLITE_ENABLE_FTS2
117339   if( !db->mallocFailed && rc==SQLITE_OK ){
117340     extern int sqlite3Fts2Init(sqlite3*);
117341     rc = sqlite3Fts2Init(db);
117342   }
117343 #endif
117344
117345 #ifdef SQLITE_ENABLE_FTS3
117346   if( !db->mallocFailed && rc==SQLITE_OK ){
117347     rc = sqlite3Fts3Init(db);
117348   }
117349 #endif
117350
117351 #ifdef SQLITE_ENABLE_ICU
117352   if( !db->mallocFailed && rc==SQLITE_OK ){
117353     rc = sqlite3IcuInit(db);
117354   }
117355 #endif
117356
117357 #ifdef SQLITE_ENABLE_RTREE
117358   if( !db->mallocFailed && rc==SQLITE_OK){
117359     rc = sqlite3RtreeInit(db);
117360   }
117361 #endif
117362
117363   sqlite3Error(db, rc, 0);
117364
117365   /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
117366   ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
117367   ** mode.  Doing nothing at all also makes NORMAL the default.
117368   */
117369 #ifdef SQLITE_DEFAULT_LOCKING_MODE
117370   db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
117371   sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
117372                           SQLITE_DEFAULT_LOCKING_MODE);
117373 #endif
117374
117375   /* Enable the lookaside-malloc subsystem */
117376   setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
117377                         sqlite3GlobalConfig.nLookaside);
117378
117379   sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
117380
117381 opendb_out:
117382   sqlite3_free(zOpen);
117383   if( db ){
117384     assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
117385     sqlite3_mutex_leave(db->mutex);
117386   }
117387   rc = sqlite3_errcode(db);
117388   assert( db!=0 || rc==SQLITE_NOMEM );
117389   if( rc==SQLITE_NOMEM ){
117390     sqlite3_close(db);
117391     db = 0;
117392   }else if( rc!=SQLITE_OK ){
117393     db->magic = SQLITE_MAGIC_SICK;
117394   }
117395   *ppDb = db;
117396 #ifdef SQLITE_ENABLE_SQLLOG
117397   if( sqlite3GlobalConfig.xSqllog ){
117398     /* Opening a db handle. Fourth parameter is passed 0. */
117399     void *pArg = sqlite3GlobalConfig.pSqllogArg;
117400     sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
117401   }
117402 #endif
117403   return sqlite3ApiExit(0, rc);
117404 }
117405
117406 /*
117407 ** Open a new database handle.
117408 */
117409 SQLITE_API int sqlite3_open(
117410   const char *zFilename, 
117411   sqlite3 **ppDb 
117412 ){
117413   return openDatabase(zFilename, ppDb,
117414                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
117415 }
117416 SQLITE_API int sqlite3_open_v2(
117417   const char *filename,   /* Database filename (UTF-8) */
117418   sqlite3 **ppDb,         /* OUT: SQLite db handle */
117419   int flags,              /* Flags */
117420   const char *zVfs        /* Name of VFS module to use */
117421 ){
117422   return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
117423 }
117424
117425 #ifndef SQLITE_OMIT_UTF16
117426 /*
117427 ** Open a new database handle.
117428 */
117429 SQLITE_API int sqlite3_open16(
117430   const void *zFilename, 
117431   sqlite3 **ppDb
117432 ){
117433   char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
117434   sqlite3_value *pVal;
117435   int rc;
117436
117437   assert( zFilename );
117438   assert( ppDb );
117439   *ppDb = 0;
117440 #ifndef SQLITE_OMIT_AUTOINIT
117441   rc = sqlite3_initialize();
117442   if( rc ) return rc;
117443 #endif
117444   pVal = sqlite3ValueNew(0);
117445   sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
117446   zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
117447   if( zFilename8 ){
117448     rc = openDatabase(zFilename8, ppDb,
117449                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
117450     assert( *ppDb || rc==SQLITE_NOMEM );
117451     if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
117452       ENC(*ppDb) = SQLITE_UTF16NATIVE;
117453     }
117454   }else{
117455     rc = SQLITE_NOMEM;
117456   }
117457   sqlite3ValueFree(pVal);
117458
117459   return sqlite3ApiExit(0, rc);
117460 }
117461 #endif /* SQLITE_OMIT_UTF16 */
117462
117463 /*
117464 ** Register a new collation sequence with the database handle db.
117465 */
117466 SQLITE_API int sqlite3_create_collation(
117467   sqlite3* db, 
117468   const char *zName, 
117469   int enc, 
117470   void* pCtx,
117471   int(*xCompare)(void*,int,const void*,int,const void*)
117472 ){
117473   int rc;
117474   sqlite3_mutex_enter(db->mutex);
117475   assert( !db->mallocFailed );
117476   rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, 0);
117477   rc = sqlite3ApiExit(db, rc);
117478   sqlite3_mutex_leave(db->mutex);
117479   return rc;
117480 }
117481
117482 /*
117483 ** Register a new collation sequence with the database handle db.
117484 */
117485 SQLITE_API int sqlite3_create_collation_v2(
117486   sqlite3* db, 
117487   const char *zName, 
117488   int enc, 
117489   void* pCtx,
117490   int(*xCompare)(void*,int,const void*,int,const void*),
117491   void(*xDel)(void*)
117492 ){
117493   int rc;
117494   sqlite3_mutex_enter(db->mutex);
117495   assert( !db->mallocFailed );
117496   rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
117497   rc = sqlite3ApiExit(db, rc);
117498   sqlite3_mutex_leave(db->mutex);
117499   return rc;
117500 }
117501
117502 #ifndef SQLITE_OMIT_UTF16
117503 /*
117504 ** Register a new collation sequence with the database handle db.
117505 */
117506 SQLITE_API int sqlite3_create_collation16(
117507   sqlite3* db, 
117508   const void *zName,
117509   int enc, 
117510   void* pCtx,
117511   int(*xCompare)(void*,int,const void*,int,const void*)
117512 ){
117513   int rc = SQLITE_OK;
117514   char *zName8;
117515   sqlite3_mutex_enter(db->mutex);
117516   assert( !db->mallocFailed );
117517   zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
117518   if( zName8 ){
117519     rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
117520     sqlite3DbFree(db, zName8);
117521   }
117522   rc = sqlite3ApiExit(db, rc);
117523   sqlite3_mutex_leave(db->mutex);
117524   return rc;
117525 }
117526 #endif /* SQLITE_OMIT_UTF16 */
117527
117528 /*
117529 ** Register a collation sequence factory callback with the database handle
117530 ** db. Replace any previously installed collation sequence factory.
117531 */
117532 SQLITE_API int sqlite3_collation_needed(
117533   sqlite3 *db, 
117534   void *pCollNeededArg, 
117535   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
117536 ){
117537   sqlite3_mutex_enter(db->mutex);
117538   db->xCollNeeded = xCollNeeded;
117539   db->xCollNeeded16 = 0;
117540   db->pCollNeededArg = pCollNeededArg;
117541   sqlite3_mutex_leave(db->mutex);
117542   return SQLITE_OK;
117543 }
117544
117545 #ifndef SQLITE_OMIT_UTF16
117546 /*
117547 ** Register a collation sequence factory callback with the database handle
117548 ** db. Replace any previously installed collation sequence factory.
117549 */
117550 SQLITE_API int sqlite3_collation_needed16(
117551   sqlite3 *db, 
117552   void *pCollNeededArg, 
117553   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
117554 ){
117555   sqlite3_mutex_enter(db->mutex);
117556   db->xCollNeeded = 0;
117557   db->xCollNeeded16 = xCollNeeded16;
117558   db->pCollNeededArg = pCollNeededArg;
117559   sqlite3_mutex_leave(db->mutex);
117560   return SQLITE_OK;
117561 }
117562 #endif /* SQLITE_OMIT_UTF16 */
117563
117564 #ifndef SQLITE_OMIT_DEPRECATED
117565 /*
117566 ** This function is now an anachronism. It used to be used to recover from a
117567 ** malloc() failure, but SQLite now does this automatically.
117568 */
117569 SQLITE_API int sqlite3_global_recover(void){
117570   return SQLITE_OK;
117571 }
117572 #endif
117573
117574 /*
117575 ** Test to see whether or not the database connection is in autocommit
117576 ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
117577 ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
117578 ** by the next COMMIT or ROLLBACK.
117579 **
117580 ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
117581 */
117582 SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
117583   return db->autoCommit;
117584 }
117585
117586 /*
117587 ** The following routines are subtitutes for constants SQLITE_CORRUPT,
117588 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
117589 ** constants.  They server two purposes:
117590 **
117591 **   1.  Serve as a convenient place to set a breakpoint in a debugger
117592 **       to detect when version error conditions occurs.
117593 **
117594 **   2.  Invoke sqlite3_log() to provide the source code location where
117595 **       a low-level error is first detected.
117596 */
117597 SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
117598   testcase( sqlite3GlobalConfig.xLog!=0 );
117599   sqlite3_log(SQLITE_CORRUPT,
117600               "database corruption at line %d of [%.10s]",
117601               lineno, 20+sqlite3_sourceid());
117602   return SQLITE_CORRUPT;
117603 }
117604 SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
117605   testcase( sqlite3GlobalConfig.xLog!=0 );
117606   sqlite3_log(SQLITE_MISUSE, 
117607               "misuse at line %d of [%.10s]",
117608               lineno, 20+sqlite3_sourceid());
117609   return SQLITE_MISUSE;
117610 }
117611 SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
117612   testcase( sqlite3GlobalConfig.xLog!=0 );
117613   sqlite3_log(SQLITE_CANTOPEN, 
117614               "cannot open file at line %d of [%.10s]",
117615               lineno, 20+sqlite3_sourceid());
117616   return SQLITE_CANTOPEN;
117617 }
117618
117619
117620 #ifndef SQLITE_OMIT_DEPRECATED
117621 /*
117622 ** This is a convenience routine that makes sure that all thread-specific
117623 ** data for this thread has been deallocated.
117624 **
117625 ** SQLite no longer uses thread-specific data so this routine is now a
117626 ** no-op.  It is retained for historical compatibility.
117627 */
117628 SQLITE_API void sqlite3_thread_cleanup(void){
117629 }
117630 #endif
117631
117632 /*
117633 ** Return meta information about a specific column of a database table.
117634 ** See comment in sqlite3.h (sqlite.h.in) for details.
117635 */
117636 #ifdef SQLITE_ENABLE_COLUMN_METADATA
117637 SQLITE_API int sqlite3_table_column_metadata(
117638   sqlite3 *db,                /* Connection handle */
117639   const char *zDbName,        /* Database name or NULL */
117640   const char *zTableName,     /* Table name */
117641   const char *zColumnName,    /* Column name */
117642   char const **pzDataType,    /* OUTPUT: Declared data type */
117643   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
117644   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
117645   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
117646   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
117647 ){
117648   int rc;
117649   char *zErrMsg = 0;
117650   Table *pTab = 0;
117651   Column *pCol = 0;
117652   int iCol;
117653
117654   char const *zDataType = 0;
117655   char const *zCollSeq = 0;
117656   int notnull = 0;
117657   int primarykey = 0;
117658   int autoinc = 0;
117659
117660   /* Ensure the database schema has been loaded */
117661   sqlite3_mutex_enter(db->mutex);
117662   sqlite3BtreeEnterAll(db);
117663   rc = sqlite3Init(db, &zErrMsg);
117664   if( SQLITE_OK!=rc ){
117665     goto error_out;
117666   }
117667
117668   /* Locate the table in question */
117669   pTab = sqlite3FindTable(db, zTableName, zDbName);
117670   if( !pTab || pTab->pSelect ){
117671     pTab = 0;
117672     goto error_out;
117673   }
117674
117675   /* Find the column for which info is requested */
117676   if( sqlite3IsRowid(zColumnName) ){
117677     iCol = pTab->iPKey;
117678     if( iCol>=0 ){
117679       pCol = &pTab->aCol[iCol];
117680     }
117681   }else{
117682     for(iCol=0; iCol<pTab->nCol; iCol++){
117683       pCol = &pTab->aCol[iCol];
117684       if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
117685         break;
117686       }
117687     }
117688     if( iCol==pTab->nCol ){
117689       pTab = 0;
117690       goto error_out;
117691     }
117692   }
117693
117694   /* The following block stores the meta information that will be returned
117695   ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
117696   ** and autoinc. At this point there are two possibilities:
117697   ** 
117698   **     1. The specified column name was rowid", "oid" or "_rowid_" 
117699   **        and there is no explicitly declared IPK column. 
117700   **
117701   **     2. The table is not a view and the column name identified an 
117702   **        explicitly declared column. Copy meta information from *pCol.
117703   */ 
117704   if( pCol ){
117705     zDataType = pCol->zType;
117706     zCollSeq = pCol->zColl;
117707     notnull = pCol->notNull!=0;
117708     primarykey  = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
117709     autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
117710   }else{
117711     zDataType = "INTEGER";
117712     primarykey = 1;
117713   }
117714   if( !zCollSeq ){
117715     zCollSeq = "BINARY";
117716   }
117717
117718 error_out:
117719   sqlite3BtreeLeaveAll(db);
117720
117721   /* Whether the function call succeeded or failed, set the output parameters
117722   ** to whatever their local counterparts contain. If an error did occur,
117723   ** this has the effect of zeroing all output parameters.
117724   */
117725   if( pzDataType ) *pzDataType = zDataType;
117726   if( pzCollSeq ) *pzCollSeq = zCollSeq;
117727   if( pNotNull ) *pNotNull = notnull;
117728   if( pPrimaryKey ) *pPrimaryKey = primarykey;
117729   if( pAutoinc ) *pAutoinc = autoinc;
117730
117731   if( SQLITE_OK==rc && !pTab ){
117732     sqlite3DbFree(db, zErrMsg);
117733     zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
117734         zColumnName);
117735     rc = SQLITE_ERROR;
117736   }
117737   sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
117738   sqlite3DbFree(db, zErrMsg);
117739   rc = sqlite3ApiExit(db, rc);
117740   sqlite3_mutex_leave(db->mutex);
117741   return rc;
117742 }
117743 #endif
117744
117745 /*
117746 ** Sleep for a little while.  Return the amount of time slept.
117747 */
117748 SQLITE_API int sqlite3_sleep(int ms){
117749   sqlite3_vfs *pVfs;
117750   int rc;
117751   pVfs = sqlite3_vfs_find(0);
117752   if( pVfs==0 ) return 0;
117753
117754   /* This function works in milliseconds, but the underlying OsSleep() 
117755   ** API uses microseconds. Hence the 1000's.
117756   */
117757   rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
117758   return rc;
117759 }
117760
117761 /*
117762 ** Enable or disable the extended result codes.
117763 */
117764 SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
117765   sqlite3_mutex_enter(db->mutex);
117766   db->errMask = onoff ? 0xffffffff : 0xff;
117767   sqlite3_mutex_leave(db->mutex);
117768   return SQLITE_OK;
117769 }
117770
117771 /*
117772 ** Invoke the xFileControl method on a particular database.
117773 */
117774 SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
117775   int rc = SQLITE_ERROR;
117776   Btree *pBtree;
117777
117778   sqlite3_mutex_enter(db->mutex);
117779   pBtree = sqlite3DbNameToBtree(db, zDbName);
117780   if( pBtree ){
117781     Pager *pPager;
117782     sqlite3_file *fd;
117783     sqlite3BtreeEnter(pBtree);
117784     pPager = sqlite3BtreePager(pBtree);
117785     assert( pPager!=0 );
117786     fd = sqlite3PagerFile(pPager);
117787     assert( fd!=0 );
117788     if( op==SQLITE_FCNTL_FILE_POINTER ){
117789       *(sqlite3_file**)pArg = fd;
117790       rc = SQLITE_OK;
117791     }else if( fd->pMethods ){
117792       rc = sqlite3OsFileControl(fd, op, pArg);
117793     }else{
117794       rc = SQLITE_NOTFOUND;
117795     }
117796     sqlite3BtreeLeave(pBtree);
117797   }
117798   sqlite3_mutex_leave(db->mutex);
117799   return rc;   
117800 }
117801
117802 /*
117803 ** Interface to the testing logic.
117804 */
117805 SQLITE_API int sqlite3_test_control(int op, ...){
117806   int rc = 0;
117807 #ifndef SQLITE_OMIT_BUILTIN_TEST
117808   va_list ap;
117809   va_start(ap, op);
117810   switch( op ){
117811
117812     /*
117813     ** Save the current state of the PRNG.
117814     */
117815     case SQLITE_TESTCTRL_PRNG_SAVE: {
117816       sqlite3PrngSaveState();
117817       break;
117818     }
117819
117820     /*
117821     ** Restore the state of the PRNG to the last state saved using
117822     ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
117823     ** this verb acts like PRNG_RESET.
117824     */
117825     case SQLITE_TESTCTRL_PRNG_RESTORE: {
117826       sqlite3PrngRestoreState();
117827       break;
117828     }
117829
117830     /*
117831     ** Reset the PRNG back to its uninitialized state.  The next call
117832     ** to sqlite3_randomness() will reseed the PRNG using a single call
117833     ** to the xRandomness method of the default VFS.
117834     */
117835     case SQLITE_TESTCTRL_PRNG_RESET: {
117836       sqlite3PrngResetState();
117837       break;
117838     }
117839
117840     /*
117841     **  sqlite3_test_control(BITVEC_TEST, size, program)
117842     **
117843     ** Run a test against a Bitvec object of size.  The program argument
117844     ** is an array of integers that defines the test.  Return -1 on a
117845     ** memory allocation error, 0 on success, or non-zero for an error.
117846     ** See the sqlite3BitvecBuiltinTest() for additional information.
117847     */
117848     case SQLITE_TESTCTRL_BITVEC_TEST: {
117849       int sz = va_arg(ap, int);
117850       int *aProg = va_arg(ap, int*);
117851       rc = sqlite3BitvecBuiltinTest(sz, aProg);
117852       break;
117853     }
117854
117855     /*
117856     **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
117857     **
117858     ** Register hooks to call to indicate which malloc() failures 
117859     ** are benign.
117860     */
117861     case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
117862       typedef void (*void_function)(void);
117863       void_function xBenignBegin;
117864       void_function xBenignEnd;
117865       xBenignBegin = va_arg(ap, void_function);
117866       xBenignEnd = va_arg(ap, void_function);
117867       sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
117868       break;
117869     }
117870
117871     /*
117872     **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
117873     **
117874     ** Set the PENDING byte to the value in the argument, if X>0.
117875     ** Make no changes if X==0.  Return the value of the pending byte
117876     ** as it existing before this routine was called.
117877     **
117878     ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
117879     ** an incompatible database file format.  Changing the PENDING byte
117880     ** while any database connection is open results in undefined and
117881     ** dileterious behavior.
117882     */
117883     case SQLITE_TESTCTRL_PENDING_BYTE: {
117884       rc = PENDING_BYTE;
117885 #ifndef SQLITE_OMIT_WSD
117886       {
117887         unsigned int newVal = va_arg(ap, unsigned int);
117888         if( newVal ) sqlite3PendingByte = newVal;
117889       }
117890 #endif
117891       break;
117892     }
117893
117894     /*
117895     **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
117896     **
117897     ** This action provides a run-time test to see whether or not
117898     ** assert() was enabled at compile-time.  If X is true and assert()
117899     ** is enabled, then the return value is true.  If X is true and
117900     ** assert() is disabled, then the return value is zero.  If X is
117901     ** false and assert() is enabled, then the assertion fires and the
117902     ** process aborts.  If X is false and assert() is disabled, then the
117903     ** return value is zero.
117904     */
117905     case SQLITE_TESTCTRL_ASSERT: {
117906       volatile int x = 0;
117907       assert( (x = va_arg(ap,int))!=0 );
117908       rc = x;
117909       break;
117910     }
117911
117912
117913     /*
117914     **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
117915     **
117916     ** This action provides a run-time test to see how the ALWAYS and
117917     ** NEVER macros were defined at compile-time.
117918     **
117919     ** The return value is ALWAYS(X).  
117920     **
117921     ** The recommended test is X==2.  If the return value is 2, that means
117922     ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
117923     ** default setting.  If the return value is 1, then ALWAYS() is either
117924     ** hard-coded to true or else it asserts if its argument is false.
117925     ** The first behavior (hard-coded to true) is the case if
117926     ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
117927     ** behavior (assert if the argument to ALWAYS() is false) is the case if
117928     ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
117929     **
117930     ** The run-time test procedure might look something like this:
117931     **
117932     **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
117933     **      // ALWAYS() and NEVER() are no-op pass-through macros
117934     **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
117935     **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
117936     **    }else{
117937     **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
117938     **    }
117939     */
117940     case SQLITE_TESTCTRL_ALWAYS: {
117941       int x = va_arg(ap,int);
117942       rc = ALWAYS(x);
117943       break;
117944     }
117945
117946     /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
117947     **
117948     ** Set the nReserve size to N for the main database on the database
117949     ** connection db.
117950     */
117951     case SQLITE_TESTCTRL_RESERVE: {
117952       sqlite3 *db = va_arg(ap, sqlite3*);
117953       int x = va_arg(ap,int);
117954       sqlite3_mutex_enter(db->mutex);
117955       sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
117956       sqlite3_mutex_leave(db->mutex);
117957       break;
117958     }
117959
117960     /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
117961     **
117962     ** Enable or disable various optimizations for testing purposes.  The 
117963     ** argument N is a bitmask of optimizations to be disabled.  For normal
117964     ** operation N should be 0.  The idea is that a test program (like the
117965     ** SQL Logic Test or SLT test module) can run the same SQL multiple times
117966     ** with various optimizations disabled to verify that the same answer
117967     ** is obtained in every case.
117968     */
117969     case SQLITE_TESTCTRL_OPTIMIZATIONS: {
117970       sqlite3 *db = va_arg(ap, sqlite3*);
117971       db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
117972       break;
117973     }
117974
117975 #ifdef SQLITE_N_KEYWORD
117976     /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
117977     **
117978     ** If zWord is a keyword recognized by the parser, then return the
117979     ** number of keywords.  Or if zWord is not a keyword, return 0.
117980     ** 
117981     ** This test feature is only available in the amalgamation since
117982     ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
117983     ** is built using separate source files.
117984     */
117985     case SQLITE_TESTCTRL_ISKEYWORD: {
117986       const char *zWord = va_arg(ap, const char*);
117987       int n = sqlite3Strlen30(zWord);
117988       rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
117989       break;
117990     }
117991 #endif 
117992
117993     /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
117994     **
117995     ** Pass pFree into sqlite3ScratchFree(). 
117996     ** If sz>0 then allocate a scratch buffer into pNew.  
117997     */
117998     case SQLITE_TESTCTRL_SCRATCHMALLOC: {
117999       void *pFree, **ppNew;
118000       int sz;
118001       sz = va_arg(ap, int);
118002       ppNew = va_arg(ap, void**);
118003       pFree = va_arg(ap, void*);
118004       if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
118005       sqlite3ScratchFree(pFree);
118006       break;
118007     }
118008
118009     /*   sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
118010     **
118011     ** If parameter onoff is non-zero, configure the wrappers so that all
118012     ** subsequent calls to localtime() and variants fail. If onoff is zero,
118013     ** undo this setting.
118014     */
118015     case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
118016       sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
118017       break;
118018     }
118019
118020 #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
118021     /*   sqlite3_test_control(SQLITE_TESTCTRL_EXPLAIN_STMT,
118022     **                        sqlite3_stmt*,const char**);
118023     **
118024     ** If compiled with SQLITE_ENABLE_TREE_EXPLAIN, each sqlite3_stmt holds
118025     ** a string that describes the optimized parse tree.  This test-control
118026     ** returns a pointer to that string.
118027     */
118028     case SQLITE_TESTCTRL_EXPLAIN_STMT: {
118029       sqlite3_stmt *pStmt = va_arg(ap, sqlite3_stmt*);
118030       const char **pzRet = va_arg(ap, const char**);
118031       *pzRet = sqlite3VdbeExplanation((Vdbe*)pStmt);
118032       break;
118033     }
118034 #endif
118035
118036   }
118037   va_end(ap);
118038 #endif /* SQLITE_OMIT_BUILTIN_TEST */
118039   return rc;
118040 }
118041
118042 /*
118043 ** This is a utility routine, useful to VFS implementations, that checks
118044 ** to see if a database file was a URI that contained a specific query 
118045 ** parameter, and if so obtains the value of the query parameter.
118046 **
118047 ** The zFilename argument is the filename pointer passed into the xOpen()
118048 ** method of a VFS implementation.  The zParam argument is the name of the
118049 ** query parameter we seek.  This routine returns the value of the zParam
118050 ** parameter if it exists.  If the parameter does not exist, this routine
118051 ** returns a NULL pointer.
118052 */
118053 SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
118054   if( zFilename==0 ) return 0;
118055   zFilename += sqlite3Strlen30(zFilename) + 1;
118056   while( zFilename[0] ){
118057     int x = strcmp(zFilename, zParam);
118058     zFilename += sqlite3Strlen30(zFilename) + 1;
118059     if( x==0 ) return zFilename;
118060     zFilename += sqlite3Strlen30(zFilename) + 1;
118061   }
118062   return 0;
118063 }
118064
118065 /*
118066 ** Return a boolean value for a query parameter.
118067 */
118068 SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
118069   const char *z = sqlite3_uri_parameter(zFilename, zParam);
118070   bDflt = bDflt!=0;
118071   return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
118072 }
118073
118074 /*
118075 ** Return a 64-bit integer value for a query parameter.
118076 */
118077 SQLITE_API sqlite3_int64 sqlite3_uri_int64(
118078   const char *zFilename,    /* Filename as passed to xOpen */
118079   const char *zParam,       /* URI parameter sought */
118080   sqlite3_int64 bDflt       /* return if parameter is missing */
118081 ){
118082   const char *z = sqlite3_uri_parameter(zFilename, zParam);
118083   sqlite3_int64 v;
118084   if( z && sqlite3Atoi64(z, &v, sqlite3Strlen30(z), SQLITE_UTF8)==SQLITE_OK ){
118085     bDflt = v;
118086   }
118087   return bDflt;
118088 }
118089
118090 /*
118091 ** Return the Btree pointer identified by zDbName.  Return NULL if not found.
118092 */
118093 SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
118094   int i;
118095   for(i=0; i<db->nDb; i++){
118096     if( db->aDb[i].pBt
118097      && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0)
118098     ){
118099       return db->aDb[i].pBt;
118100     }
118101   }
118102   return 0;
118103 }
118104
118105 /*
118106 ** Return the filename of the database associated with a database
118107 ** connection.
118108 */
118109 SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
118110   Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
118111   return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
118112 }
118113
118114 /*
118115 ** Return 1 if database is read-only or 0 if read/write.  Return -1 if
118116 ** no such database exists.
118117 */
118118 SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
118119   Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
118120   return pBt ? sqlite3PagerIsreadonly(sqlite3BtreePager(pBt)) : -1;
118121 }
118122
118123 /************** End of main.c ************************************************/
118124 /************** Begin file notify.c ******************************************/
118125 /*
118126 ** 2009 March 3
118127 **
118128 ** The author disclaims copyright to this source code.  In place of
118129 ** a legal notice, here is a blessing:
118130 **
118131 **    May you do good and not evil.
118132 **    May you find forgiveness for yourself and forgive others.
118133 **    May you share freely, never taking more than you give.
118134 **
118135 *************************************************************************
118136 **
118137 ** This file contains the implementation of the sqlite3_unlock_notify()
118138 ** API method and its associated functionality.
118139 */
118140
118141 /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
118142 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
118143
118144 /*
118145 ** Public interfaces:
118146 **
118147 **   sqlite3ConnectionBlocked()
118148 **   sqlite3ConnectionUnlocked()
118149 **   sqlite3ConnectionClosed()
118150 **   sqlite3_unlock_notify()
118151 */
118152
118153 #define assertMutexHeld() \
118154   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
118155
118156 /*
118157 ** Head of a linked list of all sqlite3 objects created by this process
118158 ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
118159 ** is not NULL. This variable may only accessed while the STATIC_MASTER
118160 ** mutex is held.
118161 */
118162 static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
118163
118164 #ifndef NDEBUG
118165 /*
118166 ** This function is a complex assert() that verifies the following 
118167 ** properties of the blocked connections list:
118168 **
118169 **   1) Each entry in the list has a non-NULL value for either 
118170 **      pUnlockConnection or pBlockingConnection, or both.
118171 **
118172 **   2) All entries in the list that share a common value for 
118173 **      xUnlockNotify are grouped together.
118174 **
118175 **   3) If the argument db is not NULL, then none of the entries in the
118176 **      blocked connections list have pUnlockConnection or pBlockingConnection
118177 **      set to db. This is used when closing connection db.
118178 */
118179 static void checkListProperties(sqlite3 *db){
118180   sqlite3 *p;
118181   for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
118182     int seen = 0;
118183     sqlite3 *p2;
118184
118185     /* Verify property (1) */
118186     assert( p->pUnlockConnection || p->pBlockingConnection );
118187
118188     /* Verify property (2) */
118189     for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
118190       if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
118191       assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
118192       assert( db==0 || p->pUnlockConnection!=db );
118193       assert( db==0 || p->pBlockingConnection!=db );
118194     }
118195   }
118196 }
118197 #else
118198 # define checkListProperties(x)
118199 #endif
118200
118201 /*
118202 ** Remove connection db from the blocked connections list. If connection
118203 ** db is not currently a part of the list, this function is a no-op.
118204 */
118205 static void removeFromBlockedList(sqlite3 *db){
118206   sqlite3 **pp;
118207   assertMutexHeld();
118208   for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
118209     if( *pp==db ){
118210       *pp = (*pp)->pNextBlocked;
118211       break;
118212     }
118213   }
118214 }
118215
118216 /*
118217 ** Add connection db to the blocked connections list. It is assumed
118218 ** that it is not already a part of the list.
118219 */
118220 static void addToBlockedList(sqlite3 *db){
118221   sqlite3 **pp;
118222   assertMutexHeld();
118223   for(
118224     pp=&sqlite3BlockedList; 
118225     *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify; 
118226     pp=&(*pp)->pNextBlocked
118227   );
118228   db->pNextBlocked = *pp;
118229   *pp = db;
118230 }
118231
118232 /*
118233 ** Obtain the STATIC_MASTER mutex.
118234 */
118235 static void enterMutex(void){
118236   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
118237   checkListProperties(0);
118238 }
118239
118240 /*
118241 ** Release the STATIC_MASTER mutex.
118242 */
118243 static void leaveMutex(void){
118244   assertMutexHeld();
118245   checkListProperties(0);
118246   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
118247 }
118248
118249 /*
118250 ** Register an unlock-notify callback.
118251 **
118252 ** This is called after connection "db" has attempted some operation
118253 ** but has received an SQLITE_LOCKED error because another connection
118254 ** (call it pOther) in the same process was busy using the same shared
118255 ** cache.  pOther is found by looking at db->pBlockingConnection.
118256 **
118257 ** If there is no blocking connection, the callback is invoked immediately,
118258 ** before this routine returns.
118259 **
118260 ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
118261 ** a deadlock.
118262 **
118263 ** Otherwise, make arrangements to invoke xNotify when pOther drops
118264 ** its locks.
118265 **
118266 ** Each call to this routine overrides any prior callbacks registered
118267 ** on the same "db".  If xNotify==0 then any prior callbacks are immediately
118268 ** cancelled.
118269 */
118270 SQLITE_API int sqlite3_unlock_notify(
118271   sqlite3 *db,
118272   void (*xNotify)(void **, int),
118273   void *pArg
118274 ){
118275   int rc = SQLITE_OK;
118276
118277   sqlite3_mutex_enter(db->mutex);
118278   enterMutex();
118279
118280   if( xNotify==0 ){
118281     removeFromBlockedList(db);
118282     db->pBlockingConnection = 0;
118283     db->pUnlockConnection = 0;
118284     db->xUnlockNotify = 0;
118285     db->pUnlockArg = 0;
118286   }else if( 0==db->pBlockingConnection ){
118287     /* The blocking transaction has been concluded. Or there never was a 
118288     ** blocking transaction. In either case, invoke the notify callback
118289     ** immediately. 
118290     */
118291     xNotify(&pArg, 1);
118292   }else{
118293     sqlite3 *p;
118294
118295     for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
118296     if( p ){
118297       rc = SQLITE_LOCKED;              /* Deadlock detected. */
118298     }else{
118299       db->pUnlockConnection = db->pBlockingConnection;
118300       db->xUnlockNotify = xNotify;
118301       db->pUnlockArg = pArg;
118302       removeFromBlockedList(db);
118303       addToBlockedList(db);
118304     }
118305   }
118306
118307   leaveMutex();
118308   assert( !db->mallocFailed );
118309   sqlite3Error(db, rc, (rc?"database is deadlocked":0));
118310   sqlite3_mutex_leave(db->mutex);
118311   return rc;
118312 }
118313
118314 /*
118315 ** This function is called while stepping or preparing a statement 
118316 ** associated with connection db. The operation will return SQLITE_LOCKED
118317 ** to the user because it requires a lock that will not be available
118318 ** until connection pBlocker concludes its current transaction.
118319 */
118320 SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
118321   enterMutex();
118322   if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
118323     addToBlockedList(db);
118324   }
118325   db->pBlockingConnection = pBlocker;
118326   leaveMutex();
118327 }
118328
118329 /*
118330 ** This function is called when
118331 ** the transaction opened by database db has just finished. Locks held 
118332 ** by database connection db have been released.
118333 **
118334 ** This function loops through each entry in the blocked connections
118335 ** list and does the following:
118336 **
118337 **   1) If the sqlite3.pBlockingConnection member of a list entry is
118338 **      set to db, then set pBlockingConnection=0.
118339 **
118340 **   2) If the sqlite3.pUnlockConnection member of a list entry is
118341 **      set to db, then invoke the configured unlock-notify callback and
118342 **      set pUnlockConnection=0.
118343 **
118344 **   3) If the two steps above mean that pBlockingConnection==0 and
118345 **      pUnlockConnection==0, remove the entry from the blocked connections
118346 **      list.
118347 */
118348 SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
118349   void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
118350   int nArg = 0;                            /* Number of entries in aArg[] */
118351   sqlite3 **pp;                            /* Iterator variable */
118352   void **aArg;               /* Arguments to the unlock callback */
118353   void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
118354   void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
118355
118356   aArg = aStatic;
118357   enterMutex();         /* Enter STATIC_MASTER mutex */
118358
118359   /* This loop runs once for each entry in the blocked-connections list. */
118360   for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
118361     sqlite3 *p = *pp;
118362
118363     /* Step 1. */
118364     if( p->pBlockingConnection==db ){
118365       p->pBlockingConnection = 0;
118366     }
118367
118368     /* Step 2. */
118369     if( p->pUnlockConnection==db ){
118370       assert( p->xUnlockNotify );
118371       if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
118372         xUnlockNotify(aArg, nArg);
118373         nArg = 0;
118374       }
118375
118376       sqlite3BeginBenignMalloc();
118377       assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
118378       assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
118379       if( (!aDyn && nArg==(int)ArraySize(aStatic))
118380        || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
118381       ){
118382         /* The aArg[] array needs to grow. */
118383         void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
118384         if( pNew ){
118385           memcpy(pNew, aArg, nArg*sizeof(void *));
118386           sqlite3_free(aDyn);
118387           aDyn = aArg = pNew;
118388         }else{
118389           /* This occurs when the array of context pointers that need to
118390           ** be passed to the unlock-notify callback is larger than the
118391           ** aStatic[] array allocated on the stack and the attempt to 
118392           ** allocate a larger array from the heap has failed.
118393           **
118394           ** This is a difficult situation to handle. Returning an error
118395           ** code to the caller is insufficient, as even if an error code
118396           ** is returned the transaction on connection db will still be
118397           ** closed and the unlock-notify callbacks on blocked connections
118398           ** will go unissued. This might cause the application to wait
118399           ** indefinitely for an unlock-notify callback that will never 
118400           ** arrive.
118401           **
118402           ** Instead, invoke the unlock-notify callback with the context
118403           ** array already accumulated. We can then clear the array and
118404           ** begin accumulating any further context pointers without 
118405           ** requiring any dynamic allocation. This is sub-optimal because
118406           ** it means that instead of one callback with a large array of
118407           ** context pointers the application will receive two or more
118408           ** callbacks with smaller arrays of context pointers, which will
118409           ** reduce the applications ability to prioritize multiple 
118410           ** connections. But it is the best that can be done under the
118411           ** circumstances.
118412           */
118413           xUnlockNotify(aArg, nArg);
118414           nArg = 0;
118415         }
118416       }
118417       sqlite3EndBenignMalloc();
118418
118419       aArg[nArg++] = p->pUnlockArg;
118420       xUnlockNotify = p->xUnlockNotify;
118421       p->pUnlockConnection = 0;
118422       p->xUnlockNotify = 0;
118423       p->pUnlockArg = 0;
118424     }
118425
118426     /* Step 3. */
118427     if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
118428       /* Remove connection p from the blocked connections list. */
118429       *pp = p->pNextBlocked;
118430       p->pNextBlocked = 0;
118431     }else{
118432       pp = &p->pNextBlocked;
118433     }
118434   }
118435
118436   if( nArg!=0 ){
118437     xUnlockNotify(aArg, nArg);
118438   }
118439   sqlite3_free(aDyn);
118440   leaveMutex();         /* Leave STATIC_MASTER mutex */
118441 }
118442
118443 /*
118444 ** This is called when the database connection passed as an argument is 
118445 ** being closed. The connection is removed from the blocked list.
118446 */
118447 SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
118448   sqlite3ConnectionUnlocked(db);
118449   enterMutex();
118450   removeFromBlockedList(db);
118451   checkListProperties(db);
118452   leaveMutex();
118453 }
118454 #endif
118455
118456 /************** End of notify.c **********************************************/
118457 /************** Begin file fts3.c ********************************************/
118458 /*
118459 ** 2006 Oct 10
118460 **
118461 ** The author disclaims copyright to this source code.  In place of
118462 ** a legal notice, here is a blessing:
118463 **
118464 **    May you do good and not evil.
118465 **    May you find forgiveness for yourself and forgive others.
118466 **    May you share freely, never taking more than you give.
118467 **
118468 ******************************************************************************
118469 **
118470 ** This is an SQLite module implementing full-text search.
118471 */
118472
118473 /*
118474 ** The code in this file is only compiled if:
118475 **
118476 **     * The FTS3 module is being built as an extension
118477 **       (in which case SQLITE_CORE is not defined), or
118478 **
118479 **     * The FTS3 module is being built into the core of
118480 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
118481 */
118482
118483 /* The full-text index is stored in a series of b+tree (-like)
118484 ** structures called segments which map terms to doclists.  The
118485 ** structures are like b+trees in layout, but are constructed from the
118486 ** bottom up in optimal fashion and are not updatable.  Since trees
118487 ** are built from the bottom up, things will be described from the
118488 ** bottom up.
118489 **
118490 **
118491 **** Varints ****
118492 ** The basic unit of encoding is a variable-length integer called a
118493 ** varint.  We encode variable-length integers in little-endian order
118494 ** using seven bits * per byte as follows:
118495 **
118496 ** KEY:
118497 **         A = 0xxxxxxx    7 bits of data and one flag bit
118498 **         B = 1xxxxxxx    7 bits of data and one flag bit
118499 **
118500 **  7 bits - A
118501 ** 14 bits - BA
118502 ** 21 bits - BBA
118503 ** and so on.
118504 **
118505 ** This is similar in concept to how sqlite encodes "varints" but
118506 ** the encoding is not the same.  SQLite varints are big-endian
118507 ** are are limited to 9 bytes in length whereas FTS3 varints are
118508 ** little-endian and can be up to 10 bytes in length (in theory).
118509 **
118510 ** Example encodings:
118511 **
118512 **     1:    0x01
118513 **   127:    0x7f
118514 **   128:    0x81 0x00
118515 **
118516 **
118517 **** Document lists ****
118518 ** A doclist (document list) holds a docid-sorted list of hits for a
118519 ** given term.  Doclists hold docids and associated token positions.
118520 ** A docid is the unique integer identifier for a single document.
118521 ** A position is the index of a word within the document.  The first 
118522 ** word of the document has a position of 0.
118523 **
118524 ** FTS3 used to optionally store character offsets using a compile-time
118525 ** option.  But that functionality is no longer supported.
118526 **
118527 ** A doclist is stored like this:
118528 **
118529 ** array {
118530 **   varint docid;          (delta from previous doclist)
118531 **   array {                (position list for column 0)
118532 **     varint position;     (2 more than the delta from previous position)
118533 **   }
118534 **   array {
118535 **     varint POS_COLUMN;   (marks start of position list for new column)
118536 **     varint column;       (index of new column)
118537 **     array {
118538 **       varint position;   (2 more than the delta from previous position)
118539 **     }
118540 **   }
118541 **   varint POS_END;        (marks end of positions for this document.
118542 ** }
118543 **
118544 ** Here, array { X } means zero or more occurrences of X, adjacent in
118545 ** memory.  A "position" is an index of a token in the token stream
118546 ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur 
118547 ** in the same logical place as the position element, and act as sentinals
118548 ** ending a position list array.  POS_END is 0.  POS_COLUMN is 1.
118549 ** The positions numbers are not stored literally but rather as two more
118550 ** than the difference from the prior position, or the just the position plus
118551 ** 2 for the first position.  Example:
118552 **
118553 **   label:       A B C D E  F  G H   I  J K
118554 **   value:     123 5 9 1 1 14 35 0 234 72 0
118555 **
118556 ** The 123 value is the first docid.  For column zero in this document
118557 ** there are two matches at positions 3 and 10 (5-2 and 9-2+3).  The 1
118558 ** at D signals the start of a new column; the 1 at E indicates that the
118559 ** new column is column number 1.  There are two positions at 12 and 45
118560 ** (14-2 and 35-2+12).  The 0 at H indicate the end-of-document.  The
118561 ** 234 at I is the delta to next docid (357).  It has one position 70
118562 ** (72-2) and then terminates with the 0 at K.
118563 **
118564 ** A "position-list" is the list of positions for multiple columns for
118565 ** a single docid.  A "column-list" is the set of positions for a single
118566 ** column.  Hence, a position-list consists of one or more column-lists,
118567 ** a document record consists of a docid followed by a position-list and
118568 ** a doclist consists of one or more document records.
118569 **
118570 ** A bare doclist omits the position information, becoming an 
118571 ** array of varint-encoded docids.
118572 **
118573 **** Segment leaf nodes ****
118574 ** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
118575 ** nodes are written using LeafWriter, and read using LeafReader (to
118576 ** iterate through a single leaf node's data) and LeavesReader (to
118577 ** iterate through a segment's entire leaf layer).  Leaf nodes have
118578 ** the format:
118579 **
118580 ** varint iHeight;             (height from leaf level, always 0)
118581 ** varint nTerm;               (length of first term)
118582 ** char pTerm[nTerm];          (content of first term)
118583 ** varint nDoclist;            (length of term's associated doclist)
118584 ** char pDoclist[nDoclist];    (content of doclist)
118585 ** array {
118586 **                             (further terms are delta-encoded)
118587 **   varint nPrefix;           (length of prefix shared with previous term)
118588 **   varint nSuffix;           (length of unshared suffix)
118589 **   char pTermSuffix[nSuffix];(unshared suffix of next term)
118590 **   varint nDoclist;          (length of term's associated doclist)
118591 **   char pDoclist[nDoclist];  (content of doclist)
118592 ** }
118593 **
118594 ** Here, array { X } means zero or more occurrences of X, adjacent in
118595 ** memory.
118596 **
118597 ** Leaf nodes are broken into blocks which are stored contiguously in
118598 ** the %_segments table in sorted order.  This means that when the end
118599 ** of a node is reached, the next term is in the node with the next
118600 ** greater node id.
118601 **
118602 ** New data is spilled to a new leaf node when the current node
118603 ** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
118604 ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
118605 ** node (a leaf node with a single term and doclist).  The goal of
118606 ** these settings is to pack together groups of small doclists while
118607 ** making it efficient to directly access large doclists.  The
118608 ** assumption is that large doclists represent terms which are more
118609 ** likely to be query targets.
118610 **
118611 ** TODO(shess) It may be useful for blocking decisions to be more
118612 ** dynamic.  For instance, it may make more sense to have a 2.5k leaf
118613 ** node rather than splitting into 2k and .5k nodes.  My intuition is
118614 ** that this might extend through 2x or 4x the pagesize.
118615 **
118616 **
118617 **** Segment interior nodes ****
118618 ** Segment interior nodes store blockids for subtree nodes and terms
118619 ** to describe what data is stored by the each subtree.  Interior
118620 ** nodes are written using InteriorWriter, and read using
118621 ** InteriorReader.  InteriorWriters are created as needed when
118622 ** SegmentWriter creates new leaf nodes, or when an interior node
118623 ** itself grows too big and must be split.  The format of interior
118624 ** nodes:
118625 **
118626 ** varint iHeight;           (height from leaf level, always >0)
118627 ** varint iBlockid;          (block id of node's leftmost subtree)
118628 ** optional {
118629 **   varint nTerm;           (length of first term)
118630 **   char pTerm[nTerm];      (content of first term)
118631 **   array {
118632 **                                (further terms are delta-encoded)
118633 **     varint nPrefix;            (length of shared prefix with previous term)
118634 **     varint nSuffix;            (length of unshared suffix)
118635 **     char pTermSuffix[nSuffix]; (unshared suffix of next term)
118636 **   }
118637 ** }
118638 **
118639 ** Here, optional { X } means an optional element, while array { X }
118640 ** means zero or more occurrences of X, adjacent in memory.
118641 **
118642 ** An interior node encodes n terms separating n+1 subtrees.  The
118643 ** subtree blocks are contiguous, so only the first subtree's blockid
118644 ** is encoded.  The subtree at iBlockid will contain all terms less
118645 ** than the first term encoded (or all terms if no term is encoded).
118646 ** Otherwise, for terms greater than or equal to pTerm[i] but less
118647 ** than pTerm[i+1], the subtree for that term will be rooted at
118648 ** iBlockid+i.  Interior nodes only store enough term data to
118649 ** distinguish adjacent children (if the rightmost term of the left
118650 ** child is "something", and the leftmost term of the right child is
118651 ** "wicked", only "w" is stored).
118652 **
118653 ** New data is spilled to a new interior node at the same height when
118654 ** the current node exceeds INTERIOR_MAX bytes (default 2048).
118655 ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
118656 ** interior nodes and making the tree too skinny.  The interior nodes
118657 ** at a given height are naturally tracked by interior nodes at
118658 ** height+1, and so on.
118659 **
118660 **
118661 **** Segment directory ****
118662 ** The segment directory in table %_segdir stores meta-information for
118663 ** merging and deleting segments, and also the root node of the
118664 ** segment's tree.
118665 **
118666 ** The root node is the top node of the segment's tree after encoding
118667 ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
118668 ** This could be either a leaf node or an interior node.  If the top
118669 ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
118670 ** and a new root interior node is generated (which should always fit
118671 ** within ROOT_MAX because it only needs space for 2 varints, the
118672 ** height and the blockid of the previous root).
118673 **
118674 ** The meta-information in the segment directory is:
118675 **   level               - segment level (see below)
118676 **   idx                 - index within level
118677 **                       - (level,idx uniquely identify a segment)
118678 **   start_block         - first leaf node
118679 **   leaves_end_block    - last leaf node
118680 **   end_block           - last block (including interior nodes)
118681 **   root                - contents of root node
118682 **
118683 ** If the root node is a leaf node, then start_block,
118684 ** leaves_end_block, and end_block are all 0.
118685 **
118686 **
118687 **** Segment merging ****
118688 ** To amortize update costs, segments are grouped into levels and
118689 ** merged in batches.  Each increase in level represents exponentially
118690 ** more documents.
118691 **
118692 ** New documents (actually, document updates) are tokenized and
118693 ** written individually (using LeafWriter) to a level 0 segment, with
118694 ** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
118695 ** level 0 segments are merged into a single level 1 segment.  Level 1
118696 ** is populated like level 0, and eventually MERGE_COUNT level 1
118697 ** segments are merged to a single level 2 segment (representing
118698 ** MERGE_COUNT^2 updates), and so on.
118699 **
118700 ** A segment merge traverses all segments at a given level in
118701 ** parallel, performing a straightforward sorted merge.  Since segment
118702 ** leaf nodes are written in to the %_segments table in order, this
118703 ** merge traverses the underlying sqlite disk structures efficiently.
118704 ** After the merge, all segment blocks from the merged level are
118705 ** deleted.
118706 **
118707 ** MERGE_COUNT controls how often we merge segments.  16 seems to be
118708 ** somewhat of a sweet spot for insertion performance.  32 and 64 show
118709 ** very similar performance numbers to 16 on insertion, though they're
118710 ** a tiny bit slower (perhaps due to more overhead in merge-time
118711 ** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
118712 ** 16, 2 about 66% slower than 16.
118713 **
118714 ** At query time, high MERGE_COUNT increases the number of segments
118715 ** which need to be scanned and merged.  For instance, with 100k docs
118716 ** inserted:
118717 **
118718 **    MERGE_COUNT   segments
118719 **       16           25
118720 **        8           12
118721 **        4           10
118722 **        2            6
118723 **
118724 ** This appears to have only a moderate impact on queries for very
118725 ** frequent terms (which are somewhat dominated by segment merge
118726 ** costs), and infrequent and non-existent terms still seem to be fast
118727 ** even with many segments.
118728 **
118729 ** TODO(shess) That said, it would be nice to have a better query-side
118730 ** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
118731 ** optimizations to things like doclist merging will swing the sweet
118732 ** spot around.
118733 **
118734 **
118735 **
118736 **** Handling of deletions and updates ****
118737 ** Since we're using a segmented structure, with no docid-oriented
118738 ** index into the term index, we clearly cannot simply update the term
118739 ** index when a document is deleted or updated.  For deletions, we
118740 ** write an empty doclist (varint(docid) varint(POS_END)), for updates
118741 ** we simply write the new doclist.  Segment merges overwrite older
118742 ** data for a particular docid with newer data, so deletes or updates
118743 ** will eventually overtake the earlier data and knock it out.  The
118744 ** query logic likewise merges doclists so that newer data knocks out
118745 ** older data.
118746 */
118747
118748 /************** Include fts3Int.h in the middle of fts3.c ********************/
118749 /************** Begin file fts3Int.h *****************************************/
118750 /*
118751 ** 2009 Nov 12
118752 **
118753 ** The author disclaims copyright to this source code.  In place of
118754 ** a legal notice, here is a blessing:
118755 **
118756 **    May you do good and not evil.
118757 **    May you find forgiveness for yourself and forgive others.
118758 **    May you share freely, never taking more than you give.
118759 **
118760 ******************************************************************************
118761 **
118762 */
118763 #ifndef _FTSINT_H
118764 #define _FTSINT_H
118765
118766 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
118767 # define NDEBUG 1
118768 #endif
118769
118770 /*
118771 ** FTS4 is really an extension for FTS3.  It is enabled using the
118772 ** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
118773 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
118774 */
118775 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
118776 # define SQLITE_ENABLE_FTS3
118777 #endif
118778
118779 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
118780
118781 /* If not building as part of the core, include sqlite3ext.h. */
118782 #ifndef SQLITE_CORE
118783 SQLITE_API extern const sqlite3_api_routines *sqlite3_api;
118784 #endif
118785
118786 /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
118787 /************** Begin file fts3_tokenizer.h **********************************/
118788 /*
118789 ** 2006 July 10
118790 **
118791 ** The author disclaims copyright to this source code.
118792 **
118793 *************************************************************************
118794 ** Defines the interface to tokenizers used by fulltext-search.  There
118795 ** are three basic components:
118796 **
118797 ** sqlite3_tokenizer_module is a singleton defining the tokenizer
118798 ** interface functions.  This is essentially the class structure for
118799 ** tokenizers.
118800 **
118801 ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
118802 ** including customization information defined at creation time.
118803 **
118804 ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
118805 ** tokens from a particular input.
118806 */
118807 #ifndef _FTS3_TOKENIZER_H_
118808 #define _FTS3_TOKENIZER_H_
118809
118810 /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
118811 ** If tokenizers are to be allowed to call sqlite3_*() functions, then
118812 ** we will need a way to register the API consistently.
118813 */
118814
118815 /*
118816 ** Structures used by the tokenizer interface. When a new tokenizer
118817 ** implementation is registered, the caller provides a pointer to
118818 ** an sqlite3_tokenizer_module containing pointers to the callback
118819 ** functions that make up an implementation.
118820 **
118821 ** When an fts3 table is created, it passes any arguments passed to
118822 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
118823 ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
118824 ** implementation. The xCreate() function in turn returns an 
118825 ** sqlite3_tokenizer structure representing the specific tokenizer to
118826 ** be used for the fts3 table (customized by the tokenizer clause arguments).
118827 **
118828 ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
118829 ** method is called. It returns an sqlite3_tokenizer_cursor object
118830 ** that may be used to tokenize a specific input buffer based on
118831 ** the tokenization rules supplied by a specific sqlite3_tokenizer
118832 ** object.
118833 */
118834 typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
118835 typedef struct sqlite3_tokenizer sqlite3_tokenizer;
118836 typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
118837
118838 struct sqlite3_tokenizer_module {
118839
118840   /*
118841   ** Structure version. Should always be set to 0 or 1.
118842   */
118843   int iVersion;
118844
118845   /*
118846   ** Create a new tokenizer. The values in the argv[] array are the
118847   ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
118848   ** TABLE statement that created the fts3 table. For example, if
118849   ** the following SQL is executed:
118850   **
118851   **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
118852   **
118853   ** then argc is set to 2, and the argv[] array contains pointers
118854   ** to the strings "arg1" and "arg2".
118855   **
118856   ** This method should return either SQLITE_OK (0), or an SQLite error 
118857   ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
118858   ** to point at the newly created tokenizer structure. The generic
118859   ** sqlite3_tokenizer.pModule variable should not be initialized by
118860   ** this callback. The caller will do so.
118861   */
118862   int (*xCreate)(
118863     int argc,                           /* Size of argv array */
118864     const char *const*argv,             /* Tokenizer argument strings */
118865     sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
118866   );
118867
118868   /*
118869   ** Destroy an existing tokenizer. The fts3 module calls this method
118870   ** exactly once for each successful call to xCreate().
118871   */
118872   int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
118873
118874   /*
118875   ** Create a tokenizer cursor to tokenize an input buffer. The caller
118876   ** is responsible for ensuring that the input buffer remains valid
118877   ** until the cursor is closed (using the xClose() method). 
118878   */
118879   int (*xOpen)(
118880     sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
118881     const char *pInput, int nBytes,      /* Input buffer */
118882     sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
118883   );
118884
118885   /*
118886   ** Destroy an existing tokenizer cursor. The fts3 module calls this 
118887   ** method exactly once for each successful call to xOpen().
118888   */
118889   int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
118890
118891   /*
118892   ** Retrieve the next token from the tokenizer cursor pCursor. This
118893   ** method should either return SQLITE_OK and set the values of the
118894   ** "OUT" variables identified below, or SQLITE_DONE to indicate that
118895   ** the end of the buffer has been reached, or an SQLite error code.
118896   **
118897   ** *ppToken should be set to point at a buffer containing the 
118898   ** normalized version of the token (i.e. after any case-folding and/or
118899   ** stemming has been performed). *pnBytes should be set to the length
118900   ** of this buffer in bytes. The input text that generated the token is
118901   ** identified by the byte offsets returned in *piStartOffset and
118902   ** *piEndOffset. *piStartOffset should be set to the index of the first
118903   ** byte of the token in the input buffer. *piEndOffset should be set
118904   ** to the index of the first byte just past the end of the token in
118905   ** the input buffer.
118906   **
118907   ** The buffer *ppToken is set to point at is managed by the tokenizer
118908   ** implementation. It is only required to be valid until the next call
118909   ** to xNext() or xClose(). 
118910   */
118911   /* TODO(shess) current implementation requires pInput to be
118912   ** nul-terminated.  This should either be fixed, or pInput/nBytes
118913   ** should be converted to zInput.
118914   */
118915   int (*xNext)(
118916     sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
118917     const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
118918     int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
118919     int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
118920     int *piPosition      /* OUT: Number of tokens returned before this one */
118921   );
118922
118923   /***********************************************************************
118924   ** Methods below this point are only available if iVersion>=1.
118925   */
118926
118927   /* 
118928   ** Configure the language id of a tokenizer cursor.
118929   */
118930   int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
118931 };
118932
118933 struct sqlite3_tokenizer {
118934   const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
118935   /* Tokenizer implementations will typically add additional fields */
118936 };
118937
118938 struct sqlite3_tokenizer_cursor {
118939   sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
118940   /* Tokenizer implementations will typically add additional fields */
118941 };
118942
118943 int fts3_global_term_cnt(int iTerm, int iCol);
118944 int fts3_term_cnt(int iTerm, int iCol);
118945
118946
118947 #endif /* _FTS3_TOKENIZER_H_ */
118948
118949 /************** End of fts3_tokenizer.h **************************************/
118950 /************** Continuing where we left off in fts3Int.h ********************/
118951 /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
118952 /************** Begin file fts3_hash.h ***************************************/
118953 /*
118954 ** 2001 September 22
118955 **
118956 ** The author disclaims copyright to this source code.  In place of
118957 ** a legal notice, here is a blessing:
118958 **
118959 **    May you do good and not evil.
118960 **    May you find forgiveness for yourself and forgive others.
118961 **    May you share freely, never taking more than you give.
118962 **
118963 *************************************************************************
118964 ** This is the header file for the generic hash-table implementation
118965 ** used in SQLite.  We've modified it slightly to serve as a standalone
118966 ** hash table implementation for the full-text indexing module.
118967 **
118968 */
118969 #ifndef _FTS3_HASH_H_
118970 #define _FTS3_HASH_H_
118971
118972 /* Forward declarations of structures. */
118973 typedef struct Fts3Hash Fts3Hash;
118974 typedef struct Fts3HashElem Fts3HashElem;
118975
118976 /* A complete hash table is an instance of the following structure.
118977 ** The internals of this structure are intended to be opaque -- client
118978 ** code should not attempt to access or modify the fields of this structure
118979 ** directly.  Change this structure only by using the routines below.
118980 ** However, many of the "procedures" and "functions" for modifying and
118981 ** accessing this structure are really macros, so we can't really make
118982 ** this structure opaque.
118983 */
118984 struct Fts3Hash {
118985   char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
118986   char copyKey;           /* True if copy of key made on insert */
118987   int count;              /* Number of entries in this table */
118988   Fts3HashElem *first;    /* The first element of the array */
118989   int htsize;             /* Number of buckets in the hash table */
118990   struct _fts3ht {        /* the hash table */
118991     int count;               /* Number of entries with this hash */
118992     Fts3HashElem *chain;     /* Pointer to first entry with this hash */
118993   } *ht;
118994 };
118995
118996 /* Each element in the hash table is an instance of the following 
118997 ** structure.  All elements are stored on a single doubly-linked list.
118998 **
118999 ** Again, this structure is intended to be opaque, but it can't really
119000 ** be opaque because it is used by macros.
119001 */
119002 struct Fts3HashElem {
119003   Fts3HashElem *next, *prev; /* Next and previous elements in the table */
119004   void *data;                /* Data associated with this element */
119005   void *pKey; int nKey;      /* Key associated with this element */
119006 };
119007
119008 /*
119009 ** There are 2 different modes of operation for a hash table:
119010 **
119011 **   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
119012 **                           (including the null-terminator, if any).  Case
119013 **                           is respected in comparisons.
119014 **
119015 **   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long. 
119016 **                           memcmp() is used to compare keys.
119017 **
119018 ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.  
119019 */
119020 #define FTS3_HASH_STRING    1
119021 #define FTS3_HASH_BINARY    2
119022
119023 /*
119024 ** Access routines.  To delete, insert a NULL pointer.
119025 */
119026 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
119027 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
119028 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
119029 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
119030 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
119031
119032 /*
119033 ** Shorthand for the functions above
119034 */
119035 #define fts3HashInit     sqlite3Fts3HashInit
119036 #define fts3HashInsert   sqlite3Fts3HashInsert
119037 #define fts3HashFind     sqlite3Fts3HashFind
119038 #define fts3HashClear    sqlite3Fts3HashClear
119039 #define fts3HashFindElem sqlite3Fts3HashFindElem
119040
119041 /*
119042 ** Macros for looping over all elements of a hash table.  The idiom is
119043 ** like this:
119044 **
119045 **   Fts3Hash h;
119046 **   Fts3HashElem *p;
119047 **   ...
119048 **   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
119049 **     SomeStructure *pData = fts3HashData(p);
119050 **     // do something with pData
119051 **   }
119052 */
119053 #define fts3HashFirst(H)  ((H)->first)
119054 #define fts3HashNext(E)   ((E)->next)
119055 #define fts3HashData(E)   ((E)->data)
119056 #define fts3HashKey(E)    ((E)->pKey)
119057 #define fts3HashKeysize(E) ((E)->nKey)
119058
119059 /*
119060 ** Number of entries in a hash table
119061 */
119062 #define fts3HashCount(H)  ((H)->count)
119063
119064 #endif /* _FTS3_HASH_H_ */
119065
119066 /************** End of fts3_hash.h *******************************************/
119067 /************** Continuing where we left off in fts3Int.h ********************/
119068
119069 /*
119070 ** This constant controls how often segments are merged. Once there are
119071 ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
119072 ** segment of level N+1.
119073 */
119074 #define FTS3_MERGE_COUNT 16
119075
119076 /*
119077 ** This is the maximum amount of data (in bytes) to store in the 
119078 ** Fts3Table.pendingTerms hash table. Normally, the hash table is
119079 ** populated as documents are inserted/updated/deleted in a transaction
119080 ** and used to create a new segment when the transaction is committed.
119081 ** However if this limit is reached midway through a transaction, a new 
119082 ** segment is created and the hash table cleared immediately.
119083 */
119084 #define FTS3_MAX_PENDING_DATA (1*1024*1024)
119085
119086 /*
119087 ** Macro to return the number of elements in an array. SQLite has a
119088 ** similar macro called ArraySize(). Use a different name to avoid
119089 ** a collision when building an amalgamation with built-in FTS3.
119090 */
119091 #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
119092
119093
119094 #ifndef MIN
119095 # define MIN(x,y) ((x)<(y)?(x):(y))
119096 #endif
119097 #ifndef MAX
119098 # define MAX(x,y) ((x)>(y)?(x):(y))
119099 #endif
119100
119101 /*
119102 ** Maximum length of a varint encoded integer. The varint format is different
119103 ** from that used by SQLite, so the maximum length is 10, not 9.
119104 */
119105 #define FTS3_VARINT_MAX 10
119106
119107 /*
119108 ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
119109 ** in the document set and zero or more prefix indexes. All indexes are stored
119110 ** as one or more b+-trees in the %_segments and %_segdir tables. 
119111 **
119112 ** It is possible to determine which index a b+-tree belongs to based on the
119113 ** value stored in the "%_segdir.level" column. Given this value L, the index
119114 ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
119115 ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
119116 ** between 1024 and 2047 to index 1, and so on.
119117 **
119118 ** It is considered impossible for an index to use more than 1024 levels. In 
119119 ** theory though this may happen, but only after at least 
119120 ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
119121 */
119122 #define FTS3_SEGDIR_MAXLEVEL      1024
119123 #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
119124
119125 /*
119126 ** The testcase() macro is only used by the amalgamation.  If undefined,
119127 ** make it a no-op.
119128 */
119129 #ifndef testcase
119130 # define testcase(X)
119131 #endif
119132
119133 /*
119134 ** Terminator values for position-lists and column-lists.
119135 */
119136 #define POS_COLUMN  (1)     /* Column-list terminator */
119137 #define POS_END     (0)     /* Position-list terminator */ 
119138
119139 /*
119140 ** This section provides definitions to allow the
119141 ** FTS3 extension to be compiled outside of the 
119142 ** amalgamation.
119143 */
119144 #ifndef SQLITE_AMALGAMATION
119145 /*
119146 ** Macros indicating that conditional expressions are always true or
119147 ** false.
119148 */
119149 #ifdef SQLITE_COVERAGE_TEST
119150 # define ALWAYS(x) (1)
119151 # define NEVER(X)  (0)
119152 #else
119153 # define ALWAYS(x) (x)
119154 # define NEVER(x)  (x)
119155 #endif
119156
119157 /*
119158 ** Internal types used by SQLite.
119159 */
119160 typedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */
119161 typedef short int i16;            /* 2-byte (or larger) signed integer */
119162 typedef unsigned int u32;         /* 4-byte unsigned integer */
119163 typedef sqlite3_uint64 u64;       /* 8-byte unsigned integer */
119164 typedef sqlite3_int64 i64;        /* 8-byte signed integer */
119165
119166 /*
119167 ** Macro used to suppress compiler warnings for unused parameters.
119168 */
119169 #define UNUSED_PARAMETER(x) (void)(x)
119170
119171 /*
119172 ** Activate assert() only if SQLITE_TEST is enabled.
119173 */
119174 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
119175 # define NDEBUG 1
119176 #endif
119177
119178 /*
119179 ** The TESTONLY macro is used to enclose variable declarations or
119180 ** other bits of code that are needed to support the arguments
119181 ** within testcase() and assert() macros.
119182 */
119183 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
119184 # define TESTONLY(X)  X
119185 #else
119186 # define TESTONLY(X)
119187 #endif
119188
119189 #endif /* SQLITE_AMALGAMATION */
119190
119191 #ifdef SQLITE_DEBUG
119192 SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
119193 # define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
119194 #else
119195 # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
119196 #endif
119197
119198 typedef struct Fts3Table Fts3Table;
119199 typedef struct Fts3Cursor Fts3Cursor;
119200 typedef struct Fts3Expr Fts3Expr;
119201 typedef struct Fts3Phrase Fts3Phrase;
119202 typedef struct Fts3PhraseToken Fts3PhraseToken;
119203
119204 typedef struct Fts3Doclist Fts3Doclist;
119205 typedef struct Fts3SegFilter Fts3SegFilter;
119206 typedef struct Fts3DeferredToken Fts3DeferredToken;
119207 typedef struct Fts3SegReader Fts3SegReader;
119208 typedef struct Fts3MultiSegReader Fts3MultiSegReader;
119209
119210 /*
119211 ** A connection to a fulltext index is an instance of the following
119212 ** structure. The xCreate and xConnect methods create an instance
119213 ** of this structure and xDestroy and xDisconnect free that instance.
119214 ** All other methods receive a pointer to the structure as one of their
119215 ** arguments.
119216 */
119217 struct Fts3Table {
119218   sqlite3_vtab base;              /* Base class used by SQLite core */
119219   sqlite3 *db;                    /* The database connection */
119220   const char *zDb;                /* logical database name */
119221   const char *zName;              /* virtual table name */
119222   int nColumn;                    /* number of named columns in virtual table */
119223   char **azColumn;                /* column names.  malloced */
119224   sqlite3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */
119225   char *zContentTbl;              /* content=xxx option, or NULL */
119226   char *zLanguageid;              /* languageid=xxx option, or NULL */
119227   u8 bAutoincrmerge;              /* True if automerge=1 */
119228   u32 nLeafAdd;                   /* Number of leaf blocks added this trans */
119229
119230   /* Precompiled statements used by the implementation. Each of these 
119231   ** statements is run and reset within a single virtual table API call. 
119232   */
119233   sqlite3_stmt *aStmt[37];
119234
119235   char *zReadExprlist;
119236   char *zWriteExprlist;
119237
119238   int nNodeSize;                  /* Soft limit for node size */
119239   u8 bFts4;                       /* True for FTS4, false for FTS3 */
119240   u8 bHasStat;                    /* True if %_stat table exists */
119241   u8 bHasDocsize;                 /* True if %_docsize table exists */
119242   u8 bDescIdx;                    /* True if doclists are in reverse order */
119243   u8 bIgnoreSavepoint;            /* True to ignore xSavepoint invocations */
119244   int nPgsz;                      /* Page size for host database */
119245   char *zSegmentsTbl;             /* Name of %_segments table */
119246   sqlite3_blob *pSegments;        /* Blob handle open on %_segments table */
119247
119248   /* 
119249   ** The following array of hash tables is used to buffer pending index 
119250   ** updates during transactions. All pending updates buffered at any one
119251   ** time must share a common language-id (see the FTS4 langid= feature).
119252   ** The current language id is stored in variable iPrevLangid.
119253   **
119254   ** A single FTS4 table may have multiple full-text indexes. For each index
119255   ** there is an entry in the aIndex[] array. Index 0 is an index of all the
119256   ** terms that appear in the document set. Each subsequent index in aIndex[]
119257   ** is an index of prefixes of a specific length.
119258   **
119259   ** Variable nPendingData contains an estimate the memory consumed by the 
119260   ** pending data structures, including hash table overhead, but not including
119261   ** malloc overhead.  When nPendingData exceeds nMaxPendingData, all hash
119262   ** tables are flushed to disk. Variable iPrevDocid is the docid of the most 
119263   ** recently inserted record.
119264   */
119265   int nIndex;                     /* Size of aIndex[] */
119266   struct Fts3Index {
119267     int nPrefix;                  /* Prefix length (0 for main terms index) */
119268     Fts3Hash hPending;            /* Pending terms table for this index */
119269   } *aIndex;
119270   int nMaxPendingData;            /* Max pending data before flush to disk */
119271   int nPendingData;               /* Current bytes of pending data */
119272   sqlite_int64 iPrevDocid;        /* Docid of most recently inserted document */
119273   int iPrevLangid;                /* Langid of recently inserted document */
119274
119275 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
119276   /* State variables used for validating that the transaction control
119277   ** methods of the virtual table are called at appropriate times.  These
119278   ** values do not contribute to FTS functionality; they are used for
119279   ** verifying the operation of the SQLite core.
119280   */
119281   int inTransaction;     /* True after xBegin but before xCommit/xRollback */
119282   int mxSavepoint;       /* Largest valid xSavepoint integer */
119283 #endif
119284 };
119285
119286 /*
119287 ** When the core wants to read from the virtual table, it creates a
119288 ** virtual table cursor (an instance of the following structure) using
119289 ** the xOpen method. Cursors are destroyed using the xClose method.
119290 */
119291 struct Fts3Cursor {
119292   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
119293   i16 eSearch;                    /* Search strategy (see below) */
119294   u8 isEof;                       /* True if at End Of Results */
119295   u8 isRequireSeek;               /* True if must seek pStmt to %_content row */
119296   sqlite3_stmt *pStmt;            /* Prepared statement in use by the cursor */
119297   Fts3Expr *pExpr;                /* Parsed MATCH query string */
119298   int iLangid;                    /* Language being queried for */
119299   int nPhrase;                    /* Number of matchable phrases in query */
119300   Fts3DeferredToken *pDeferred;   /* Deferred search tokens, if any */
119301   sqlite3_int64 iPrevId;          /* Previous id read from aDoclist */
119302   char *pNextId;                  /* Pointer into the body of aDoclist */
119303   char *aDoclist;                 /* List of docids for full-text queries */
119304   int nDoclist;                   /* Size of buffer at aDoclist */
119305   u8 bDesc;                       /* True to sort in descending order */
119306   int eEvalmode;                  /* An FTS3_EVAL_XX constant */
119307   int nRowAvg;                    /* Average size of database rows, in pages */
119308   sqlite3_int64 nDoc;             /* Documents in table */
119309
119310   int isMatchinfoNeeded;          /* True when aMatchinfo[] needs filling in */
119311   u32 *aMatchinfo;                /* Information about most recent match */
119312   int nMatchinfo;                 /* Number of elements in aMatchinfo[] */
119313   char *zMatchinfo;               /* Matchinfo specification */
119314 };
119315
119316 #define FTS3_EVAL_FILTER    0
119317 #define FTS3_EVAL_NEXT      1
119318 #define FTS3_EVAL_MATCHINFO 2
119319
119320 /*
119321 ** The Fts3Cursor.eSearch member is always set to one of the following.
119322 ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
119323 ** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index
119324 ** of the column to be searched.  For example, in
119325 **
119326 **     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
119327 **     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
119328 ** 
119329 ** Because the LHS of the MATCH operator is 2nd column "b",
119330 ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
119331 ** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1" 
119332 ** indicating that all columns should be searched,
119333 ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
119334 */
119335 #define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
119336 #define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
119337 #define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
119338
119339
119340 struct Fts3Doclist {
119341   char *aAll;                    /* Array containing doclist (or NULL) */
119342   int nAll;                      /* Size of a[] in bytes */
119343   char *pNextDocid;              /* Pointer to next docid */
119344
119345   sqlite3_int64 iDocid;          /* Current docid (if pList!=0) */
119346   int bFreeList;                 /* True if pList should be sqlite3_free()d */
119347   char *pList;                   /* Pointer to position list following iDocid */
119348   int nList;                     /* Length of position list */
119349 };
119350
119351 /*
119352 ** A "phrase" is a sequence of one or more tokens that must match in
119353 ** sequence.  A single token is the base case and the most common case.
119354 ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
119355 ** nToken will be the number of tokens in the string.
119356 */
119357 struct Fts3PhraseToken {
119358   char *z;                        /* Text of the token */
119359   int n;                          /* Number of bytes in buffer z */
119360   int isPrefix;                   /* True if token ends with a "*" character */
119361   int bFirst;                     /* True if token must appear at position 0 */
119362
119363   /* Variables above this point are populated when the expression is
119364   ** parsed (by code in fts3_expr.c). Below this point the variables are
119365   ** used when evaluating the expression. */
119366   Fts3DeferredToken *pDeferred;   /* Deferred token object for this token */
119367   Fts3MultiSegReader *pSegcsr;    /* Segment-reader for this token */
119368 };
119369
119370 struct Fts3Phrase {
119371   /* Cache of doclist for this phrase. */
119372   Fts3Doclist doclist;
119373   int bIncr;                 /* True if doclist is loaded incrementally */
119374   int iDoclistToken;
119375
119376   /* Variables below this point are populated by fts3_expr.c when parsing 
119377   ** a MATCH expression. Everything above is part of the evaluation phase. 
119378   */
119379   int nToken;                /* Number of tokens in the phrase */
119380   int iColumn;               /* Index of column this phrase must match */
119381   Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
119382 };
119383
119384 /*
119385 ** A tree of these objects forms the RHS of a MATCH operator.
119386 **
119387 ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist 
119388 ** points to a malloced buffer, size nDoclist bytes, containing the results 
119389 ** of this phrase query in FTS3 doclist format. As usual, the initial 
119390 ** "Length" field found in doclists stored on disk is omitted from this 
119391 ** buffer.
119392 **
119393 ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
119394 ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
119395 ** where nCol is the number of columns in the queried FTS table. The array
119396 ** is populated as follows:
119397 **
119398 **   aMI[iCol*3 + 0] = Undefined
119399 **   aMI[iCol*3 + 1] = Number of occurrences
119400 **   aMI[iCol*3 + 2] = Number of rows containing at least one instance
119401 **
119402 ** The aMI array is allocated using sqlite3_malloc(). It should be freed 
119403 ** when the expression node is.
119404 */
119405 struct Fts3Expr {
119406   int eType;                 /* One of the FTSQUERY_XXX values defined below */
119407   int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
119408   Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
119409   Fts3Expr *pLeft;           /* Left operand */
119410   Fts3Expr *pRight;          /* Right operand */
119411   Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
119412
119413   /* The following are used by the fts3_eval.c module. */
119414   sqlite3_int64 iDocid;      /* Current docid */
119415   u8 bEof;                   /* True this expression is at EOF already */
119416   u8 bStart;                 /* True if iDocid is valid */
119417   u8 bDeferred;              /* True if this expression is entirely deferred */
119418
119419   u32 *aMI;
119420 };
119421
119422 /*
119423 ** Candidate values for Fts3Query.eType. Note that the order of the first
119424 ** four values is in order of precedence when parsing expressions. For 
119425 ** example, the following:
119426 **
119427 **   "a OR b AND c NOT d NEAR e"
119428 **
119429 ** is equivalent to:
119430 **
119431 **   "a OR (b AND (c NOT (d NEAR e)))"
119432 */
119433 #define FTSQUERY_NEAR   1
119434 #define FTSQUERY_NOT    2
119435 #define FTSQUERY_AND    3
119436 #define FTSQUERY_OR     4
119437 #define FTSQUERY_PHRASE 5
119438
119439
119440 /* fts3_write.c */
119441 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
119442 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
119443 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
119444 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
119445 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
119446   sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
119447 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
119448   Fts3Table*,int,const char*,int,int,Fts3SegReader**);
119449 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
119450 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
119451 SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *);
119452 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
119453
119454 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
119455 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
119456
119457 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
119458 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
119459 SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
119460 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
119461 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
119462 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
119463 #else
119464 # define sqlite3Fts3FreeDeferredTokens(x)
119465 # define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
119466 # define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
119467 # define sqlite3Fts3FreeDeferredDoclists(x)
119468 # define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
119469 #endif
119470
119471 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
119472 SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
119473
119474 /* Special values interpreted by sqlite3SegReaderCursor() */
119475 #define FTS3_SEGCURSOR_PENDING        -1
119476 #define FTS3_SEGCURSOR_ALL            -2
119477
119478 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
119479 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
119480 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
119481
119482 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *, 
119483     int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
119484
119485 /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
119486 #define FTS3_SEGMENT_REQUIRE_POS   0x00000001
119487 #define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002
119488 #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
119489 #define FTS3_SEGMENT_PREFIX        0x00000008
119490 #define FTS3_SEGMENT_SCAN          0x00000010
119491 #define FTS3_SEGMENT_FIRST         0x00000020
119492
119493 /* Type passed as 4th argument to SegmentReaderIterate() */
119494 struct Fts3SegFilter {
119495   const char *zTerm;
119496   int nTerm;
119497   int iCol;
119498   int flags;
119499 };
119500
119501 struct Fts3MultiSegReader {
119502   /* Used internally by sqlite3Fts3SegReaderXXX() calls */
119503   Fts3SegReader **apSegment;      /* Array of Fts3SegReader objects */
119504   int nSegment;                   /* Size of apSegment array */
119505   int nAdvance;                   /* How many seg-readers to advance */
119506   Fts3SegFilter *pFilter;         /* Pointer to filter object */
119507   char *aBuffer;                  /* Buffer to merge doclists in */
119508   int nBuffer;                    /* Allocated size of aBuffer[] in bytes */
119509
119510   int iColFilter;                 /* If >=0, filter for this column */
119511   int bRestart;
119512
119513   /* Used by fts3.c only. */
119514   int nCost;                      /* Cost of running iterator */
119515   int bLookup;                    /* True if a lookup of a single entry. */
119516
119517   /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
119518   char *zTerm;                    /* Pointer to term buffer */
119519   int nTerm;                      /* Size of zTerm in bytes */
119520   char *aDoclist;                 /* Pointer to doclist buffer */
119521   int nDoclist;                   /* Size of aDoclist[] in bytes */
119522 };
119523
119524 SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
119525
119526 /* fts3.c */
119527 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
119528 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
119529 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
119530 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
119531 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
119532 SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
119533 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
119534 SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
119535 SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
119536
119537 /* fts3_tokenizer.c */
119538 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
119539 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
119540 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *, 
119541     sqlite3_tokenizer **, char **
119542 );
119543 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
119544
119545 /* fts3_snippet.c */
119546 SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
119547 SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
119548   const char *, const char *, int, int
119549 );
119550 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
119551
119552 /* fts3_expr.c */
119553 SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
119554   char **, int, int, int, const char *, int, Fts3Expr **, char **
119555 );
119556 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
119557 #ifdef SQLITE_TEST
119558 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
119559 SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
119560 #endif
119561
119562 SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
119563   sqlite3_tokenizer_cursor **
119564 );
119565
119566 /* fts3_aux.c */
119567 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
119568
119569 SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
119570
119571 SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
119572     Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
119573 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
119574     Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
119575 SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **); 
119576 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
119577 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
119578
119579 /* fts3_tokenize_vtab.c */
119580 SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *);
119581
119582 /* fts3_unicode2.c (functions generated by parsing unicode text files) */
119583 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
119584 SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
119585 SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
119586 SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
119587 #endif
119588
119589 #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
119590 #endif /* _FTSINT_H */
119591
119592 /************** End of fts3Int.h *********************************************/
119593 /************** Continuing where we left off in fts3.c ***********************/
119594 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
119595
119596 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
119597 # define SQLITE_CORE 1
119598 #endif
119599
119600 /* #include <assert.h> */
119601 /* #include <stdlib.h> */
119602 /* #include <stddef.h> */
119603 /* #include <stdio.h> */
119604 /* #include <string.h> */
119605 /* #include <stdarg.h> */
119606
119607 #ifndef SQLITE_CORE 
119608   SQLITE_EXTENSION_INIT1
119609 #endif
119610
119611 static int fts3EvalNext(Fts3Cursor *pCsr);
119612 static int fts3EvalStart(Fts3Cursor *pCsr);
119613 static int fts3TermSegReaderCursor(
119614     Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
119615
119616 /* 
119617 ** Write a 64-bit variable-length integer to memory starting at p[0].
119618 ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
119619 ** The number of bytes written is returned.
119620 */
119621 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
119622   unsigned char *q = (unsigned char *) p;
119623   sqlite_uint64 vu = v;
119624   do{
119625     *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
119626     vu >>= 7;
119627   }while( vu!=0 );
119628   q[-1] &= 0x7f;  /* turn off high bit in final byte */
119629   assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
119630   return (int) (q - (unsigned char *)p);
119631 }
119632
119633 /* 
119634 ** Read a 64-bit variable-length integer from memory starting at p[0].
119635 ** Return the number of bytes read, or 0 on error.
119636 ** The value is stored in *v.
119637 */
119638 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
119639   const unsigned char *q = (const unsigned char *) p;
119640   sqlite_uint64 x = 0, y = 1;
119641   while( (*q&0x80)==0x80 && q-(unsigned char *)p<FTS3_VARINT_MAX ){
119642     x += y * (*q++ & 0x7f);
119643     y <<= 7;
119644   }
119645   x += y * (*q++);
119646   *v = (sqlite_int64) x;
119647   return (int) (q - (unsigned char *)p);
119648 }
119649
119650 /*
119651 ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
119652 ** 32-bit integer before it is returned.
119653 */
119654 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
119655  sqlite_int64 i;
119656  int ret = sqlite3Fts3GetVarint(p, &i);
119657  *pi = (int) i;
119658  return ret;
119659 }
119660
119661 /*
119662 ** Return the number of bytes required to encode v as a varint
119663 */
119664 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
119665   int i = 0;
119666   do{
119667     i++;
119668     v >>= 7;
119669   }while( v!=0 );
119670   return i;
119671 }
119672
119673 /*
119674 ** Convert an SQL-style quoted string into a normal string by removing
119675 ** the quote characters.  The conversion is done in-place.  If the
119676 ** input does not begin with a quote character, then this routine
119677 ** is a no-op.
119678 **
119679 ** Examples:
119680 **
119681 **     "abc"   becomes   abc
119682 **     'xyz'   becomes   xyz
119683 **     [pqr]   becomes   pqr
119684 **     `mno`   becomes   mno
119685 **
119686 */
119687 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
119688   char quote;                     /* Quote character (if any ) */
119689
119690   quote = z[0];
119691   if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
119692     int iIn = 1;                  /* Index of next byte to read from input */
119693     int iOut = 0;                 /* Index of next byte to write to output */
119694
119695     /* If the first byte was a '[', then the close-quote character is a ']' */
119696     if( quote=='[' ) quote = ']';  
119697
119698     while( ALWAYS(z[iIn]) ){
119699       if( z[iIn]==quote ){
119700         if( z[iIn+1]!=quote ) break;
119701         z[iOut++] = quote;
119702         iIn += 2;
119703       }else{
119704         z[iOut++] = z[iIn++];
119705       }
119706     }
119707     z[iOut] = '\0';
119708   }
119709 }
119710
119711 /*
119712 ** Read a single varint from the doclist at *pp and advance *pp to point
119713 ** to the first byte past the end of the varint.  Add the value of the varint
119714 ** to *pVal.
119715 */
119716 static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
119717   sqlite3_int64 iVal;
119718   *pp += sqlite3Fts3GetVarint(*pp, &iVal);
119719   *pVal += iVal;
119720 }
119721
119722 /*
119723 ** When this function is called, *pp points to the first byte following a
119724 ** varint that is part of a doclist (or position-list, or any other list
119725 ** of varints). This function moves *pp to point to the start of that varint,
119726 ** and sets *pVal by the varint value.
119727 **
119728 ** Argument pStart points to the first byte of the doclist that the
119729 ** varint is part of.
119730 */
119731 static void fts3GetReverseVarint(
119732   char **pp, 
119733   char *pStart, 
119734   sqlite3_int64 *pVal
119735 ){
119736   sqlite3_int64 iVal;
119737   char *p;
119738
119739   /* Pointer p now points at the first byte past the varint we are 
119740   ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
119741   ** clear on character p[-1]. */
119742   for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
119743   p++;
119744   *pp = p;
119745
119746   sqlite3Fts3GetVarint(p, &iVal);
119747   *pVal = iVal;
119748 }
119749
119750 /*
119751 ** The xDisconnect() virtual table method.
119752 */
119753 static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
119754   Fts3Table *p = (Fts3Table *)pVtab;
119755   int i;
119756
119757   assert( p->nPendingData==0 );
119758   assert( p->pSegments==0 );
119759
119760   /* Free any prepared statements held */
119761   for(i=0; i<SizeofArray(p->aStmt); i++){
119762     sqlite3_finalize(p->aStmt[i]);
119763   }
119764   sqlite3_free(p->zSegmentsTbl);
119765   sqlite3_free(p->zReadExprlist);
119766   sqlite3_free(p->zWriteExprlist);
119767   sqlite3_free(p->zContentTbl);
119768   sqlite3_free(p->zLanguageid);
119769
119770   /* Invoke the tokenizer destructor to free the tokenizer. */
119771   p->pTokenizer->pModule->xDestroy(p->pTokenizer);
119772
119773   sqlite3_free(p);
119774   return SQLITE_OK;
119775 }
119776
119777 /*
119778 ** Construct one or more SQL statements from the format string given
119779 ** and then evaluate those statements. The success code is written
119780 ** into *pRc.
119781 **
119782 ** If *pRc is initially non-zero then this routine is a no-op.
119783 */
119784 static void fts3DbExec(
119785   int *pRc,              /* Success code */
119786   sqlite3 *db,           /* Database in which to run SQL */
119787   const char *zFormat,   /* Format string for SQL */
119788   ...                    /* Arguments to the format string */
119789 ){
119790   va_list ap;
119791   char *zSql;
119792   if( *pRc ) return;
119793   va_start(ap, zFormat);
119794   zSql = sqlite3_vmprintf(zFormat, ap);
119795   va_end(ap);
119796   if( zSql==0 ){
119797     *pRc = SQLITE_NOMEM;
119798   }else{
119799     *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
119800     sqlite3_free(zSql);
119801   }
119802 }
119803
119804 /*
119805 ** The xDestroy() virtual table method.
119806 */
119807 static int fts3DestroyMethod(sqlite3_vtab *pVtab){
119808   Fts3Table *p = (Fts3Table *)pVtab;
119809   int rc = SQLITE_OK;              /* Return code */
119810   const char *zDb = p->zDb;        /* Name of database (e.g. "main", "temp") */
119811   sqlite3 *db = p->db;             /* Database handle */
119812
119813   /* Drop the shadow tables */
119814   if( p->zContentTbl==0 ){
119815     fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
119816   }
119817   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
119818   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
119819   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
119820   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
119821
119822   /* If everything has worked, invoke fts3DisconnectMethod() to free the
119823   ** memory associated with the Fts3Table structure and return SQLITE_OK.
119824   ** Otherwise, return an SQLite error code.
119825   */
119826   return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
119827 }
119828
119829
119830 /*
119831 ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
119832 ** passed as the first argument. This is done as part of the xConnect()
119833 ** and xCreate() methods.
119834 **
119835 ** If *pRc is non-zero when this function is called, it is a no-op. 
119836 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
119837 ** before returning.
119838 */
119839 static void fts3DeclareVtab(int *pRc, Fts3Table *p){
119840   if( *pRc==SQLITE_OK ){
119841     int i;                        /* Iterator variable */
119842     int rc;                       /* Return code */
119843     char *zSql;                   /* SQL statement passed to declare_vtab() */
119844     char *zCols;                  /* List of user defined columns */
119845     const char *zLanguageid;
119846
119847     zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
119848     sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
119849
119850     /* Create a list of user columns for the virtual table */
119851     zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
119852     for(i=1; zCols && i<p->nColumn; i++){
119853       zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
119854     }
119855
119856     /* Create the whole "CREATE TABLE" statement to pass to SQLite */
119857     zSql = sqlite3_mprintf(
119858         "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)", 
119859         zCols, p->zName, zLanguageid
119860     );
119861     if( !zCols || !zSql ){
119862       rc = SQLITE_NOMEM;
119863     }else{
119864       rc = sqlite3_declare_vtab(p->db, zSql);
119865     }
119866
119867     sqlite3_free(zSql);
119868     sqlite3_free(zCols);
119869     *pRc = rc;
119870   }
119871 }
119872
119873 /*
119874 ** Create the %_stat table if it does not already exist.
119875 */
119876 SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
119877   fts3DbExec(pRc, p->db, 
119878       "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
119879           "(id INTEGER PRIMARY KEY, value BLOB);",
119880       p->zDb, p->zName
119881   );
119882   if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
119883 }
119884
119885 /*
119886 ** Create the backing store tables (%_content, %_segments and %_segdir)
119887 ** required by the FTS3 table passed as the only argument. This is done
119888 ** as part of the vtab xCreate() method.
119889 **
119890 ** If the p->bHasDocsize boolean is true (indicating that this is an
119891 ** FTS4 table, not an FTS3 table) then also create the %_docsize and
119892 ** %_stat tables required by FTS4.
119893 */
119894 static int fts3CreateTables(Fts3Table *p){
119895   int rc = SQLITE_OK;             /* Return code */
119896   int i;                          /* Iterator variable */
119897   sqlite3 *db = p->db;            /* The database connection */
119898
119899   if( p->zContentTbl==0 ){
119900     const char *zLanguageid = p->zLanguageid;
119901     char *zContentCols;           /* Columns of %_content table */
119902
119903     /* Create a list of user columns for the content table */
119904     zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
119905     for(i=0; zContentCols && i<p->nColumn; i++){
119906       char *z = p->azColumn[i];
119907       zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
119908     }
119909     if( zLanguageid && zContentCols ){
119910       zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
119911     }
119912     if( zContentCols==0 ) rc = SQLITE_NOMEM;
119913   
119914     /* Create the content table */
119915     fts3DbExec(&rc, db, 
119916        "CREATE TABLE %Q.'%q_content'(%s)",
119917        p->zDb, p->zName, zContentCols
119918     );
119919     sqlite3_free(zContentCols);
119920   }
119921
119922   /* Create other tables */
119923   fts3DbExec(&rc, db, 
119924       "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
119925       p->zDb, p->zName
119926   );
119927   fts3DbExec(&rc, db, 
119928       "CREATE TABLE %Q.'%q_segdir'("
119929         "level INTEGER,"
119930         "idx INTEGER,"
119931         "start_block INTEGER,"
119932         "leaves_end_block INTEGER,"
119933         "end_block INTEGER,"
119934         "root BLOB,"
119935         "PRIMARY KEY(level, idx)"
119936       ");",
119937       p->zDb, p->zName
119938   );
119939   if( p->bHasDocsize ){
119940     fts3DbExec(&rc, db, 
119941         "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
119942         p->zDb, p->zName
119943     );
119944   }
119945   assert( p->bHasStat==p->bFts4 );
119946   if( p->bHasStat ){
119947     sqlite3Fts3CreateStatTable(&rc, p);
119948   }
119949   return rc;
119950 }
119951
119952 /*
119953 ** Store the current database page-size in bytes in p->nPgsz.
119954 **
119955 ** If *pRc is non-zero when this function is called, it is a no-op. 
119956 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
119957 ** before returning.
119958 */
119959 static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
119960   if( *pRc==SQLITE_OK ){
119961     int rc;                       /* Return code */
119962     char *zSql;                   /* SQL text "PRAGMA %Q.page_size" */
119963     sqlite3_stmt *pStmt;          /* Compiled "PRAGMA %Q.page_size" statement */
119964   
119965     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
119966     if( !zSql ){
119967       rc = SQLITE_NOMEM;
119968     }else{
119969       rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
119970       if( rc==SQLITE_OK ){
119971         sqlite3_step(pStmt);
119972         p->nPgsz = sqlite3_column_int(pStmt, 0);
119973         rc = sqlite3_finalize(pStmt);
119974       }else if( rc==SQLITE_AUTH ){
119975         p->nPgsz = 1024;
119976         rc = SQLITE_OK;
119977       }
119978     }
119979     assert( p->nPgsz>0 || rc!=SQLITE_OK );
119980     sqlite3_free(zSql);
119981     *pRc = rc;
119982   }
119983 }
119984
119985 /*
119986 ** "Special" FTS4 arguments are column specifications of the following form:
119987 **
119988 **   <key> = <value>
119989 **
119990 ** There may not be whitespace surrounding the "=" character. The <value> 
119991 ** term may be quoted, but the <key> may not.
119992 */
119993 static int fts3IsSpecialColumn(
119994   const char *z, 
119995   int *pnKey,
119996   char **pzValue
119997 ){
119998   char *zValue;
119999   const char *zCsr = z;
120000
120001   while( *zCsr!='=' ){
120002     if( *zCsr=='\0' ) return 0;
120003     zCsr++;
120004   }
120005
120006   *pnKey = (int)(zCsr-z);
120007   zValue = sqlite3_mprintf("%s", &zCsr[1]);
120008   if( zValue ){
120009     sqlite3Fts3Dequote(zValue);
120010   }
120011   *pzValue = zValue;
120012   return 1;
120013 }
120014
120015 /*
120016 ** Append the output of a printf() style formatting to an existing string.
120017 */
120018 static void fts3Appendf(
120019   int *pRc,                       /* IN/OUT: Error code */
120020   char **pz,                      /* IN/OUT: Pointer to string buffer */
120021   const char *zFormat,            /* Printf format string to append */
120022   ...                             /* Arguments for printf format string */
120023 ){
120024   if( *pRc==SQLITE_OK ){
120025     va_list ap;
120026     char *z;
120027     va_start(ap, zFormat);
120028     z = sqlite3_vmprintf(zFormat, ap);
120029     va_end(ap);
120030     if( z && *pz ){
120031       char *z2 = sqlite3_mprintf("%s%s", *pz, z);
120032       sqlite3_free(z);
120033       z = z2;
120034     }
120035     if( z==0 ) *pRc = SQLITE_NOMEM;
120036     sqlite3_free(*pz);
120037     *pz = z;
120038   }
120039 }
120040
120041 /*
120042 ** Return a copy of input string zInput enclosed in double-quotes (") and
120043 ** with all double quote characters escaped. For example:
120044 **
120045 **     fts3QuoteId("un \"zip\"")   ->    "un \"\"zip\"\""
120046 **
120047 ** The pointer returned points to memory obtained from sqlite3_malloc(). It
120048 ** is the callers responsibility to call sqlite3_free() to release this
120049 ** memory.
120050 */
120051 static char *fts3QuoteId(char const *zInput){
120052   int nRet;
120053   char *zRet;
120054   nRet = 2 + (int)strlen(zInput)*2 + 1;
120055   zRet = sqlite3_malloc(nRet);
120056   if( zRet ){
120057     int i;
120058     char *z = zRet;
120059     *(z++) = '"';
120060     for(i=0; zInput[i]; i++){
120061       if( zInput[i]=='"' ) *(z++) = '"';
120062       *(z++) = zInput[i];
120063     }
120064     *(z++) = '"';
120065     *(z++) = '\0';
120066   }
120067   return zRet;
120068 }
120069
120070 /*
120071 ** Return a list of comma separated SQL expressions and a FROM clause that 
120072 ** could be used in a SELECT statement such as the following:
120073 **
120074 **     SELECT <list of expressions> FROM %_content AS x ...
120075 **
120076 ** to return the docid, followed by each column of text data in order
120077 ** from left to write. If parameter zFunc is not NULL, then instead of
120078 ** being returned directly each column of text data is passed to an SQL
120079 ** function named zFunc first. For example, if zFunc is "unzip" and the
120080 ** table has the three user-defined columns "a", "b", and "c", the following
120081 ** string is returned:
120082 **
120083 **     "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
120084 **
120085 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
120086 ** is the responsibility of the caller to eventually free it.
120087 **
120088 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
120089 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
120090 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
120091 ** no error occurs, *pRc is left unmodified.
120092 */
120093 static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
120094   char *zRet = 0;
120095   char *zFree = 0;
120096   char *zFunction;
120097   int i;
120098
120099   if( p->zContentTbl==0 ){
120100     if( !zFunc ){
120101       zFunction = "";
120102     }else{
120103       zFree = zFunction = fts3QuoteId(zFunc);
120104     }
120105     fts3Appendf(pRc, &zRet, "docid");
120106     for(i=0; i<p->nColumn; i++){
120107       fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
120108     }
120109     if( p->zLanguageid ){
120110       fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
120111     }
120112     sqlite3_free(zFree);
120113   }else{
120114     fts3Appendf(pRc, &zRet, "rowid");
120115     for(i=0; i<p->nColumn; i++){
120116       fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
120117     }
120118     if( p->zLanguageid ){
120119       fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
120120     }
120121   }
120122   fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x", 
120123       p->zDb,
120124       (p->zContentTbl ? p->zContentTbl : p->zName),
120125       (p->zContentTbl ? "" : "_content")
120126   );
120127   return zRet;
120128 }
120129
120130 /*
120131 ** Return a list of N comma separated question marks, where N is the number
120132 ** of columns in the %_content table (one for the docid plus one for each
120133 ** user-defined text column).
120134 **
120135 ** If argument zFunc is not NULL, then all but the first question mark
120136 ** is preceded by zFunc and an open bracket, and followed by a closed
120137 ** bracket. For example, if zFunc is "zip" and the FTS3 table has three 
120138 ** user-defined text columns, the following string is returned:
120139 **
120140 **     "?, zip(?), zip(?), zip(?)"
120141 **
120142 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
120143 ** is the responsibility of the caller to eventually free it.
120144 **
120145 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
120146 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
120147 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
120148 ** no error occurs, *pRc is left unmodified.
120149 */
120150 static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
120151   char *zRet = 0;
120152   char *zFree = 0;
120153   char *zFunction;
120154   int i;
120155
120156   if( !zFunc ){
120157     zFunction = "";
120158   }else{
120159     zFree = zFunction = fts3QuoteId(zFunc);
120160   }
120161   fts3Appendf(pRc, &zRet, "?");
120162   for(i=0; i<p->nColumn; i++){
120163     fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
120164   }
120165   if( p->zLanguageid ){
120166     fts3Appendf(pRc, &zRet, ", ?");
120167   }
120168   sqlite3_free(zFree);
120169   return zRet;
120170 }
120171
120172 /*
120173 ** This function interprets the string at (*pp) as a non-negative integer
120174 ** value. It reads the integer and sets *pnOut to the value read, then 
120175 ** sets *pp to point to the byte immediately following the last byte of
120176 ** the integer value.
120177 **
120178 ** Only decimal digits ('0'..'9') may be part of an integer value. 
120179 **
120180 ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
120181 ** the output value undefined. Otherwise SQLITE_OK is returned.
120182 **
120183 ** This function is used when parsing the "prefix=" FTS4 parameter.
120184 */
120185 static int fts3GobbleInt(const char **pp, int *pnOut){
120186   const char *p;                  /* Iterator pointer */
120187   int nInt = 0;                   /* Output value */
120188
120189   for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
120190     nInt = nInt * 10 + (p[0] - '0');
120191   }
120192   if( p==*pp ) return SQLITE_ERROR;
120193   *pnOut = nInt;
120194   *pp = p;
120195   return SQLITE_OK;
120196 }
120197
120198 /*
120199 ** This function is called to allocate an array of Fts3Index structures
120200 ** representing the indexes maintained by the current FTS table. FTS tables
120201 ** always maintain the main "terms" index, but may also maintain one or
120202 ** more "prefix" indexes, depending on the value of the "prefix=" parameter
120203 ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
120204 **
120205 ** Argument zParam is passed the value of the "prefix=" option if one was
120206 ** specified, or NULL otherwise.
120207 **
120208 ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
120209 ** the allocated array. *pnIndex is set to the number of elements in the
120210 ** array. If an error does occur, an SQLite error code is returned.
120211 **
120212 ** Regardless of whether or not an error is returned, it is the responsibility
120213 ** of the caller to call sqlite3_free() on the output array to free it.
120214 */
120215 static int fts3PrefixParameter(
120216   const char *zParam,             /* ABC in prefix=ABC parameter to parse */
120217   int *pnIndex,                   /* OUT: size of *apIndex[] array */
120218   struct Fts3Index **apIndex      /* OUT: Array of indexes for this table */
120219 ){
120220   struct Fts3Index *aIndex;       /* Allocated array */
120221   int nIndex = 1;                 /* Number of entries in array */
120222
120223   if( zParam && zParam[0] ){
120224     const char *p;
120225     nIndex++;
120226     for(p=zParam; *p; p++){
120227       if( *p==',' ) nIndex++;
120228     }
120229   }
120230
120231   aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
120232   *apIndex = aIndex;
120233   *pnIndex = nIndex;
120234   if( !aIndex ){
120235     return SQLITE_NOMEM;
120236   }
120237
120238   memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
120239   if( zParam ){
120240     const char *p = zParam;
120241     int i;
120242     for(i=1; i<nIndex; i++){
120243       int nPrefix;
120244       if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
120245       aIndex[i].nPrefix = nPrefix;
120246       p++;
120247     }
120248   }
120249
120250   return SQLITE_OK;
120251 }
120252
120253 /*
120254 ** This function is called when initializing an FTS4 table that uses the
120255 ** content=xxx option. It determines the number of and names of the columns
120256 ** of the new FTS4 table.
120257 **
120258 ** The third argument passed to this function is the value passed to the
120259 ** config=xxx option (i.e. "xxx"). This function queries the database for
120260 ** a table of that name. If found, the output variables are populated
120261 ** as follows:
120262 **
120263 **   *pnCol:   Set to the number of columns table xxx has,
120264 **
120265 **   *pnStr:   Set to the total amount of space required to store a copy
120266 **             of each columns name, including the nul-terminator.
120267 **
120268 **   *pazCol:  Set to point to an array of *pnCol strings. Each string is
120269 **             the name of the corresponding column in table xxx. The array
120270 **             and its contents are allocated using a single allocation. It
120271 **             is the responsibility of the caller to free this allocation
120272 **             by eventually passing the *pazCol value to sqlite3_free().
120273 **
120274 ** If the table cannot be found, an error code is returned and the output
120275 ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
120276 ** returned (and the output variables are undefined).
120277 */
120278 static int fts3ContentColumns(
120279   sqlite3 *db,                    /* Database handle */
120280   const char *zDb,                /* Name of db (i.e. "main", "temp" etc.) */
120281   const char *zTbl,               /* Name of content table */
120282   const char ***pazCol,           /* OUT: Malloc'd array of column names */
120283   int *pnCol,                     /* OUT: Size of array *pazCol */
120284   int *pnStr                      /* OUT: Bytes of string content */
120285 ){
120286   int rc = SQLITE_OK;             /* Return code */
120287   char *zSql;                     /* "SELECT *" statement on zTbl */  
120288   sqlite3_stmt *pStmt = 0;        /* Compiled version of zSql */
120289
120290   zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
120291   if( !zSql ){
120292     rc = SQLITE_NOMEM;
120293   }else{
120294     rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
120295   }
120296   sqlite3_free(zSql);
120297
120298   if( rc==SQLITE_OK ){
120299     const char **azCol;           /* Output array */
120300     int nStr = 0;                 /* Size of all column names (incl. 0x00) */
120301     int nCol;                     /* Number of table columns */
120302     int i;                        /* Used to iterate through columns */
120303
120304     /* Loop through the returned columns. Set nStr to the number of bytes of
120305     ** space required to store a copy of each column name, including the
120306     ** nul-terminator byte.  */
120307     nCol = sqlite3_column_count(pStmt);
120308     for(i=0; i<nCol; i++){
120309       const char *zCol = sqlite3_column_name(pStmt, i);
120310       nStr += (int)strlen(zCol) + 1;
120311     }
120312
120313     /* Allocate and populate the array to return. */
120314     azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
120315     if( azCol==0 ){
120316       rc = SQLITE_NOMEM;
120317     }else{
120318       char *p = (char *)&azCol[nCol];
120319       for(i=0; i<nCol; i++){
120320         const char *zCol = sqlite3_column_name(pStmt, i);
120321         int n = (int)strlen(zCol)+1;
120322         memcpy(p, zCol, n);
120323         azCol[i] = p;
120324         p += n;
120325       }
120326     }
120327     sqlite3_finalize(pStmt);
120328
120329     /* Set the output variables. */
120330     *pnCol = nCol;
120331     *pnStr = nStr;
120332     *pazCol = azCol;
120333   }
120334
120335   return rc;
120336 }
120337
120338 /*
120339 ** This function is the implementation of both the xConnect and xCreate
120340 ** methods of the FTS3 virtual table.
120341 **
120342 ** The argv[] array contains the following:
120343 **
120344 **   argv[0]   -> module name  ("fts3" or "fts4")
120345 **   argv[1]   -> database name
120346 **   argv[2]   -> table name
120347 **   argv[...] -> "column name" and other module argument fields.
120348 */
120349 static int fts3InitVtab(
120350   int isCreate,                   /* True for xCreate, false for xConnect */
120351   sqlite3 *db,                    /* The SQLite database connection */
120352   void *pAux,                     /* Hash table containing tokenizers */
120353   int argc,                       /* Number of elements in argv array */
120354   const char * const *argv,       /* xCreate/xConnect argument array */
120355   sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
120356   char **pzErr                    /* Write any error message here */
120357 ){
120358   Fts3Hash *pHash = (Fts3Hash *)pAux;
120359   Fts3Table *p = 0;               /* Pointer to allocated vtab */
120360   int rc = SQLITE_OK;             /* Return code */
120361   int i;                          /* Iterator variable */
120362   int nByte;                      /* Size of allocation used for *p */
120363   int iCol;                       /* Column index */
120364   int nString = 0;                /* Bytes required to hold all column names */
120365   int nCol = 0;                   /* Number of columns in the FTS table */
120366   char *zCsr;                     /* Space for holding column names */
120367   int nDb;                        /* Bytes required to hold database name */
120368   int nName;                      /* Bytes required to hold table name */
120369   int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
120370   const char **aCol;              /* Array of column names */
120371   sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
120372
120373   int nIndex;                     /* Size of aIndex[] array */
120374   struct Fts3Index *aIndex = 0;   /* Array of indexes for this table */
120375
120376   /* The results of parsing supported FTS4 key=value options: */
120377   int bNoDocsize = 0;             /* True to omit %_docsize table */
120378   int bDescIdx = 0;               /* True to store descending indexes */
120379   char *zPrefix = 0;              /* Prefix parameter value (or NULL) */
120380   char *zCompress = 0;            /* compress=? parameter (or NULL) */
120381   char *zUncompress = 0;          /* uncompress=? parameter (or NULL) */
120382   char *zContent = 0;             /* content=? parameter (or NULL) */
120383   char *zLanguageid = 0;          /* languageid=? parameter (or NULL) */
120384
120385   assert( strlen(argv[0])==4 );
120386   assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
120387        || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
120388   );
120389
120390   nDb = (int)strlen(argv[1]) + 1;
120391   nName = (int)strlen(argv[2]) + 1;
120392
120393   aCol = (const char **)sqlite3_malloc(sizeof(const char *) * (argc-2) );
120394   if( !aCol ) return SQLITE_NOMEM;
120395   memset((void *)aCol, 0, sizeof(const char *) * (argc-2));
120396
120397   /* Loop through all of the arguments passed by the user to the FTS3/4
120398   ** module (i.e. all the column names and special arguments). This loop
120399   ** does the following:
120400   **
120401   **   + Figures out the number of columns the FTSX table will have, and
120402   **     the number of bytes of space that must be allocated to store copies
120403   **     of the column names.
120404   **
120405   **   + If there is a tokenizer specification included in the arguments,
120406   **     initializes the tokenizer pTokenizer.
120407   */
120408   for(i=3; rc==SQLITE_OK && i<argc; i++){
120409     char const *z = argv[i];
120410     int nKey;
120411     char *zVal;
120412
120413     /* Check if this is a tokenizer specification */
120414     if( !pTokenizer 
120415      && strlen(z)>8
120416      && 0==sqlite3_strnicmp(z, "tokenize", 8) 
120417      && 0==sqlite3Fts3IsIdChar(z[8])
120418     ){
120419       rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
120420     }
120421
120422     /* Check if it is an FTS4 special argument. */
120423     else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
120424       struct Fts4Option {
120425         const char *zOpt;
120426         int nOpt;
120427       } aFts4Opt[] = {
120428         { "matchinfo",   9 },     /* 0 -> MATCHINFO */
120429         { "prefix",      6 },     /* 1 -> PREFIX */
120430         { "compress",    8 },     /* 2 -> COMPRESS */
120431         { "uncompress", 10 },     /* 3 -> UNCOMPRESS */
120432         { "order",       5 },     /* 4 -> ORDER */
120433         { "content",     7 },     /* 5 -> CONTENT */
120434         { "languageid", 10 }      /* 6 -> LANGUAGEID */
120435       };
120436
120437       int iOpt;
120438       if( !zVal ){
120439         rc = SQLITE_NOMEM;
120440       }else{
120441         for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
120442           struct Fts4Option *pOp = &aFts4Opt[iOpt];
120443           if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
120444             break;
120445           }
120446         }
120447         if( iOpt==SizeofArray(aFts4Opt) ){
120448           *pzErr = sqlite3_mprintf("unrecognized parameter: %s", z);
120449           rc = SQLITE_ERROR;
120450         }else{
120451           switch( iOpt ){
120452             case 0:               /* MATCHINFO */
120453               if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
120454                 *pzErr = sqlite3_mprintf("unrecognized matchinfo: %s", zVal);
120455                 rc = SQLITE_ERROR;
120456               }
120457               bNoDocsize = 1;
120458               break;
120459
120460             case 1:               /* PREFIX */
120461               sqlite3_free(zPrefix);
120462               zPrefix = zVal;
120463               zVal = 0;
120464               break;
120465
120466             case 2:               /* COMPRESS */
120467               sqlite3_free(zCompress);
120468               zCompress = zVal;
120469               zVal = 0;
120470               break;
120471
120472             case 3:               /* UNCOMPRESS */
120473               sqlite3_free(zUncompress);
120474               zUncompress = zVal;
120475               zVal = 0;
120476               break;
120477
120478             case 4:               /* ORDER */
120479               if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3)) 
120480                && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4)) 
120481               ){
120482                 *pzErr = sqlite3_mprintf("unrecognized order: %s", zVal);
120483                 rc = SQLITE_ERROR;
120484               }
120485               bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
120486               break;
120487
120488             case 5:              /* CONTENT */
120489               sqlite3_free(zContent);
120490               zContent = zVal;
120491               zVal = 0;
120492               break;
120493
120494             case 6:              /* LANGUAGEID */
120495               assert( iOpt==6 );
120496               sqlite3_free(zLanguageid);
120497               zLanguageid = zVal;
120498               zVal = 0;
120499               break;
120500           }
120501         }
120502         sqlite3_free(zVal);
120503       }
120504     }
120505
120506     /* Otherwise, the argument is a column name. */
120507     else {
120508       nString += (int)(strlen(z) + 1);
120509       aCol[nCol++] = z;
120510     }
120511   }
120512
120513   /* If a content=xxx option was specified, the following:
120514   **
120515   **   1. Ignore any compress= and uncompress= options.
120516   **
120517   **   2. If no column names were specified as part of the CREATE VIRTUAL
120518   **      TABLE statement, use all columns from the content table.
120519   */
120520   if( rc==SQLITE_OK && zContent ){
120521     sqlite3_free(zCompress); 
120522     sqlite3_free(zUncompress); 
120523     zCompress = 0;
120524     zUncompress = 0;
120525     if( nCol==0 ){
120526       sqlite3_free((void*)aCol); 
120527       aCol = 0;
120528       rc = fts3ContentColumns(db, argv[1], zContent, &aCol, &nCol, &nString);
120529
120530       /* If a languageid= option was specified, remove the language id
120531       ** column from the aCol[] array. */ 
120532       if( rc==SQLITE_OK && zLanguageid ){
120533         int j;
120534         for(j=0; j<nCol; j++){
120535           if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
120536             int k;
120537             for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
120538             nCol--;
120539             break;
120540           }
120541         }
120542       }
120543     }
120544   }
120545   if( rc!=SQLITE_OK ) goto fts3_init_out;
120546
120547   if( nCol==0 ){
120548     assert( nString==0 );
120549     aCol[0] = "content";
120550     nString = 8;
120551     nCol = 1;
120552   }
120553
120554   if( pTokenizer==0 ){
120555     rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
120556     if( rc!=SQLITE_OK ) goto fts3_init_out;
120557   }
120558   assert( pTokenizer );
120559
120560   rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
120561   if( rc==SQLITE_ERROR ){
120562     assert( zPrefix );
120563     *pzErr = sqlite3_mprintf("error parsing prefix parameter: %s", zPrefix);
120564   }
120565   if( rc!=SQLITE_OK ) goto fts3_init_out;
120566
120567   /* Allocate and populate the Fts3Table structure. */
120568   nByte = sizeof(Fts3Table) +                  /* Fts3Table */
120569           nCol * sizeof(char *) +              /* azColumn */
120570           nIndex * sizeof(struct Fts3Index) +  /* aIndex */
120571           nName +                              /* zName */
120572           nDb +                                /* zDb */
120573           nString;                             /* Space for azColumn strings */
120574   p = (Fts3Table*)sqlite3_malloc(nByte);
120575   if( p==0 ){
120576     rc = SQLITE_NOMEM;
120577     goto fts3_init_out;
120578   }
120579   memset(p, 0, nByte);
120580   p->db = db;
120581   p->nColumn = nCol;
120582   p->nPendingData = 0;
120583   p->azColumn = (char **)&p[1];
120584   p->pTokenizer = pTokenizer;
120585   p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
120586   p->bHasDocsize = (isFts4 && bNoDocsize==0);
120587   p->bHasStat = isFts4;
120588   p->bFts4 = isFts4;
120589   p->bDescIdx = bDescIdx;
120590   p->bAutoincrmerge = 0xff;   /* 0xff means setting unknown */
120591   p->zContentTbl = zContent;
120592   p->zLanguageid = zLanguageid;
120593   zContent = 0;
120594   zLanguageid = 0;
120595   TESTONLY( p->inTransaction = -1 );
120596   TESTONLY( p->mxSavepoint = -1 );
120597
120598   p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
120599   memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
120600   p->nIndex = nIndex;
120601   for(i=0; i<nIndex; i++){
120602     fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
120603   }
120604
120605   /* Fill in the zName and zDb fields of the vtab structure. */
120606   zCsr = (char *)&p->aIndex[nIndex];
120607   p->zName = zCsr;
120608   memcpy(zCsr, argv[2], nName);
120609   zCsr += nName;
120610   p->zDb = zCsr;
120611   memcpy(zCsr, argv[1], nDb);
120612   zCsr += nDb;
120613
120614   /* Fill in the azColumn array */
120615   for(iCol=0; iCol<nCol; iCol++){
120616     char *z; 
120617     int n = 0;
120618     z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
120619     memcpy(zCsr, z, n);
120620     zCsr[n] = '\0';
120621     sqlite3Fts3Dequote(zCsr);
120622     p->azColumn[iCol] = zCsr;
120623     zCsr += n+1;
120624     assert( zCsr <= &((char *)p)[nByte] );
120625   }
120626
120627   if( (zCompress==0)!=(zUncompress==0) ){
120628     char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
120629     rc = SQLITE_ERROR;
120630     *pzErr = sqlite3_mprintf("missing %s parameter in fts4 constructor", zMiss);
120631   }
120632   p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
120633   p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
120634   if( rc!=SQLITE_OK ) goto fts3_init_out;
120635
120636   /* If this is an xCreate call, create the underlying tables in the 
120637   ** database. TODO: For xConnect(), it could verify that said tables exist.
120638   */
120639   if( isCreate ){
120640     rc = fts3CreateTables(p);
120641   }
120642
120643   /* Check to see if a legacy fts3 table has been "upgraded" by the
120644   ** addition of a %_stat table so that it can use incremental merge.
120645   */
120646   if( !isFts4 && !isCreate ){
120647     int rc2 = SQLITE_OK;
120648     fts3DbExec(&rc2, db, "SELECT 1 FROM %Q.'%q_stat' WHERE id=2",
120649                p->zDb, p->zName);
120650     if( rc2==SQLITE_OK ) p->bHasStat = 1;
120651   }
120652
120653   /* Figure out the page-size for the database. This is required in order to
120654   ** estimate the cost of loading large doclists from the database.  */
120655   fts3DatabasePageSize(&rc, p);
120656   p->nNodeSize = p->nPgsz-35;
120657
120658   /* Declare the table schema to SQLite. */
120659   fts3DeclareVtab(&rc, p);
120660
120661 fts3_init_out:
120662   sqlite3_free(zPrefix);
120663   sqlite3_free(aIndex);
120664   sqlite3_free(zCompress);
120665   sqlite3_free(zUncompress);
120666   sqlite3_free(zContent);
120667   sqlite3_free(zLanguageid);
120668   sqlite3_free((void *)aCol);
120669   if( rc!=SQLITE_OK ){
120670     if( p ){
120671       fts3DisconnectMethod((sqlite3_vtab *)p);
120672     }else if( pTokenizer ){
120673       pTokenizer->pModule->xDestroy(pTokenizer);
120674     }
120675   }else{
120676     assert( p->pSegments==0 );
120677     *ppVTab = &p->base;
120678   }
120679   return rc;
120680 }
120681
120682 /*
120683 ** The xConnect() and xCreate() methods for the virtual table. All the
120684 ** work is done in function fts3InitVtab().
120685 */
120686 static int fts3ConnectMethod(
120687   sqlite3 *db,                    /* Database connection */
120688   void *pAux,                     /* Pointer to tokenizer hash table */
120689   int argc,                       /* Number of elements in argv array */
120690   const char * const *argv,       /* xCreate/xConnect argument array */
120691   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
120692   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
120693 ){
120694   return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
120695 }
120696 static int fts3CreateMethod(
120697   sqlite3 *db,                    /* Database connection */
120698   void *pAux,                     /* Pointer to tokenizer hash table */
120699   int argc,                       /* Number of elements in argv array */
120700   const char * const *argv,       /* xCreate/xConnect argument array */
120701   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
120702   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
120703 ){
120704   return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
120705 }
120706
120707 /* 
120708 ** Implementation of the xBestIndex method for FTS3 tables. There
120709 ** are three possible strategies, in order of preference:
120710 **
120711 **   1. Direct lookup by rowid or docid. 
120712 **   2. Full-text search using a MATCH operator on a non-docid column.
120713 **   3. Linear scan of %_content table.
120714 */
120715 static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
120716   Fts3Table *p = (Fts3Table *)pVTab;
120717   int i;                          /* Iterator variable */
120718   int iCons = -1;                 /* Index of constraint to use */
120719   int iLangidCons = -1;           /* Index of langid=x constraint, if present */
120720
120721   /* By default use a full table scan. This is an expensive option,
120722   ** so search through the constraints to see if a more efficient 
120723   ** strategy is possible.
120724   */
120725   pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
120726   pInfo->estimatedCost = 500000;
120727   for(i=0; i<pInfo->nConstraint; i++){
120728     struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
120729     if( pCons->usable==0 ) continue;
120730
120731     /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
120732     if( iCons<0 
120733      && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ 
120734      && (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1 )
120735     ){
120736       pInfo->idxNum = FTS3_DOCID_SEARCH;
120737       pInfo->estimatedCost = 1.0;
120738       iCons = i;
120739     }
120740
120741     /* A MATCH constraint. Use a full-text search.
120742     **
120743     ** If there is more than one MATCH constraint available, use the first
120744     ** one encountered. If there is both a MATCH constraint and a direct
120745     ** rowid/docid lookup, prefer the MATCH strategy. This is done even 
120746     ** though the rowid/docid lookup is faster than a MATCH query, selecting
120747     ** it would lead to an "unable to use function MATCH in the requested 
120748     ** context" error.
120749     */
120750     if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH 
120751      && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
120752     ){
120753       pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
120754       pInfo->estimatedCost = 2.0;
120755       iCons = i;
120756     }
120757
120758     /* Equality constraint on the langid column */
120759     if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ 
120760      && pCons->iColumn==p->nColumn + 2
120761     ){
120762       iLangidCons = i;
120763     }
120764   }
120765
120766   if( iCons>=0 ){
120767     pInfo->aConstraintUsage[iCons].argvIndex = 1;
120768     pInfo->aConstraintUsage[iCons].omit = 1;
120769   } 
120770   if( iLangidCons>=0 ){
120771     pInfo->aConstraintUsage[iLangidCons].argvIndex = 2;
120772   } 
120773
120774   /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
120775   ** docid) order. Both ascending and descending are possible. 
120776   */
120777   if( pInfo->nOrderBy==1 ){
120778     struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
120779     if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
120780       if( pOrder->desc ){
120781         pInfo->idxStr = "DESC";
120782       }else{
120783         pInfo->idxStr = "ASC";
120784       }
120785       pInfo->orderByConsumed = 1;
120786     }
120787   }
120788
120789   assert( p->pSegments==0 );
120790   return SQLITE_OK;
120791 }
120792
120793 /*
120794 ** Implementation of xOpen method.
120795 */
120796 static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
120797   sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */
120798
120799   UNUSED_PARAMETER(pVTab);
120800
120801   /* Allocate a buffer large enough for an Fts3Cursor structure. If the
120802   ** allocation succeeds, zero it and return SQLITE_OK. Otherwise, 
120803   ** if the allocation fails, return SQLITE_NOMEM.
120804   */
120805   *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
120806   if( !pCsr ){
120807     return SQLITE_NOMEM;
120808   }
120809   memset(pCsr, 0, sizeof(Fts3Cursor));
120810   return SQLITE_OK;
120811 }
120812
120813 /*
120814 ** Close the cursor.  For additional information see the documentation
120815 ** on the xClose method of the virtual table interface.
120816 */
120817 static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
120818   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
120819   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
120820   sqlite3_finalize(pCsr->pStmt);
120821   sqlite3Fts3ExprFree(pCsr->pExpr);
120822   sqlite3Fts3FreeDeferredTokens(pCsr);
120823   sqlite3_free(pCsr->aDoclist);
120824   sqlite3_free(pCsr->aMatchinfo);
120825   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
120826   sqlite3_free(pCsr);
120827   return SQLITE_OK;
120828 }
120829
120830 /*
120831 ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
120832 ** compose and prepare an SQL statement of the form:
120833 **
120834 **    "SELECT <columns> FROM %_content WHERE rowid = ?"
120835 **
120836 ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
120837 ** it. If an error occurs, return an SQLite error code.
120838 **
120839 ** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLITE_OK.
120840 */
120841 static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlite3_stmt **ppStmt){
120842   int rc = SQLITE_OK;
120843   if( pCsr->pStmt==0 ){
120844     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
120845     char *zSql;
120846     zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
120847     if( !zSql ) return SQLITE_NOMEM;
120848     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
120849     sqlite3_free(zSql);
120850   }
120851   *ppStmt = pCsr->pStmt;
120852   return rc;
120853 }
120854
120855 /*
120856 ** Position the pCsr->pStmt statement so that it is on the row
120857 ** of the %_content table that contains the last match.  Return
120858 ** SQLITE_OK on success.  
120859 */
120860 static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
120861   int rc = SQLITE_OK;
120862   if( pCsr->isRequireSeek ){
120863     sqlite3_stmt *pStmt = 0;
120864
120865     rc = fts3CursorSeekStmt(pCsr, &pStmt);
120866     if( rc==SQLITE_OK ){
120867       sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
120868       pCsr->isRequireSeek = 0;
120869       if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
120870         return SQLITE_OK;
120871       }else{
120872         rc = sqlite3_reset(pCsr->pStmt);
120873         if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
120874           /* If no row was found and no error has occurred, then the %_content
120875           ** table is missing a row that is present in the full-text index.
120876           ** The data structures are corrupt.  */
120877           rc = FTS_CORRUPT_VTAB;
120878           pCsr->isEof = 1;
120879         }
120880       }
120881     }
120882   }
120883
120884   if( rc!=SQLITE_OK && pContext ){
120885     sqlite3_result_error_code(pContext, rc);
120886   }
120887   return rc;
120888 }
120889
120890 /*
120891 ** This function is used to process a single interior node when searching
120892 ** a b-tree for a term or term prefix. The node data is passed to this 
120893 ** function via the zNode/nNode parameters. The term to search for is
120894 ** passed in zTerm/nTerm.
120895 **
120896 ** If piFirst is not NULL, then this function sets *piFirst to the blockid
120897 ** of the child node that heads the sub-tree that may contain the term.
120898 **
120899 ** If piLast is not NULL, then *piLast is set to the right-most child node
120900 ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
120901 ** a prefix.
120902 **
120903 ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
120904 */
120905 static int fts3ScanInteriorNode(
120906   const char *zTerm,              /* Term to select leaves for */
120907   int nTerm,                      /* Size of term zTerm in bytes */
120908   const char *zNode,              /* Buffer containing segment interior node */
120909   int nNode,                      /* Size of buffer at zNode */
120910   sqlite3_int64 *piFirst,         /* OUT: Selected child node */
120911   sqlite3_int64 *piLast           /* OUT: Selected child node */
120912 ){
120913   int rc = SQLITE_OK;             /* Return code */
120914   const char *zCsr = zNode;       /* Cursor to iterate through node */
120915   const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
120916   char *zBuffer = 0;              /* Buffer to load terms into */
120917   int nAlloc = 0;                 /* Size of allocated buffer */
120918   int isFirstTerm = 1;            /* True when processing first term on page */
120919   sqlite3_int64 iChild;           /* Block id of child node to descend to */
120920
120921   /* Skip over the 'height' varint that occurs at the start of every 
120922   ** interior node. Then load the blockid of the left-child of the b-tree
120923   ** node into variable iChild.  
120924   **
120925   ** Even if the data structure on disk is corrupted, this (reading two
120926   ** varints from the buffer) does not risk an overread. If zNode is a
120927   ** root node, then the buffer comes from a SELECT statement. SQLite does
120928   ** not make this guarantee explicitly, but in practice there are always
120929   ** either more than 20 bytes of allocated space following the nNode bytes of
120930   ** contents, or two zero bytes. Or, if the node is read from the %_segments
120931   ** table, then there are always 20 bytes of zeroed padding following the
120932   ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
120933   */
120934   zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
120935   zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
120936   if( zCsr>zEnd ){
120937     return FTS_CORRUPT_VTAB;
120938   }
120939   
120940   while( zCsr<zEnd && (piFirst || piLast) ){
120941     int cmp;                      /* memcmp() result */
120942     int nSuffix;                  /* Size of term suffix */
120943     int nPrefix = 0;              /* Size of term prefix */
120944     int nBuffer;                  /* Total term size */
120945   
120946     /* Load the next term on the node into zBuffer. Use realloc() to expand
120947     ** the size of zBuffer if required.  */
120948     if( !isFirstTerm ){
120949       zCsr += sqlite3Fts3GetVarint32(zCsr, &nPrefix);
120950     }
120951     isFirstTerm = 0;
120952     zCsr += sqlite3Fts3GetVarint32(zCsr, &nSuffix);
120953     
120954     if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
120955       rc = FTS_CORRUPT_VTAB;
120956       goto finish_scan;
120957     }
120958     if( nPrefix+nSuffix>nAlloc ){
120959       char *zNew;
120960       nAlloc = (nPrefix+nSuffix) * 2;
120961       zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
120962       if( !zNew ){
120963         rc = SQLITE_NOMEM;
120964         goto finish_scan;
120965       }
120966       zBuffer = zNew;
120967     }
120968     assert( zBuffer );
120969     memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
120970     nBuffer = nPrefix + nSuffix;
120971     zCsr += nSuffix;
120972
120973     /* Compare the term we are searching for with the term just loaded from
120974     ** the interior node. If the specified term is greater than or equal
120975     ** to the term from the interior node, then all terms on the sub-tree 
120976     ** headed by node iChild are smaller than zTerm. No need to search 
120977     ** iChild.
120978     **
120979     ** If the interior node term is larger than the specified term, then
120980     ** the tree headed by iChild may contain the specified term.
120981     */
120982     cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
120983     if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
120984       *piFirst = iChild;
120985       piFirst = 0;
120986     }
120987
120988     if( piLast && cmp<0 ){
120989       *piLast = iChild;
120990       piLast = 0;
120991     }
120992
120993     iChild++;
120994   };
120995
120996   if( piFirst ) *piFirst = iChild;
120997   if( piLast ) *piLast = iChild;
120998
120999  finish_scan:
121000   sqlite3_free(zBuffer);
121001   return rc;
121002 }
121003
121004
121005 /*
121006 ** The buffer pointed to by argument zNode (size nNode bytes) contains an
121007 ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
121008 ** contains a term. This function searches the sub-tree headed by the zNode
121009 ** node for the range of leaf nodes that may contain the specified term
121010 ** or terms for which the specified term is a prefix.
121011 **
121012 ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the 
121013 ** left-most leaf node in the tree that may contain the specified term.
121014 ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
121015 ** right-most leaf node that may contain a term for which the specified
121016 ** term is a prefix.
121017 **
121018 ** It is possible that the range of returned leaf nodes does not contain 
121019 ** the specified term or any terms for which it is a prefix. However, if the 
121020 ** segment does contain any such terms, they are stored within the identified
121021 ** range. Because this function only inspects interior segment nodes (and
121022 ** never loads leaf nodes into memory), it is not possible to be sure.
121023 **
121024 ** If an error occurs, an error code other than SQLITE_OK is returned.
121025 */ 
121026 static int fts3SelectLeaf(
121027   Fts3Table *p,                   /* Virtual table handle */
121028   const char *zTerm,              /* Term to select leaves for */
121029   int nTerm,                      /* Size of term zTerm in bytes */
121030   const char *zNode,              /* Buffer containing segment interior node */
121031   int nNode,                      /* Size of buffer at zNode */
121032   sqlite3_int64 *piLeaf,          /* Selected leaf node */
121033   sqlite3_int64 *piLeaf2          /* Selected leaf node */
121034 ){
121035   int rc;                         /* Return code */
121036   int iHeight;                    /* Height of this node in tree */
121037
121038   assert( piLeaf || piLeaf2 );
121039
121040   sqlite3Fts3GetVarint32(zNode, &iHeight);
121041   rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
121042   assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
121043
121044   if( rc==SQLITE_OK && iHeight>1 ){
121045     char *zBlob = 0;              /* Blob read from %_segments table */
121046     int nBlob;                    /* Size of zBlob in bytes */
121047
121048     if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
121049       rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
121050       if( rc==SQLITE_OK ){
121051         rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
121052       }
121053       sqlite3_free(zBlob);
121054       piLeaf = 0;
121055       zBlob = 0;
121056     }
121057
121058     if( rc==SQLITE_OK ){
121059       rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
121060     }
121061     if( rc==SQLITE_OK ){
121062       rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
121063     }
121064     sqlite3_free(zBlob);
121065   }
121066
121067   return rc;
121068 }
121069
121070 /*
121071 ** This function is used to create delta-encoded serialized lists of FTS3 
121072 ** varints. Each call to this function appends a single varint to a list.
121073 */
121074 static void fts3PutDeltaVarint(
121075   char **pp,                      /* IN/OUT: Output pointer */
121076   sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
121077   sqlite3_int64 iVal              /* Write this value to the list */
121078 ){
121079   assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
121080   *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
121081   *piPrev = iVal;
121082 }
121083
121084 /*
121085 ** When this function is called, *ppPoslist is assumed to point to the 
121086 ** start of a position-list. After it returns, *ppPoslist points to the
121087 ** first byte after the position-list.
121088 **
121089 ** A position list is list of positions (delta encoded) and columns for 
121090 ** a single document record of a doclist.  So, in other words, this
121091 ** routine advances *ppPoslist so that it points to the next docid in
121092 ** the doclist, or to the first byte past the end of the doclist.
121093 **
121094 ** If pp is not NULL, then the contents of the position list are copied
121095 ** to *pp. *pp is set to point to the first byte past the last byte copied
121096 ** before this function returns.
121097 */
121098 static void fts3PoslistCopy(char **pp, char **ppPoslist){
121099   char *pEnd = *ppPoslist;
121100   char c = 0;
121101
121102   /* The end of a position list is marked by a zero encoded as an FTS3 
121103   ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
121104   ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
121105   ** of some other, multi-byte, value.
121106   **
121107   ** The following while-loop moves pEnd to point to the first byte that is not 
121108   ** immediately preceded by a byte with the 0x80 bit set. Then increments
121109   ** pEnd once more so that it points to the byte immediately following the
121110   ** last byte in the position-list.
121111   */
121112   while( *pEnd | c ){
121113     c = *pEnd++ & 0x80;
121114     testcase( c!=0 && (*pEnd)==0 );
121115   }
121116   pEnd++;  /* Advance past the POS_END terminator byte */
121117
121118   if( pp ){
121119     int n = (int)(pEnd - *ppPoslist);
121120     char *p = *pp;
121121     memcpy(p, *ppPoslist, n);
121122     p += n;
121123     *pp = p;
121124   }
121125   *ppPoslist = pEnd;
121126 }
121127
121128 /*
121129 ** When this function is called, *ppPoslist is assumed to point to the 
121130 ** start of a column-list. After it returns, *ppPoslist points to the
121131 ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
121132 **
121133 ** A column-list is list of delta-encoded positions for a single column
121134 ** within a single document within a doclist.
121135 **
121136 ** The column-list is terminated either by a POS_COLUMN varint (1) or
121137 ** a POS_END varint (0).  This routine leaves *ppPoslist pointing to
121138 ** the POS_COLUMN or POS_END that terminates the column-list.
121139 **
121140 ** If pp is not NULL, then the contents of the column-list are copied
121141 ** to *pp. *pp is set to point to the first byte past the last byte copied
121142 ** before this function returns.  The POS_COLUMN or POS_END terminator
121143 ** is not copied into *pp.
121144 */
121145 static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
121146   char *pEnd = *ppPoslist;
121147   char c = 0;
121148
121149   /* A column-list is terminated by either a 0x01 or 0x00 byte that is
121150   ** not part of a multi-byte varint.
121151   */
121152   while( 0xFE & (*pEnd | c) ){
121153     c = *pEnd++ & 0x80;
121154     testcase( c!=0 && ((*pEnd)&0xfe)==0 );
121155   }
121156   if( pp ){
121157     int n = (int)(pEnd - *ppPoslist);
121158     char *p = *pp;
121159     memcpy(p, *ppPoslist, n);
121160     p += n;
121161     *pp = p;
121162   }
121163   *ppPoslist = pEnd;
121164 }
121165
121166 /*
121167 ** Value used to signify the end of an position-list. This is safe because
121168 ** it is not possible to have a document with 2^31 terms.
121169 */
121170 #define POSITION_LIST_END 0x7fffffff
121171
121172 /*
121173 ** This function is used to help parse position-lists. When this function is
121174 ** called, *pp may point to the start of the next varint in the position-list
121175 ** being parsed, or it may point to 1 byte past the end of the position-list
121176 ** (in which case **pp will be a terminator bytes POS_END (0) or
121177 ** (1)).
121178 **
121179 ** If *pp points past the end of the current position-list, set *pi to 
121180 ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
121181 ** increment the current value of *pi by the value read, and set *pp to
121182 ** point to the next value before returning.
121183 **
121184 ** Before calling this routine *pi must be initialized to the value of
121185 ** the previous position, or zero if we are reading the first position
121186 ** in the position-list.  Because positions are delta-encoded, the value
121187 ** of the previous position is needed in order to compute the value of
121188 ** the next position.
121189 */
121190 static void fts3ReadNextPos(
121191   char **pp,                    /* IN/OUT: Pointer into position-list buffer */
121192   sqlite3_int64 *pi             /* IN/OUT: Value read from position-list */
121193 ){
121194   if( (**pp)&0xFE ){
121195     fts3GetDeltaVarint(pp, pi);
121196     *pi -= 2;
121197   }else{
121198     *pi = POSITION_LIST_END;
121199   }
121200 }
121201
121202 /*
121203 ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
121204 ** the value of iCol encoded as a varint to *pp.   This will start a new
121205 ** column list.
121206 **
121207 ** Set *pp to point to the byte just after the last byte written before 
121208 ** returning (do not modify it if iCol==0). Return the total number of bytes
121209 ** written (0 if iCol==0).
121210 */
121211 static int fts3PutColNumber(char **pp, int iCol){
121212   int n = 0;                      /* Number of bytes written */
121213   if( iCol ){
121214     char *p = *pp;                /* Output pointer */
121215     n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
121216     *p = 0x01;
121217     *pp = &p[n];
121218   }
121219   return n;
121220 }
121221
121222 /*
121223 ** Compute the union of two position lists.  The output written
121224 ** into *pp contains all positions of both *pp1 and *pp2 in sorted
121225 ** order and with any duplicates removed.  All pointers are
121226 ** updated appropriately.   The caller is responsible for insuring
121227 ** that there is enough space in *pp to hold the complete output.
121228 */
121229 static void fts3PoslistMerge(
121230   char **pp,                      /* Output buffer */
121231   char **pp1,                     /* Left input list */
121232   char **pp2                      /* Right input list */
121233 ){
121234   char *p = *pp;
121235   char *p1 = *pp1;
121236   char *p2 = *pp2;
121237
121238   while( *p1 || *p2 ){
121239     int iCol1;         /* The current column index in pp1 */
121240     int iCol2;         /* The current column index in pp2 */
121241
121242     if( *p1==POS_COLUMN ) sqlite3Fts3GetVarint32(&p1[1], &iCol1);
121243     else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
121244     else iCol1 = 0;
121245
121246     if( *p2==POS_COLUMN ) sqlite3Fts3GetVarint32(&p2[1], &iCol2);
121247     else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
121248     else iCol2 = 0;
121249
121250     if( iCol1==iCol2 ){
121251       sqlite3_int64 i1 = 0;       /* Last position from pp1 */
121252       sqlite3_int64 i2 = 0;       /* Last position from pp2 */
121253       sqlite3_int64 iPrev = 0;
121254       int n = fts3PutColNumber(&p, iCol1);
121255       p1 += n;
121256       p2 += n;
121257
121258       /* At this point, both p1 and p2 point to the start of column-lists
121259       ** for the same column (the column with index iCol1 and iCol2).
121260       ** A column-list is a list of non-negative delta-encoded varints, each 
121261       ** incremented by 2 before being stored. Each list is terminated by a
121262       ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
121263       ** and writes the results to buffer p. p is left pointing to the byte
121264       ** after the list written. No terminator (POS_END or POS_COLUMN) is
121265       ** written to the output.
121266       */
121267       fts3GetDeltaVarint(&p1, &i1);
121268       fts3GetDeltaVarint(&p2, &i2);
121269       do {
121270         fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2); 
121271         iPrev -= 2;
121272         if( i1==i2 ){
121273           fts3ReadNextPos(&p1, &i1);
121274           fts3ReadNextPos(&p2, &i2);
121275         }else if( i1<i2 ){
121276           fts3ReadNextPos(&p1, &i1);
121277         }else{
121278           fts3ReadNextPos(&p2, &i2);
121279         }
121280       }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
121281     }else if( iCol1<iCol2 ){
121282       p1 += fts3PutColNumber(&p, iCol1);
121283       fts3ColumnlistCopy(&p, &p1);
121284     }else{
121285       p2 += fts3PutColNumber(&p, iCol2);
121286       fts3ColumnlistCopy(&p, &p2);
121287     }
121288   }
121289
121290   *p++ = POS_END;
121291   *pp = p;
121292   *pp1 = p1 + 1;
121293   *pp2 = p2 + 1;
121294 }
121295
121296 /*
121297 ** This function is used to merge two position lists into one. When it is
121298 ** called, *pp1 and *pp2 must both point to position lists. A position-list is
121299 ** the part of a doclist that follows each document id. For example, if a row
121300 ** contains:
121301 **
121302 **     'a b c'|'x y z'|'a b b a'
121303 **
121304 ** Then the position list for this row for token 'b' would consist of:
121305 **
121306 **     0x02 0x01 0x02 0x03 0x03 0x00
121307 **
121308 ** When this function returns, both *pp1 and *pp2 are left pointing to the
121309 ** byte following the 0x00 terminator of their respective position lists.
121310 **
121311 ** If isSaveLeft is 0, an entry is added to the output position list for 
121312 ** each position in *pp2 for which there exists one or more positions in
121313 ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
121314 ** when the *pp1 token appears before the *pp2 token, but not more than nToken
121315 ** slots before it.
121316 **
121317 ** e.g. nToken==1 searches for adjacent positions.
121318 */
121319 static int fts3PoslistPhraseMerge(
121320   char **pp,                      /* IN/OUT: Preallocated output buffer */
121321   int nToken,                     /* Maximum difference in token positions */
121322   int isSaveLeft,                 /* Save the left position */
121323   int isExact,                    /* If *pp1 is exactly nTokens before *pp2 */
121324   char **pp1,                     /* IN/OUT: Left input list */
121325   char **pp2                      /* IN/OUT: Right input list */
121326 ){
121327   char *p = *pp;
121328   char *p1 = *pp1;
121329   char *p2 = *pp2;
121330   int iCol1 = 0;
121331   int iCol2 = 0;
121332
121333   /* Never set both isSaveLeft and isExact for the same invocation. */
121334   assert( isSaveLeft==0 || isExact==0 );
121335
121336   assert( p!=0 && *p1!=0 && *p2!=0 );
121337   if( *p1==POS_COLUMN ){ 
121338     p1++;
121339     p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
121340   }
121341   if( *p2==POS_COLUMN ){ 
121342     p2++;
121343     p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
121344   }
121345
121346   while( 1 ){
121347     if( iCol1==iCol2 ){
121348       char *pSave = p;
121349       sqlite3_int64 iPrev = 0;
121350       sqlite3_int64 iPos1 = 0;
121351       sqlite3_int64 iPos2 = 0;
121352
121353       if( iCol1 ){
121354         *p++ = POS_COLUMN;
121355         p += sqlite3Fts3PutVarint(p, iCol1);
121356       }
121357
121358       assert( *p1!=POS_END && *p1!=POS_COLUMN );
121359       assert( *p2!=POS_END && *p2!=POS_COLUMN );
121360       fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
121361       fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
121362
121363       while( 1 ){
121364         if( iPos2==iPos1+nToken 
121365          || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken) 
121366         ){
121367           sqlite3_int64 iSave;
121368           iSave = isSaveLeft ? iPos1 : iPos2;
121369           fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
121370           pSave = 0;
121371           assert( p );
121372         }
121373         if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
121374           if( (*p2&0xFE)==0 ) break;
121375           fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
121376         }else{
121377           if( (*p1&0xFE)==0 ) break;
121378           fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
121379         }
121380       }
121381
121382       if( pSave ){
121383         assert( pp && p );
121384         p = pSave;
121385       }
121386
121387       fts3ColumnlistCopy(0, &p1);
121388       fts3ColumnlistCopy(0, &p2);
121389       assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
121390       if( 0==*p1 || 0==*p2 ) break;
121391
121392       p1++;
121393       p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
121394       p2++;
121395       p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
121396     }
121397
121398     /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
121399     ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
121400     ** end of the position list, or the 0x01 that precedes the next 
121401     ** column-number in the position list. 
121402     */
121403     else if( iCol1<iCol2 ){
121404       fts3ColumnlistCopy(0, &p1);
121405       if( 0==*p1 ) break;
121406       p1++;
121407       p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
121408     }else{
121409       fts3ColumnlistCopy(0, &p2);
121410       if( 0==*p2 ) break;
121411       p2++;
121412       p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
121413     }
121414   }
121415
121416   fts3PoslistCopy(0, &p2);
121417   fts3PoslistCopy(0, &p1);
121418   *pp1 = p1;
121419   *pp2 = p2;
121420   if( *pp==p ){
121421     return 0;
121422   }
121423   *p++ = 0x00;
121424   *pp = p;
121425   return 1;
121426 }
121427
121428 /*
121429 ** Merge two position-lists as required by the NEAR operator. The argument
121430 ** position lists correspond to the left and right phrases of an expression 
121431 ** like:
121432 **
121433 **     "phrase 1" NEAR "phrase number 2"
121434 **
121435 ** Position list *pp1 corresponds to the left-hand side of the NEAR 
121436 ** expression and *pp2 to the right. As usual, the indexes in the position 
121437 ** lists are the offsets of the last token in each phrase (tokens "1" and "2" 
121438 ** in the example above).
121439 **
121440 ** The output position list - written to *pp - is a copy of *pp2 with those
121441 ** entries that are not sufficiently NEAR entries in *pp1 removed.
121442 */
121443 static int fts3PoslistNearMerge(
121444   char **pp,                      /* Output buffer */
121445   char *aTmp,                     /* Temporary buffer space */
121446   int nRight,                     /* Maximum difference in token positions */
121447   int nLeft,                      /* Maximum difference in token positions */
121448   char **pp1,                     /* IN/OUT: Left input list */
121449   char **pp2                      /* IN/OUT: Right input list */
121450 ){
121451   char *p1 = *pp1;
121452   char *p2 = *pp2;
121453
121454   char *pTmp1 = aTmp;
121455   char *pTmp2;
121456   char *aTmp2;
121457   int res = 1;
121458
121459   fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
121460   aTmp2 = pTmp2 = pTmp1;
121461   *pp1 = p1;
121462   *pp2 = p2;
121463   fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
121464   if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
121465     fts3PoslistMerge(pp, &aTmp, &aTmp2);
121466   }else if( pTmp1!=aTmp ){
121467     fts3PoslistCopy(pp, &aTmp);
121468   }else if( pTmp2!=aTmp2 ){
121469     fts3PoslistCopy(pp, &aTmp2);
121470   }else{
121471     res = 0;
121472   }
121473
121474   return res;
121475 }
121476
121477 /* 
121478 ** An instance of this function is used to merge together the (potentially
121479 ** large number of) doclists for each term that matches a prefix query.
121480 ** See function fts3TermSelectMerge() for details.
121481 */
121482 typedef struct TermSelect TermSelect;
121483 struct TermSelect {
121484   char *aaOutput[16];             /* Malloc'd output buffers */
121485   int anOutput[16];               /* Size each output buffer in bytes */
121486 };
121487
121488 /*
121489 ** This function is used to read a single varint from a buffer. Parameter
121490 ** pEnd points 1 byte past the end of the buffer. When this function is
121491 ** called, if *pp points to pEnd or greater, then the end of the buffer
121492 ** has been reached. In this case *pp is set to 0 and the function returns.
121493 **
121494 ** If *pp does not point to or past pEnd, then a single varint is read
121495 ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
121496 **
121497 ** If bDescIdx is false, the value read is added to *pVal before returning.
121498 ** If it is true, the value read is subtracted from *pVal before this 
121499 ** function returns.
121500 */
121501 static void fts3GetDeltaVarint3(
121502   char **pp,                      /* IN/OUT: Point to read varint from */
121503   char *pEnd,                     /* End of buffer */
121504   int bDescIdx,                   /* True if docids are descending */
121505   sqlite3_int64 *pVal             /* IN/OUT: Integer value */
121506 ){
121507   if( *pp>=pEnd ){
121508     *pp = 0;
121509   }else{
121510     sqlite3_int64 iVal;
121511     *pp += sqlite3Fts3GetVarint(*pp, &iVal);
121512     if( bDescIdx ){
121513       *pVal -= iVal;
121514     }else{
121515       *pVal += iVal;
121516     }
121517   }
121518 }
121519
121520 /*
121521 ** This function is used to write a single varint to a buffer. The varint
121522 ** is written to *pp. Before returning, *pp is set to point 1 byte past the
121523 ** end of the value written.
121524 **
121525 ** If *pbFirst is zero when this function is called, the value written to
121526 ** the buffer is that of parameter iVal. 
121527 **
121528 ** If *pbFirst is non-zero when this function is called, then the value 
121529 ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
121530 ** (if bDescIdx is non-zero).
121531 **
121532 ** Before returning, this function always sets *pbFirst to 1 and *piPrev
121533 ** to the value of parameter iVal.
121534 */
121535 static void fts3PutDeltaVarint3(
121536   char **pp,                      /* IN/OUT: Output pointer */
121537   int bDescIdx,                   /* True for descending docids */
121538   sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
121539   int *pbFirst,                   /* IN/OUT: True after first int written */
121540   sqlite3_int64 iVal              /* Write this value to the list */
121541 ){
121542   sqlite3_int64 iWrite;
121543   if( bDescIdx==0 || *pbFirst==0 ){
121544     iWrite = iVal - *piPrev;
121545   }else{
121546     iWrite = *piPrev - iVal;
121547   }
121548   assert( *pbFirst || *piPrev==0 );
121549   assert( *pbFirst==0 || iWrite>0 );
121550   *pp += sqlite3Fts3PutVarint(*pp, iWrite);
121551   *piPrev = iVal;
121552   *pbFirst = 1;
121553 }
121554
121555
121556 /*
121557 ** This macro is used by various functions that merge doclists. The two
121558 ** arguments are 64-bit docid values. If the value of the stack variable
121559 ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2). 
121560 ** Otherwise, (i2-i1).
121561 **
121562 ** Using this makes it easier to write code that can merge doclists that are
121563 ** sorted in either ascending or descending order.
121564 */
121565 #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
121566
121567 /*
121568 ** This function does an "OR" merge of two doclists (output contains all
121569 ** positions contained in either argument doclist). If the docids in the 
121570 ** input doclists are sorted in ascending order, parameter bDescDoclist
121571 ** should be false. If they are sorted in ascending order, it should be
121572 ** passed a non-zero value.
121573 **
121574 ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
121575 ** containing the output doclist and SQLITE_OK is returned. In this case
121576 ** *pnOut is set to the number of bytes in the output doclist.
121577 **
121578 ** If an error occurs, an SQLite error code is returned. The output values
121579 ** are undefined in this case.
121580 */
121581 static int fts3DoclistOrMerge(
121582   int bDescDoclist,               /* True if arguments are desc */
121583   char *a1, int n1,               /* First doclist */
121584   char *a2, int n2,               /* Second doclist */
121585   char **paOut, int *pnOut        /* OUT: Malloc'd doclist */
121586 ){
121587   sqlite3_int64 i1 = 0;
121588   sqlite3_int64 i2 = 0;
121589   sqlite3_int64 iPrev = 0;
121590   char *pEnd1 = &a1[n1];
121591   char *pEnd2 = &a2[n2];
121592   char *p1 = a1;
121593   char *p2 = a2;
121594   char *p;
121595   char *aOut;
121596   int bFirstOut = 0;
121597
121598   *paOut = 0;
121599   *pnOut = 0;
121600
121601   /* Allocate space for the output. Both the input and output doclists
121602   ** are delta encoded. If they are in ascending order (bDescDoclist==0),
121603   ** then the first docid in each list is simply encoded as a varint. For
121604   ** each subsequent docid, the varint stored is the difference between the
121605   ** current and previous docid (a positive number - since the list is in
121606   ** ascending order).
121607   **
121608   ** The first docid written to the output is therefore encoded using the 
121609   ** same number of bytes as it is in whichever of the input lists it is
121610   ** read from. And each subsequent docid read from the same input list 
121611   ** consumes either the same or less bytes as it did in the input (since
121612   ** the difference between it and the previous value in the output must
121613   ** be a positive value less than or equal to the delta value read from 
121614   ** the input list). The same argument applies to all but the first docid
121615   ** read from the 'other' list. And to the contents of all position lists
121616   ** that will be copied and merged from the input to the output.
121617   **
121618   ** However, if the first docid copied to the output is a negative number,
121619   ** then the encoding of the first docid from the 'other' input list may
121620   ** be larger in the output than it was in the input (since the delta value
121621   ** may be a larger positive integer than the actual docid).
121622   **
121623   ** The space required to store the output is therefore the sum of the
121624   ** sizes of the two inputs, plus enough space for exactly one of the input
121625   ** docids to grow. 
121626   **
121627   ** A symetric argument may be made if the doclists are in descending 
121628   ** order.
121629   */
121630   aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
121631   if( !aOut ) return SQLITE_NOMEM;
121632
121633   p = aOut;
121634   fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
121635   fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
121636   while( p1 || p2 ){
121637     sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
121638
121639     if( p2 && p1 && iDiff==0 ){
121640       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
121641       fts3PoslistMerge(&p, &p1, &p2);
121642       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
121643       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
121644     }else if( !p2 || (p1 && iDiff<0) ){
121645       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
121646       fts3PoslistCopy(&p, &p1);
121647       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
121648     }else{
121649       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
121650       fts3PoslistCopy(&p, &p2);
121651       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
121652     }
121653   }
121654
121655   *paOut = aOut;
121656   *pnOut = (int)(p-aOut);
121657   assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
121658   return SQLITE_OK;
121659 }
121660
121661 /*
121662 ** This function does a "phrase" merge of two doclists. In a phrase merge,
121663 ** the output contains a copy of each position from the right-hand input
121664 ** doclist for which there is a position in the left-hand input doclist
121665 ** exactly nDist tokens before it.
121666 **
121667 ** If the docids in the input doclists are sorted in ascending order,
121668 ** parameter bDescDoclist should be false. If they are sorted in ascending 
121669 ** order, it should be passed a non-zero value.
121670 **
121671 ** The right-hand input doclist is overwritten by this function.
121672 */
121673 static void fts3DoclistPhraseMerge(
121674   int bDescDoclist,               /* True if arguments are desc */
121675   int nDist,                      /* Distance from left to right (1=adjacent) */
121676   char *aLeft, int nLeft,         /* Left doclist */
121677   char *aRight, int *pnRight      /* IN/OUT: Right/output doclist */
121678 ){
121679   sqlite3_int64 i1 = 0;
121680   sqlite3_int64 i2 = 0;
121681   sqlite3_int64 iPrev = 0;
121682   char *pEnd1 = &aLeft[nLeft];
121683   char *pEnd2 = &aRight[*pnRight];
121684   char *p1 = aLeft;
121685   char *p2 = aRight;
121686   char *p;
121687   int bFirstOut = 0;
121688   char *aOut = aRight;
121689
121690   assert( nDist>0 );
121691
121692   p = aOut;
121693   fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
121694   fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
121695
121696   while( p1 && p2 ){
121697     sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
121698     if( iDiff==0 ){
121699       char *pSave = p;
121700       sqlite3_int64 iPrevSave = iPrev;
121701       int bFirstOutSave = bFirstOut;
121702
121703       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
121704       if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
121705         p = pSave;
121706         iPrev = iPrevSave;
121707         bFirstOut = bFirstOutSave;
121708       }
121709       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
121710       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
121711     }else if( iDiff<0 ){
121712       fts3PoslistCopy(0, &p1);
121713       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
121714     }else{
121715       fts3PoslistCopy(0, &p2);
121716       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
121717     }
121718   }
121719
121720   *pnRight = (int)(p - aOut);
121721 }
121722
121723 /*
121724 ** Argument pList points to a position list nList bytes in size. This
121725 ** function checks to see if the position list contains any entries for
121726 ** a token in position 0 (of any column). If so, it writes argument iDelta
121727 ** to the output buffer pOut, followed by a position list consisting only
121728 ** of the entries from pList at position 0, and terminated by an 0x00 byte.
121729 ** The value returned is the number of bytes written to pOut (if any).
121730 */
121731 SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
121732   sqlite3_int64 iDelta,           /* Varint that may be written to pOut */
121733   char *pList,                    /* Position list (no 0x00 term) */
121734   int nList,                      /* Size of pList in bytes */
121735   char *pOut                      /* Write output here */
121736 ){
121737   int nOut = 0;
121738   int bWritten = 0;               /* True once iDelta has been written */
121739   char *p = pList;
121740   char *pEnd = &pList[nList];
121741
121742   if( *p!=0x01 ){
121743     if( *p==0x02 ){
121744       nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
121745       pOut[nOut++] = 0x02;
121746       bWritten = 1;
121747     }
121748     fts3ColumnlistCopy(0, &p);
121749   }
121750
121751   while( p<pEnd && *p==0x01 ){
121752     sqlite3_int64 iCol;
121753     p++;
121754     p += sqlite3Fts3GetVarint(p, &iCol);
121755     if( *p==0x02 ){
121756       if( bWritten==0 ){
121757         nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
121758         bWritten = 1;
121759       }
121760       pOut[nOut++] = 0x01;
121761       nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
121762       pOut[nOut++] = 0x02;
121763     }
121764     fts3ColumnlistCopy(0, &p);
121765   }
121766   if( bWritten ){
121767     pOut[nOut++] = 0x00;
121768   }
121769
121770   return nOut;
121771 }
121772
121773
121774 /*
121775 ** Merge all doclists in the TermSelect.aaOutput[] array into a single
121776 ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
121777 ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
121778 **
121779 ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
121780 ** the responsibility of the caller to free any doclists left in the
121781 ** TermSelect.aaOutput[] array.
121782 */
121783 static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
121784   char *aOut = 0;
121785   int nOut = 0;
121786   int i;
121787
121788   /* Loop through the doclists in the aaOutput[] array. Merge them all
121789   ** into a single doclist.
121790   */
121791   for(i=0; i<SizeofArray(pTS->aaOutput); i++){
121792     if( pTS->aaOutput[i] ){
121793       if( !aOut ){
121794         aOut = pTS->aaOutput[i];
121795         nOut = pTS->anOutput[i];
121796         pTS->aaOutput[i] = 0;
121797       }else{
121798         int nNew;
121799         char *aNew;
121800
121801         int rc = fts3DoclistOrMerge(p->bDescIdx, 
121802             pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
121803         );
121804         if( rc!=SQLITE_OK ){
121805           sqlite3_free(aOut);
121806           return rc;
121807         }
121808
121809         sqlite3_free(pTS->aaOutput[i]);
121810         sqlite3_free(aOut);
121811         pTS->aaOutput[i] = 0;
121812         aOut = aNew;
121813         nOut = nNew;
121814       }
121815     }
121816   }
121817
121818   pTS->aaOutput[0] = aOut;
121819   pTS->anOutput[0] = nOut;
121820   return SQLITE_OK;
121821 }
121822
121823 /*
121824 ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
121825 ** as the first argument. The merge is an "OR" merge (see function
121826 ** fts3DoclistOrMerge() for details).
121827 **
121828 ** This function is called with the doclist for each term that matches
121829 ** a queried prefix. It merges all these doclists into one, the doclist
121830 ** for the specified prefix. Since there can be a very large number of
121831 ** doclists to merge, the merging is done pair-wise using the TermSelect
121832 ** object.
121833 **
121834 ** This function returns SQLITE_OK if the merge is successful, or an
121835 ** SQLite error code (SQLITE_NOMEM) if an error occurs.
121836 */
121837 static int fts3TermSelectMerge(
121838   Fts3Table *p,                   /* FTS table handle */
121839   TermSelect *pTS,                /* TermSelect object to merge into */
121840   char *aDoclist,                 /* Pointer to doclist */
121841   int nDoclist                    /* Size of aDoclist in bytes */
121842 ){
121843   if( pTS->aaOutput[0]==0 ){
121844     /* If this is the first term selected, copy the doclist to the output
121845     ** buffer using memcpy(). */
121846     pTS->aaOutput[0] = sqlite3_malloc(nDoclist);
121847     pTS->anOutput[0] = nDoclist;
121848     if( pTS->aaOutput[0] ){
121849       memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
121850     }else{
121851       return SQLITE_NOMEM;
121852     }
121853   }else{
121854     char *aMerge = aDoclist;
121855     int nMerge = nDoclist;
121856     int iOut;
121857
121858     for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
121859       if( pTS->aaOutput[iOut]==0 ){
121860         assert( iOut>0 );
121861         pTS->aaOutput[iOut] = aMerge;
121862         pTS->anOutput[iOut] = nMerge;
121863         break;
121864       }else{
121865         char *aNew;
121866         int nNew;
121867
121868         int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge, 
121869             pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
121870         );
121871         if( rc!=SQLITE_OK ){
121872           if( aMerge!=aDoclist ) sqlite3_free(aMerge);
121873           return rc;
121874         }
121875
121876         if( aMerge!=aDoclist ) sqlite3_free(aMerge);
121877         sqlite3_free(pTS->aaOutput[iOut]);
121878         pTS->aaOutput[iOut] = 0;
121879   
121880         aMerge = aNew;
121881         nMerge = nNew;
121882         if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
121883           pTS->aaOutput[iOut] = aMerge;
121884           pTS->anOutput[iOut] = nMerge;
121885         }
121886       }
121887     }
121888   }
121889   return SQLITE_OK;
121890 }
121891
121892 /*
121893 ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
121894 */
121895 static int fts3SegReaderCursorAppend(
121896   Fts3MultiSegReader *pCsr, 
121897   Fts3SegReader *pNew
121898 ){
121899   if( (pCsr->nSegment%16)==0 ){
121900     Fts3SegReader **apNew;
121901     int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
121902     apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
121903     if( !apNew ){
121904       sqlite3Fts3SegReaderFree(pNew);
121905       return SQLITE_NOMEM;
121906     }
121907     pCsr->apSegment = apNew;
121908   }
121909   pCsr->apSegment[pCsr->nSegment++] = pNew;
121910   return SQLITE_OK;
121911 }
121912
121913 /*
121914 ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
121915 ** 8th argument.
121916 **
121917 ** This function returns SQLITE_OK if successful, or an SQLite error code
121918 ** otherwise.
121919 */
121920 static int fts3SegReaderCursor(
121921   Fts3Table *p,                   /* FTS3 table handle */
121922   int iLangid,                    /* Language id */
121923   int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
121924   int iLevel,                     /* Level of segments to scan */
121925   const char *zTerm,              /* Term to query for */
121926   int nTerm,                      /* Size of zTerm in bytes */
121927   int isPrefix,                   /* True for a prefix search */
121928   int isScan,                     /* True to scan from zTerm to EOF */
121929   Fts3MultiSegReader *pCsr        /* Cursor object to populate */
121930 ){
121931   int rc = SQLITE_OK;             /* Error code */
121932   sqlite3_stmt *pStmt = 0;        /* Statement to iterate through segments */
121933   int rc2;                        /* Result of sqlite3_reset() */
121934
121935   /* If iLevel is less than 0 and this is not a scan, include a seg-reader 
121936   ** for the pending-terms. If this is a scan, then this call must be being
121937   ** made by an fts4aux module, not an FTS table. In this case calling
121938   ** Fts3SegReaderPending might segfault, as the data structures used by 
121939   ** fts4aux are not completely populated. So it's easiest to filter these
121940   ** calls out here.  */
121941   if( iLevel<0 && p->aIndex ){
121942     Fts3SegReader *pSeg = 0;
121943     rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix, &pSeg);
121944     if( rc==SQLITE_OK && pSeg ){
121945       rc = fts3SegReaderCursorAppend(pCsr, pSeg);
121946     }
121947   }
121948
121949   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
121950     if( rc==SQLITE_OK ){
121951       rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
121952     }
121953
121954     while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
121955       Fts3SegReader *pSeg = 0;
121956
121957       /* Read the values returned by the SELECT into local variables. */
121958       sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
121959       sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
121960       sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
121961       int nRoot = sqlite3_column_bytes(pStmt, 4);
121962       char const *zRoot = sqlite3_column_blob(pStmt, 4);
121963
121964       /* If zTerm is not NULL, and this segment is not stored entirely on its
121965       ** root node, the range of leaves scanned can be reduced. Do this. */
121966       if( iStartBlock && zTerm ){
121967         sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
121968         rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
121969         if( rc!=SQLITE_OK ) goto finished;
121970         if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
121971       }
121972  
121973       rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1, 
121974           (isPrefix==0 && isScan==0),
121975           iStartBlock, iLeavesEndBlock, 
121976           iEndBlock, zRoot, nRoot, &pSeg
121977       );
121978       if( rc!=SQLITE_OK ) goto finished;
121979       rc = fts3SegReaderCursorAppend(pCsr, pSeg);
121980     }
121981   }
121982
121983  finished:
121984   rc2 = sqlite3_reset(pStmt);
121985   if( rc==SQLITE_DONE ) rc = rc2;
121986
121987   return rc;
121988 }
121989
121990 /*
121991 ** Set up a cursor object for iterating through a full-text index or a 
121992 ** single level therein.
121993 */
121994 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
121995   Fts3Table *p,                   /* FTS3 table handle */
121996   int iLangid,                    /* Language-id to search */
121997   int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
121998   int iLevel,                     /* Level of segments to scan */
121999   const char *zTerm,              /* Term to query for */
122000   int nTerm,                      /* Size of zTerm in bytes */
122001   int isPrefix,                   /* True for a prefix search */
122002   int isScan,                     /* True to scan from zTerm to EOF */
122003   Fts3MultiSegReader *pCsr       /* Cursor object to populate */
122004 ){
122005   assert( iIndex>=0 && iIndex<p->nIndex );
122006   assert( iLevel==FTS3_SEGCURSOR_ALL
122007       ||  iLevel==FTS3_SEGCURSOR_PENDING 
122008       ||  iLevel>=0
122009   );
122010   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
122011   assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
122012   assert( isPrefix==0 || isScan==0 );
122013
122014   memset(pCsr, 0, sizeof(Fts3MultiSegReader));
122015   return fts3SegReaderCursor(
122016       p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
122017   );
122018 }
122019
122020 /*
122021 ** In addition to its current configuration, have the Fts3MultiSegReader
122022 ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
122023 **
122024 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
122025 */
122026 static int fts3SegReaderCursorAddZero(
122027   Fts3Table *p,                   /* FTS virtual table handle */
122028   int iLangid,
122029   const char *zTerm,              /* Term to scan doclist of */
122030   int nTerm,                      /* Number of bytes in zTerm */
122031   Fts3MultiSegReader *pCsr        /* Fts3MultiSegReader to modify */
122032 ){
122033   return fts3SegReaderCursor(p, 
122034       iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
122035   );
122036 }
122037
122038 /*
122039 ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
122040 ** if isPrefix is true, to scan the doclist for all terms for which 
122041 ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
122042 ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
122043 ** an SQLite error code.
122044 **
122045 ** It is the responsibility of the caller to free this object by eventually
122046 ** passing it to fts3SegReaderCursorFree() 
122047 **
122048 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
122049 ** Output parameter *ppSegcsr is set to 0 if an error occurs.
122050 */
122051 static int fts3TermSegReaderCursor(
122052   Fts3Cursor *pCsr,               /* Virtual table cursor handle */
122053   const char *zTerm,              /* Term to query for */
122054   int nTerm,                      /* Size of zTerm in bytes */
122055   int isPrefix,                   /* True for a prefix search */
122056   Fts3MultiSegReader **ppSegcsr   /* OUT: Allocated seg-reader cursor */
122057 ){
122058   Fts3MultiSegReader *pSegcsr;    /* Object to allocate and return */
122059   int rc = SQLITE_NOMEM;          /* Return code */
122060
122061   pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
122062   if( pSegcsr ){
122063     int i;
122064     int bFound = 0;               /* True once an index has been found */
122065     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
122066
122067     if( isPrefix ){
122068       for(i=1; bFound==0 && i<p->nIndex; i++){
122069         if( p->aIndex[i].nPrefix==nTerm ){
122070           bFound = 1;
122071           rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, 
122072               i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
122073           );
122074           pSegcsr->bLookup = 1;
122075         }
122076       }
122077
122078       for(i=1; bFound==0 && i<p->nIndex; i++){
122079         if( p->aIndex[i].nPrefix==nTerm+1 ){
122080           bFound = 1;
122081           rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, 
122082               i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
122083           );
122084           if( rc==SQLITE_OK ){
122085             rc = fts3SegReaderCursorAddZero(
122086                 p, pCsr->iLangid, zTerm, nTerm, pSegcsr
122087             );
122088           }
122089         }
122090       }
122091     }
122092
122093     if( bFound==0 ){
122094       rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, 
122095           0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
122096       );
122097       pSegcsr->bLookup = !isPrefix;
122098     }
122099   }
122100
122101   *ppSegcsr = pSegcsr;
122102   return rc;
122103 }
122104
122105 /*
122106 ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
122107 */
122108 static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
122109   sqlite3Fts3SegReaderFinish(pSegcsr);
122110   sqlite3_free(pSegcsr);
122111 }
122112
122113 /*
122114 ** This function retrieves the doclist for the specified term (or term
122115 ** prefix) from the database.
122116 */
122117 static int fts3TermSelect(
122118   Fts3Table *p,                   /* Virtual table handle */
122119   Fts3PhraseToken *pTok,          /* Token to query for */
122120   int iColumn,                    /* Column to query (or -ve for all columns) */
122121   int *pnOut,                     /* OUT: Size of buffer at *ppOut */
122122   char **ppOut                    /* OUT: Malloced result buffer */
122123 ){
122124   int rc;                         /* Return code */
122125   Fts3MultiSegReader *pSegcsr;    /* Seg-reader cursor for this term */
122126   TermSelect tsc;                 /* Object for pair-wise doclist merging */
122127   Fts3SegFilter filter;           /* Segment term filter configuration */
122128
122129   pSegcsr = pTok->pSegcsr;
122130   memset(&tsc, 0, sizeof(TermSelect));
122131
122132   filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
122133         | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
122134         | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
122135         | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
122136   filter.iCol = iColumn;
122137   filter.zTerm = pTok->z;
122138   filter.nTerm = pTok->n;
122139
122140   rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
122141   while( SQLITE_OK==rc
122142       && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr)) 
122143   ){
122144     rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
122145   }
122146
122147   if( rc==SQLITE_OK ){
122148     rc = fts3TermSelectFinishMerge(p, &tsc);
122149   }
122150   if( rc==SQLITE_OK ){
122151     *ppOut = tsc.aaOutput[0];
122152     *pnOut = tsc.anOutput[0];
122153   }else{
122154     int i;
122155     for(i=0; i<SizeofArray(tsc.aaOutput); i++){
122156       sqlite3_free(tsc.aaOutput[i]);
122157     }
122158   }
122159
122160   fts3SegReaderCursorFree(pSegcsr);
122161   pTok->pSegcsr = 0;
122162   return rc;
122163 }
122164
122165 /*
122166 ** This function counts the total number of docids in the doclist stored
122167 ** in buffer aList[], size nList bytes.
122168 **
122169 ** If the isPoslist argument is true, then it is assumed that the doclist
122170 ** contains a position-list following each docid. Otherwise, it is assumed
122171 ** that the doclist is simply a list of docids stored as delta encoded 
122172 ** varints.
122173 */
122174 static int fts3DoclistCountDocids(char *aList, int nList){
122175   int nDoc = 0;                   /* Return value */
122176   if( aList ){
122177     char *aEnd = &aList[nList];   /* Pointer to one byte after EOF */
122178     char *p = aList;              /* Cursor */
122179     while( p<aEnd ){
122180       nDoc++;
122181       while( (*p++)&0x80 );     /* Skip docid varint */
122182       fts3PoslistCopy(0, &p);   /* Skip over position list */
122183     }
122184   }
122185
122186   return nDoc;
122187 }
122188
122189 /*
122190 ** Advance the cursor to the next row in the %_content table that
122191 ** matches the search criteria.  For a MATCH search, this will be
122192 ** the next row that matches. For a full-table scan, this will be
122193 ** simply the next row in the %_content table.  For a docid lookup,
122194 ** this routine simply sets the EOF flag.
122195 **
122196 ** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
122197 ** even if we reach end-of-file.  The fts3EofMethod() will be called
122198 ** subsequently to determine whether or not an EOF was hit.
122199 */
122200 static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
122201   int rc;
122202   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
122203   if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
122204     if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
122205       pCsr->isEof = 1;
122206       rc = sqlite3_reset(pCsr->pStmt);
122207     }else{
122208       pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
122209       rc = SQLITE_OK;
122210     }
122211   }else{
122212     rc = fts3EvalNext((Fts3Cursor *)pCursor);
122213   }
122214   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
122215   return rc;
122216 }
122217
122218 /*
122219 ** This is the xFilter interface for the virtual table.  See
122220 ** the virtual table xFilter method documentation for additional
122221 ** information.
122222 **
122223 ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
122224 ** the %_content table.
122225 **
122226 ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
122227 ** in the %_content table.
122228 **
122229 ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
122230 ** column on the left-hand side of the MATCH operator is column
122231 ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
122232 ** side of the MATCH operator.
122233 */
122234 static int fts3FilterMethod(
122235   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
122236   int idxNum,                     /* Strategy index */
122237   const char *idxStr,             /* Unused */
122238   int nVal,                       /* Number of elements in apVal */
122239   sqlite3_value **apVal           /* Arguments for the indexing scheme */
122240 ){
122241   int rc;
122242   char *zSql;                     /* SQL statement used to access %_content */
122243   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
122244   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
122245
122246   UNUSED_PARAMETER(idxStr);
122247   UNUSED_PARAMETER(nVal);
122248
122249   assert( idxNum>=0 && idxNum<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
122250   assert( nVal==0 || nVal==1 || nVal==2 );
122251   assert( (nVal==0)==(idxNum==FTS3_FULLSCAN_SEARCH) );
122252   assert( p->pSegments==0 );
122253
122254   /* In case the cursor has been used before, clear it now. */
122255   sqlite3_finalize(pCsr->pStmt);
122256   sqlite3_free(pCsr->aDoclist);
122257   sqlite3Fts3ExprFree(pCsr->pExpr);
122258   memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
122259
122260   if( idxStr ){
122261     pCsr->bDesc = (idxStr[0]=='D');
122262   }else{
122263     pCsr->bDesc = p->bDescIdx;
122264   }
122265   pCsr->eSearch = (i16)idxNum;
122266
122267   if( idxNum!=FTS3_DOCID_SEARCH && idxNum!=FTS3_FULLSCAN_SEARCH ){
122268     int iCol = idxNum-FTS3_FULLTEXT_SEARCH;
122269     const char *zQuery = (const char *)sqlite3_value_text(apVal[0]);
122270
122271     if( zQuery==0 && sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
122272       return SQLITE_NOMEM;
122273     }
122274
122275     pCsr->iLangid = 0;
122276     if( nVal==2 ) pCsr->iLangid = sqlite3_value_int(apVal[1]);
122277
122278     assert( p->base.zErrMsg==0 );
122279     rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
122280         p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr, 
122281         &p->base.zErrMsg
122282     );
122283     if( rc!=SQLITE_OK ){
122284       return rc;
122285     }
122286
122287     rc = sqlite3Fts3ReadLock(p);
122288     if( rc!=SQLITE_OK ) return rc;
122289
122290     rc = fts3EvalStart(pCsr);
122291
122292     sqlite3Fts3SegmentsClose(p);
122293     if( rc!=SQLITE_OK ) return rc;
122294     pCsr->pNextId = pCsr->aDoclist;
122295     pCsr->iPrevId = 0;
122296   }
122297
122298   /* Compile a SELECT statement for this cursor. For a full-table-scan, the
122299   ** statement loops through all rows of the %_content table. For a
122300   ** full-text query or docid lookup, the statement retrieves a single
122301   ** row by docid.
122302   */
122303   if( idxNum==FTS3_FULLSCAN_SEARCH ){
122304     zSql = sqlite3_mprintf(
122305         "SELECT %s ORDER BY rowid %s",
122306         p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
122307     );
122308     if( zSql ){
122309       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
122310       sqlite3_free(zSql);
122311     }else{
122312       rc = SQLITE_NOMEM;
122313     }
122314   }else if( idxNum==FTS3_DOCID_SEARCH ){
122315     rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt);
122316     if( rc==SQLITE_OK ){
122317       rc = sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
122318     }
122319   }
122320   if( rc!=SQLITE_OK ) return rc;
122321
122322   return fts3NextMethod(pCursor);
122323 }
122324
122325 /* 
122326 ** This is the xEof method of the virtual table. SQLite calls this 
122327 ** routine to find out if it has reached the end of a result set.
122328 */
122329 static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
122330   return ((Fts3Cursor *)pCursor)->isEof;
122331 }
122332
122333 /* 
122334 ** This is the xRowid method. The SQLite core calls this routine to
122335 ** retrieve the rowid for the current row of the result set. fts3
122336 ** exposes %_content.docid as the rowid for the virtual table. The
122337 ** rowid should be written to *pRowid.
122338 */
122339 static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
122340   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
122341   *pRowid = pCsr->iPrevId;
122342   return SQLITE_OK;
122343 }
122344
122345 /* 
122346 ** This is the xColumn method, called by SQLite to request a value from
122347 ** the row that the supplied cursor currently points to.
122348 **
122349 ** If:
122350 **
122351 **   (iCol <  p->nColumn)   -> The value of the iCol'th user column.
122352 **   (iCol == p->nColumn)   -> Magic column with the same name as the table.
122353 **   (iCol == p->nColumn+1) -> Docid column
122354 **   (iCol == p->nColumn+2) -> Langid column
122355 */
122356 static int fts3ColumnMethod(
122357   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
122358   sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
122359   int iCol                        /* Index of column to read value from */
122360 ){
122361   int rc = SQLITE_OK;             /* Return Code */
122362   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
122363   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
122364
122365   /* The column value supplied by SQLite must be in range. */
122366   assert( iCol>=0 && iCol<=p->nColumn+2 );
122367
122368   if( iCol==p->nColumn+1 ){
122369     /* This call is a request for the "docid" column. Since "docid" is an 
122370     ** alias for "rowid", use the xRowid() method to obtain the value.
122371     */
122372     sqlite3_result_int64(pCtx, pCsr->iPrevId);
122373   }else if( iCol==p->nColumn ){
122374     /* The extra column whose name is the same as the table.
122375     ** Return a blob which is a pointer to the cursor.  */
122376     sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
122377   }else if( iCol==p->nColumn+2 && pCsr->pExpr ){
122378     sqlite3_result_int64(pCtx, pCsr->iLangid);
122379   }else{
122380     /* The requested column is either a user column (one that contains 
122381     ** indexed data), or the language-id column.  */
122382     rc = fts3CursorSeek(0, pCsr);
122383
122384     if( rc==SQLITE_OK ){
122385       if( iCol==p->nColumn+2 ){
122386         int iLangid = 0;
122387         if( p->zLanguageid ){
122388           iLangid = sqlite3_column_int(pCsr->pStmt, p->nColumn+1);
122389         }
122390         sqlite3_result_int(pCtx, iLangid);
122391       }else if( sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){
122392         sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
122393       }
122394     }
122395   }
122396
122397   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
122398   return rc;
122399 }
122400
122401 /* 
122402 ** This function is the implementation of the xUpdate callback used by 
122403 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
122404 ** inserted, updated or deleted.
122405 */
122406 static int fts3UpdateMethod(
122407   sqlite3_vtab *pVtab,            /* Virtual table handle */
122408   int nArg,                       /* Size of argument array */
122409   sqlite3_value **apVal,          /* Array of arguments */
122410   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
122411 ){
122412   return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
122413 }
122414
122415 /*
122416 ** Implementation of xSync() method. Flush the contents of the pending-terms
122417 ** hash-table to the database.
122418 */
122419 static int fts3SyncMethod(sqlite3_vtab *pVtab){
122420
122421   /* Following an incremental-merge operation, assuming that the input
122422   ** segments are not completely consumed (the usual case), they are updated
122423   ** in place to remove the entries that have already been merged. This
122424   ** involves updating the leaf block that contains the smallest unmerged
122425   ** entry and each block (if any) between the leaf and the root node. So
122426   ** if the height of the input segment b-trees is N, and input segments
122427   ** are merged eight at a time, updating the input segments at the end
122428   ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
122429   ** small - often between 0 and 2. So the overhead of the incremental
122430   ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
122431   ** dwarfing the actual productive work accomplished, the incremental merge
122432   ** is only attempted if it will write at least 64 leaf blocks. Hence
122433   ** nMinMerge.
122434   **
122435   ** Of course, updating the input segments also involves deleting a bunch
122436   ** of blocks from the segments table. But this is not considered overhead
122437   ** as it would also be required by a crisis-merge that used the same input 
122438   ** segments.
122439   */
122440   const u32 nMinMerge = 64;       /* Minimum amount of incr-merge work to do */
122441
122442   Fts3Table *p = (Fts3Table*)pVtab;
122443   int rc = sqlite3Fts3PendingTermsFlush(p);
122444
122445   if( rc==SQLITE_OK && p->bAutoincrmerge==1 && p->nLeafAdd>(nMinMerge/16) ){
122446     int mxLevel = 0;              /* Maximum relative level value in db */
122447     int A;                        /* Incr-merge parameter A */
122448
122449     rc = sqlite3Fts3MaxLevel(p, &mxLevel);
122450     assert( rc==SQLITE_OK || mxLevel==0 );
122451     A = p->nLeafAdd * mxLevel;
122452     A += (A/2);
122453     if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, 8);
122454   }
122455   sqlite3Fts3SegmentsClose(p);
122456   return rc;
122457 }
122458
122459 /*
122460 ** Implementation of xBegin() method. This is a no-op.
122461 */
122462 static int fts3BeginMethod(sqlite3_vtab *pVtab){
122463   Fts3Table *p = (Fts3Table*)pVtab;
122464   UNUSED_PARAMETER(pVtab);
122465   assert( p->pSegments==0 );
122466   assert( p->nPendingData==0 );
122467   assert( p->inTransaction!=1 );
122468   TESTONLY( p->inTransaction = 1 );
122469   TESTONLY( p->mxSavepoint = -1; );
122470   p->nLeafAdd = 0;
122471   return SQLITE_OK;
122472 }
122473
122474 /*
122475 ** Implementation of xCommit() method. This is a no-op. The contents of
122476 ** the pending-terms hash-table have already been flushed into the database
122477 ** by fts3SyncMethod().
122478 */
122479 static int fts3CommitMethod(sqlite3_vtab *pVtab){
122480   TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
122481   UNUSED_PARAMETER(pVtab);
122482   assert( p->nPendingData==0 );
122483   assert( p->inTransaction!=0 );
122484   assert( p->pSegments==0 );
122485   TESTONLY( p->inTransaction = 0 );
122486   TESTONLY( p->mxSavepoint = -1; );
122487   return SQLITE_OK;
122488 }
122489
122490 /*
122491 ** Implementation of xRollback(). Discard the contents of the pending-terms
122492 ** hash-table. Any changes made to the database are reverted by SQLite.
122493 */
122494 static int fts3RollbackMethod(sqlite3_vtab *pVtab){
122495   Fts3Table *p = (Fts3Table*)pVtab;
122496   sqlite3Fts3PendingTermsClear(p);
122497   assert( p->inTransaction!=0 );
122498   TESTONLY( p->inTransaction = 0 );
122499   TESTONLY( p->mxSavepoint = -1; );
122500   return SQLITE_OK;
122501 }
122502
122503 /*
122504 ** When called, *ppPoslist must point to the byte immediately following the
122505 ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
122506 ** moves *ppPoslist so that it instead points to the first byte of the
122507 ** same position list.
122508 */
122509 static void fts3ReversePoslist(char *pStart, char **ppPoslist){
122510   char *p = &(*ppPoslist)[-2];
122511   char c = 0;
122512
122513   while( p>pStart && (c=*p--)==0 );
122514   while( p>pStart && (*p & 0x80) | c ){ 
122515     c = *p--; 
122516   }
122517   if( p>pStart ){ p = &p[2]; }
122518   while( *p++&0x80 );
122519   *ppPoslist = p;
122520 }
122521
122522 /*
122523 ** Helper function used by the implementation of the overloaded snippet(),
122524 ** offsets() and optimize() SQL functions.
122525 **
122526 ** If the value passed as the third argument is a blob of size
122527 ** sizeof(Fts3Cursor*), then the blob contents are copied to the 
122528 ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
122529 ** message is written to context pContext and SQLITE_ERROR returned. The
122530 ** string passed via zFunc is used as part of the error message.
122531 */
122532 static int fts3FunctionArg(
122533   sqlite3_context *pContext,      /* SQL function call context */
122534   const char *zFunc,              /* Function name */
122535   sqlite3_value *pVal,            /* argv[0] passed to function */
122536   Fts3Cursor **ppCsr              /* OUT: Store cursor handle here */
122537 ){
122538   Fts3Cursor *pRet;
122539   if( sqlite3_value_type(pVal)!=SQLITE_BLOB 
122540    || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
122541   ){
122542     char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
122543     sqlite3_result_error(pContext, zErr, -1);
122544     sqlite3_free(zErr);
122545     return SQLITE_ERROR;
122546   }
122547   memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
122548   *ppCsr = pRet;
122549   return SQLITE_OK;
122550 }
122551
122552 /*
122553 ** Implementation of the snippet() function for FTS3
122554 */
122555 static void fts3SnippetFunc(
122556   sqlite3_context *pContext,      /* SQLite function call context */
122557   int nVal,                       /* Size of apVal[] array */
122558   sqlite3_value **apVal           /* Array of arguments */
122559 ){
122560   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
122561   const char *zStart = "<b>";
122562   const char *zEnd = "</b>";
122563   const char *zEllipsis = "<b>...</b>";
122564   int iCol = -1;
122565   int nToken = 15;                /* Default number of tokens in snippet */
122566
122567   /* There must be at least one argument passed to this function (otherwise
122568   ** the non-overloaded version would have been called instead of this one).
122569   */
122570   assert( nVal>=1 );
122571
122572   if( nVal>6 ){
122573     sqlite3_result_error(pContext, 
122574         "wrong number of arguments to function snippet()", -1);
122575     return;
122576   }
122577   if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
122578
122579   switch( nVal ){
122580     case 6: nToken = sqlite3_value_int(apVal[5]);
122581     case 5: iCol = sqlite3_value_int(apVal[4]);
122582     case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
122583     case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
122584     case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
122585   }
122586   if( !zEllipsis || !zEnd || !zStart ){
122587     sqlite3_result_error_nomem(pContext);
122588   }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
122589     sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
122590   }
122591 }
122592
122593 /*
122594 ** Implementation of the offsets() function for FTS3
122595 */
122596 static void fts3OffsetsFunc(
122597   sqlite3_context *pContext,      /* SQLite function call context */
122598   int nVal,                       /* Size of argument array */
122599   sqlite3_value **apVal           /* Array of arguments */
122600 ){
122601   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
122602
122603   UNUSED_PARAMETER(nVal);
122604
122605   assert( nVal==1 );
122606   if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
122607   assert( pCsr );
122608   if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
122609     sqlite3Fts3Offsets(pContext, pCsr);
122610   }
122611 }
122612
122613 /* 
122614 ** Implementation of the special optimize() function for FTS3. This 
122615 ** function merges all segments in the database to a single segment.
122616 ** Example usage is:
122617 **
122618 **   SELECT optimize(t) FROM t LIMIT 1;
122619 **
122620 ** where 't' is the name of an FTS3 table.
122621 */
122622 static void fts3OptimizeFunc(
122623   sqlite3_context *pContext,      /* SQLite function call context */
122624   int nVal,                       /* Size of argument array */
122625   sqlite3_value **apVal           /* Array of arguments */
122626 ){
122627   int rc;                         /* Return code */
122628   Fts3Table *p;                   /* Virtual table handle */
122629   Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
122630
122631   UNUSED_PARAMETER(nVal);
122632
122633   assert( nVal==1 );
122634   if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
122635   p = (Fts3Table *)pCursor->base.pVtab;
122636   assert( p );
122637
122638   rc = sqlite3Fts3Optimize(p);
122639
122640   switch( rc ){
122641     case SQLITE_OK:
122642       sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
122643       break;
122644     case SQLITE_DONE:
122645       sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
122646       break;
122647     default:
122648       sqlite3_result_error_code(pContext, rc);
122649       break;
122650   }
122651 }
122652
122653 /*
122654 ** Implementation of the matchinfo() function for FTS3
122655 */
122656 static void fts3MatchinfoFunc(
122657   sqlite3_context *pContext,      /* SQLite function call context */
122658   int nVal,                       /* Size of argument array */
122659   sqlite3_value **apVal           /* Array of arguments */
122660 ){
122661   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
122662   assert( nVal==1 || nVal==2 );
122663   if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
122664     const char *zArg = 0;
122665     if( nVal>1 ){
122666       zArg = (const char *)sqlite3_value_text(apVal[1]);
122667     }
122668     sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
122669   }
122670 }
122671
122672 /*
122673 ** This routine implements the xFindFunction method for the FTS3
122674 ** virtual table.
122675 */
122676 static int fts3FindFunctionMethod(
122677   sqlite3_vtab *pVtab,            /* Virtual table handle */
122678   int nArg,                       /* Number of SQL function arguments */
122679   const char *zName,              /* Name of SQL function */
122680   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
122681   void **ppArg                    /* Unused */
122682 ){
122683   struct Overloaded {
122684     const char *zName;
122685     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
122686   } aOverload[] = {
122687     { "snippet", fts3SnippetFunc },
122688     { "offsets", fts3OffsetsFunc },
122689     { "optimize", fts3OptimizeFunc },
122690     { "matchinfo", fts3MatchinfoFunc },
122691   };
122692   int i;                          /* Iterator variable */
122693
122694   UNUSED_PARAMETER(pVtab);
122695   UNUSED_PARAMETER(nArg);
122696   UNUSED_PARAMETER(ppArg);
122697
122698   for(i=0; i<SizeofArray(aOverload); i++){
122699     if( strcmp(zName, aOverload[i].zName)==0 ){
122700       *pxFunc = aOverload[i].xFunc;
122701       return 1;
122702     }
122703   }
122704
122705   /* No function of the specified name was found. Return 0. */
122706   return 0;
122707 }
122708
122709 /*
122710 ** Implementation of FTS3 xRename method. Rename an fts3 table.
122711 */
122712 static int fts3RenameMethod(
122713   sqlite3_vtab *pVtab,            /* Virtual table handle */
122714   const char *zName               /* New name of table */
122715 ){
122716   Fts3Table *p = (Fts3Table *)pVtab;
122717   sqlite3 *db = p->db;            /* Database connection */
122718   int rc;                         /* Return Code */
122719
122720   /* As it happens, the pending terms table is always empty here. This is
122721   ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction 
122722   ** always opens a savepoint transaction. And the xSavepoint() method 
122723   ** flushes the pending terms table. But leave the (no-op) call to
122724   ** PendingTermsFlush() in in case that changes.
122725   */
122726   assert( p->nPendingData==0 );
122727   rc = sqlite3Fts3PendingTermsFlush(p);
122728
122729   if( p->zContentTbl==0 ){
122730     fts3DbExec(&rc, db,
122731       "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';",
122732       p->zDb, p->zName, zName
122733     );
122734   }
122735
122736   if( p->bHasDocsize ){
122737     fts3DbExec(&rc, db,
122738       "ALTER TABLE %Q.'%q_docsize'  RENAME TO '%q_docsize';",
122739       p->zDb, p->zName, zName
122740     );
122741   }
122742   if( p->bHasStat ){
122743     fts3DbExec(&rc, db,
122744       "ALTER TABLE %Q.'%q_stat'  RENAME TO '%q_stat';",
122745       p->zDb, p->zName, zName
122746     );
122747   }
122748   fts3DbExec(&rc, db,
122749     "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
122750     p->zDb, p->zName, zName
122751   );
122752   fts3DbExec(&rc, db,
122753     "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';",
122754     p->zDb, p->zName, zName
122755   );
122756   return rc;
122757 }
122758
122759 /*
122760 ** The xSavepoint() method.
122761 **
122762 ** Flush the contents of the pending-terms table to disk.
122763 */
122764 static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
122765   int rc = SQLITE_OK;
122766   UNUSED_PARAMETER(iSavepoint);
122767   assert( ((Fts3Table *)pVtab)->inTransaction );
122768   assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
122769   TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
122770   if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
122771     rc = fts3SyncMethod(pVtab);
122772   }
122773   return rc;
122774 }
122775
122776 /*
122777 ** The xRelease() method.
122778 **
122779 ** This is a no-op.
122780 */
122781 static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
122782   TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
122783   UNUSED_PARAMETER(iSavepoint);
122784   UNUSED_PARAMETER(pVtab);
122785   assert( p->inTransaction );
122786   assert( p->mxSavepoint >= iSavepoint );
122787   TESTONLY( p->mxSavepoint = iSavepoint-1 );
122788   return SQLITE_OK;
122789 }
122790
122791 /*
122792 ** The xRollbackTo() method.
122793 **
122794 ** Discard the contents of the pending terms table.
122795 */
122796 static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
122797   Fts3Table *p = (Fts3Table*)pVtab;
122798   UNUSED_PARAMETER(iSavepoint);
122799   assert( p->inTransaction );
122800   assert( p->mxSavepoint >= iSavepoint );
122801   TESTONLY( p->mxSavepoint = iSavepoint );
122802   sqlite3Fts3PendingTermsClear(p);
122803   return SQLITE_OK;
122804 }
122805
122806 static const sqlite3_module fts3Module = {
122807   /* iVersion      */ 2,
122808   /* xCreate       */ fts3CreateMethod,
122809   /* xConnect      */ fts3ConnectMethod,
122810   /* xBestIndex    */ fts3BestIndexMethod,
122811   /* xDisconnect   */ fts3DisconnectMethod,
122812   /* xDestroy      */ fts3DestroyMethod,
122813   /* xOpen         */ fts3OpenMethod,
122814   /* xClose        */ fts3CloseMethod,
122815   /* xFilter       */ fts3FilterMethod,
122816   /* xNext         */ fts3NextMethod,
122817   /* xEof          */ fts3EofMethod,
122818   /* xColumn       */ fts3ColumnMethod,
122819   /* xRowid        */ fts3RowidMethod,
122820   /* xUpdate       */ fts3UpdateMethod,
122821   /* xBegin        */ fts3BeginMethod,
122822   /* xSync         */ fts3SyncMethod,
122823   /* xCommit       */ fts3CommitMethod,
122824   /* xRollback     */ fts3RollbackMethod,
122825   /* xFindFunction */ fts3FindFunctionMethod,
122826   /* xRename */       fts3RenameMethod,
122827   /* xSavepoint    */ fts3SavepointMethod,
122828   /* xRelease      */ fts3ReleaseMethod,
122829   /* xRollbackTo   */ fts3RollbackToMethod,
122830 };
122831
122832 /*
122833 ** This function is registered as the module destructor (called when an
122834 ** FTS3 enabled database connection is closed). It frees the memory
122835 ** allocated for the tokenizer hash table.
122836 */
122837 static void hashDestroy(void *p){
122838   Fts3Hash *pHash = (Fts3Hash *)p;
122839   sqlite3Fts3HashClear(pHash);
122840   sqlite3_free(pHash);
122841 }
122842
122843 /*
122844 ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are 
122845 ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
122846 ** respectively. The following three forward declarations are for functions
122847 ** declared in these files used to retrieve the respective implementations.
122848 **
122849 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
122850 ** to by the argument to point to the "simple" tokenizer implementation.
122851 ** And so on.
122852 */
122853 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
122854 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
122855 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
122856 SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
122857 #endif
122858 #ifdef SQLITE_ENABLE_ICU
122859 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
122860 #endif
122861
122862 /*
122863 ** Initialize the fts3 extension. If this extension is built as part
122864 ** of the sqlite library, then this function is called directly by
122865 ** SQLite. If fts3 is built as a dynamically loadable extension, this
122866 ** function is called by the sqlite3_extension_init() entry point.
122867 */
122868 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
122869   int rc = SQLITE_OK;
122870   Fts3Hash *pHash = 0;
122871   const sqlite3_tokenizer_module *pSimple = 0;
122872   const sqlite3_tokenizer_module *pPorter = 0;
122873 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
122874   const sqlite3_tokenizer_module *pUnicode = 0;
122875 #endif
122876
122877 #ifdef SQLITE_ENABLE_ICU
122878   const sqlite3_tokenizer_module *pIcu = 0;
122879   sqlite3Fts3IcuTokenizerModule(&pIcu);
122880 #endif
122881
122882 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
122883   sqlite3Fts3UnicodeTokenizer(&pUnicode);
122884 #endif
122885
122886 #ifdef SQLITE_TEST
122887   rc = sqlite3Fts3InitTerm(db);
122888   if( rc!=SQLITE_OK ) return rc;
122889 #endif
122890
122891   rc = sqlite3Fts3InitAux(db);
122892   if( rc!=SQLITE_OK ) return rc;
122893
122894   sqlite3Fts3SimpleTokenizerModule(&pSimple);
122895   sqlite3Fts3PorterTokenizerModule(&pPorter);
122896
122897   /* Allocate and initialize the hash-table used to store tokenizers. */
122898   pHash = sqlite3_malloc(sizeof(Fts3Hash));
122899   if( !pHash ){
122900     rc = SQLITE_NOMEM;
122901   }else{
122902     sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
122903   }
122904
122905   /* Load the built-in tokenizers into the hash table */
122906   if( rc==SQLITE_OK ){
122907     if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
122908      || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter) 
122909
122910 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
122911      || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode) 
122912 #endif
122913 #ifdef SQLITE_ENABLE_ICU
122914      || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
122915 #endif
122916     ){
122917       rc = SQLITE_NOMEM;
122918     }
122919   }
122920
122921 #ifdef SQLITE_TEST
122922   if( rc==SQLITE_OK ){
122923     rc = sqlite3Fts3ExprInitTestInterface(db);
122924   }
122925 #endif
122926
122927   /* Create the virtual table wrapper around the hash-table and overload 
122928   ** the two scalar functions. If this is successful, register the
122929   ** module with sqlite.
122930   */
122931   if( SQLITE_OK==rc 
122932    && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
122933    && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
122934    && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
122935    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
122936    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
122937    && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
122938   ){
122939     rc = sqlite3_create_module_v2(
122940         db, "fts3", &fts3Module, (void *)pHash, hashDestroy
122941     );
122942     if( rc==SQLITE_OK ){
122943       rc = sqlite3_create_module_v2(
122944           db, "fts4", &fts3Module, (void *)pHash, 0
122945       );
122946     }
122947     if( rc==SQLITE_OK ){
122948       rc = sqlite3Fts3InitTok(db, (void *)pHash);
122949     }
122950     return rc;
122951   }
122952
122953
122954   /* An error has occurred. Delete the hash table and return the error code. */
122955   assert( rc!=SQLITE_OK );
122956   if( pHash ){
122957     sqlite3Fts3HashClear(pHash);
122958     sqlite3_free(pHash);
122959   }
122960   return rc;
122961 }
122962
122963 /*
122964 ** Allocate an Fts3MultiSegReader for each token in the expression headed
122965 ** by pExpr. 
122966 **
122967 ** An Fts3SegReader object is a cursor that can seek or scan a range of
122968 ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
122969 ** Fts3SegReader objects internally to provide an interface to seek or scan
122970 ** within the union of all segments of a b-tree. Hence the name.
122971 **
122972 ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
122973 ** segment b-tree (if the term is not a prefix or it is a prefix for which
122974 ** there exists prefix b-tree of the right length) then it may be traversed
122975 ** and merged incrementally. Otherwise, it has to be merged into an in-memory 
122976 ** doclist and then traversed.
122977 */
122978 static void fts3EvalAllocateReaders(
122979   Fts3Cursor *pCsr,               /* FTS cursor handle */
122980   Fts3Expr *pExpr,                /* Allocate readers for this expression */
122981   int *pnToken,                   /* OUT: Total number of tokens in phrase. */
122982   int *pnOr,                      /* OUT: Total number of OR nodes in expr. */
122983   int *pRc                        /* IN/OUT: Error code */
122984 ){
122985   if( pExpr && SQLITE_OK==*pRc ){
122986     if( pExpr->eType==FTSQUERY_PHRASE ){
122987       int i;
122988       int nToken = pExpr->pPhrase->nToken;
122989       *pnToken += nToken;
122990       for(i=0; i<nToken; i++){
122991         Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
122992         int rc = fts3TermSegReaderCursor(pCsr, 
122993             pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
122994         );
122995         if( rc!=SQLITE_OK ){
122996           *pRc = rc;
122997           return;
122998         }
122999       }
123000       assert( pExpr->pPhrase->iDoclistToken==0 );
123001       pExpr->pPhrase->iDoclistToken = -1;
123002     }else{
123003       *pnOr += (pExpr->eType==FTSQUERY_OR);
123004       fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
123005       fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
123006     }
123007   }
123008 }
123009
123010 /*
123011 ** Arguments pList/nList contain the doclist for token iToken of phrase p.
123012 ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
123013 **
123014 ** This function assumes that pList points to a buffer allocated using
123015 ** sqlite3_malloc(). This function takes responsibility for eventually
123016 ** freeing the buffer.
123017 */
123018 static void fts3EvalPhraseMergeToken(
123019   Fts3Table *pTab,                /* FTS Table pointer */
123020   Fts3Phrase *p,                  /* Phrase to merge pList/nList into */
123021   int iToken,                     /* Token pList/nList corresponds to */
123022   char *pList,                    /* Pointer to doclist */
123023   int nList                       /* Number of bytes in pList */
123024 ){
123025   assert( iToken!=p->iDoclistToken );
123026
123027   if( pList==0 ){
123028     sqlite3_free(p->doclist.aAll);
123029     p->doclist.aAll = 0;
123030     p->doclist.nAll = 0;
123031   }
123032
123033   else if( p->iDoclistToken<0 ){
123034     p->doclist.aAll = pList;
123035     p->doclist.nAll = nList;
123036   }
123037
123038   else if( p->doclist.aAll==0 ){
123039     sqlite3_free(pList);
123040   }
123041
123042   else {
123043     char *pLeft;
123044     char *pRight;
123045     int nLeft;
123046     int nRight;
123047     int nDiff;
123048
123049     if( p->iDoclistToken<iToken ){
123050       pLeft = p->doclist.aAll;
123051       nLeft = p->doclist.nAll;
123052       pRight = pList;
123053       nRight = nList;
123054       nDiff = iToken - p->iDoclistToken;
123055     }else{
123056       pRight = p->doclist.aAll;
123057       nRight = p->doclist.nAll;
123058       pLeft = pList;
123059       nLeft = nList;
123060       nDiff = p->iDoclistToken - iToken;
123061     }
123062
123063     fts3DoclistPhraseMerge(pTab->bDescIdx, nDiff, pLeft, nLeft, pRight,&nRight);
123064     sqlite3_free(pLeft);
123065     p->doclist.aAll = pRight;
123066     p->doclist.nAll = nRight;
123067   }
123068
123069   if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
123070 }
123071
123072 /*
123073 ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
123074 ** does not take deferred tokens into account.
123075 **
123076 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
123077 */
123078 static int fts3EvalPhraseLoad(
123079   Fts3Cursor *pCsr,               /* FTS Cursor handle */
123080   Fts3Phrase *p                   /* Phrase object */
123081 ){
123082   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
123083   int iToken;
123084   int rc = SQLITE_OK;
123085
123086   for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
123087     Fts3PhraseToken *pToken = &p->aToken[iToken];
123088     assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
123089
123090     if( pToken->pSegcsr ){
123091       int nThis = 0;
123092       char *pThis = 0;
123093       rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
123094       if( rc==SQLITE_OK ){
123095         fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
123096       }
123097     }
123098     assert( pToken->pSegcsr==0 );
123099   }
123100
123101   return rc;
123102 }
123103
123104 /*
123105 ** This function is called on each phrase after the position lists for
123106 ** any deferred tokens have been loaded into memory. It updates the phrases
123107 ** current position list to include only those positions that are really
123108 ** instances of the phrase (after considering deferred tokens). If this
123109 ** means that the phrase does not appear in the current row, doclist.pList
123110 ** and doclist.nList are both zeroed.
123111 **
123112 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
123113 */
123114 static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
123115   int iToken;                     /* Used to iterate through phrase tokens */
123116   char *aPoslist = 0;             /* Position list for deferred tokens */
123117   int nPoslist = 0;               /* Number of bytes in aPoslist */
123118   int iPrev = -1;                 /* Token number of previous deferred token */
123119
123120   assert( pPhrase->doclist.bFreeList==0 );
123121
123122   for(iToken=0; iToken<pPhrase->nToken; iToken++){
123123     Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
123124     Fts3DeferredToken *pDeferred = pToken->pDeferred;
123125
123126     if( pDeferred ){
123127       char *pList;
123128       int nList;
123129       int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
123130       if( rc!=SQLITE_OK ) return rc;
123131
123132       if( pList==0 ){
123133         sqlite3_free(aPoslist);
123134         pPhrase->doclist.pList = 0;
123135         pPhrase->doclist.nList = 0;
123136         return SQLITE_OK;
123137
123138       }else if( aPoslist==0 ){
123139         aPoslist = pList;
123140         nPoslist = nList;
123141
123142       }else{
123143         char *aOut = pList;
123144         char *p1 = aPoslist;
123145         char *p2 = aOut;
123146
123147         assert( iPrev>=0 );
123148         fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
123149         sqlite3_free(aPoslist);
123150         aPoslist = pList;
123151         nPoslist = (int)(aOut - aPoslist);
123152         if( nPoslist==0 ){
123153           sqlite3_free(aPoslist);
123154           pPhrase->doclist.pList = 0;
123155           pPhrase->doclist.nList = 0;
123156           return SQLITE_OK;
123157         }
123158       }
123159       iPrev = iToken;
123160     }
123161   }
123162
123163   if( iPrev>=0 ){
123164     int nMaxUndeferred = pPhrase->iDoclistToken;
123165     if( nMaxUndeferred<0 ){
123166       pPhrase->doclist.pList = aPoslist;
123167       pPhrase->doclist.nList = nPoslist;
123168       pPhrase->doclist.iDocid = pCsr->iPrevId;
123169       pPhrase->doclist.bFreeList = 1;
123170     }else{
123171       int nDistance;
123172       char *p1;
123173       char *p2;
123174       char *aOut;
123175
123176       if( nMaxUndeferred>iPrev ){
123177         p1 = aPoslist;
123178         p2 = pPhrase->doclist.pList;
123179         nDistance = nMaxUndeferred - iPrev;
123180       }else{
123181         p1 = pPhrase->doclist.pList;
123182         p2 = aPoslist;
123183         nDistance = iPrev - nMaxUndeferred;
123184       }
123185
123186       aOut = (char *)sqlite3_malloc(nPoslist+8);
123187       if( !aOut ){
123188         sqlite3_free(aPoslist);
123189         return SQLITE_NOMEM;
123190       }
123191       
123192       pPhrase->doclist.pList = aOut;
123193       if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
123194         pPhrase->doclist.bFreeList = 1;
123195         pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
123196       }else{
123197         sqlite3_free(aOut);
123198         pPhrase->doclist.pList = 0;
123199         pPhrase->doclist.nList = 0;
123200       }
123201       sqlite3_free(aPoslist);
123202     }
123203   }
123204
123205   return SQLITE_OK;
123206 }
123207
123208 /*
123209 ** This function is called for each Fts3Phrase in a full-text query 
123210 ** expression to initialize the mechanism for returning rows. Once this
123211 ** function has been called successfully on an Fts3Phrase, it may be
123212 ** used with fts3EvalPhraseNext() to iterate through the matching docids.
123213 **
123214 ** If parameter bOptOk is true, then the phrase may (or may not) use the
123215 ** incremental loading strategy. Otherwise, the entire doclist is loaded into
123216 ** memory within this call.
123217 **
123218 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
123219 */
123220 static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
123221   int rc;                         /* Error code */
123222   Fts3PhraseToken *pFirst = &p->aToken[0];
123223   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
123224
123225   if( pCsr->bDesc==pTab->bDescIdx 
123226    && bOptOk==1 
123227    && p->nToken==1 
123228    && pFirst->pSegcsr 
123229    && pFirst->pSegcsr->bLookup 
123230    && pFirst->bFirst==0
123231   ){
123232     /* Use the incremental approach. */
123233     int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
123234     rc = sqlite3Fts3MsrIncrStart(
123235         pTab, pFirst->pSegcsr, iCol, pFirst->z, pFirst->n);
123236     p->bIncr = 1;
123237
123238   }else{
123239     /* Load the full doclist for the phrase into memory. */
123240     rc = fts3EvalPhraseLoad(pCsr, p);
123241     p->bIncr = 0;
123242   }
123243
123244   assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
123245   return rc;
123246 }
123247
123248 /*
123249 ** This function is used to iterate backwards (from the end to start) 
123250 ** through doclists. It is used by this module to iterate through phrase
123251 ** doclists in reverse and by the fts3_write.c module to iterate through
123252 ** pending-terms lists when writing to databases with "order=desc".
123253 **
123254 ** The doclist may be sorted in ascending (parameter bDescIdx==0) or 
123255 ** descending (parameter bDescIdx==1) order of docid. Regardless, this
123256 ** function iterates from the end of the doclist to the beginning.
123257 */
123258 SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
123259   int bDescIdx,                   /* True if the doclist is desc */
123260   char *aDoclist,                 /* Pointer to entire doclist */
123261   int nDoclist,                   /* Length of aDoclist in bytes */
123262   char **ppIter,                  /* IN/OUT: Iterator pointer */
123263   sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
123264   int *pnList,                    /* OUT: List length pointer */
123265   u8 *pbEof                       /* OUT: End-of-file flag */
123266 ){
123267   char *p = *ppIter;
123268
123269   assert( nDoclist>0 );
123270   assert( *pbEof==0 );
123271   assert( p || *piDocid==0 );
123272   assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
123273
123274   if( p==0 ){
123275     sqlite3_int64 iDocid = 0;
123276     char *pNext = 0;
123277     char *pDocid = aDoclist;
123278     char *pEnd = &aDoclist[nDoclist];
123279     int iMul = 1;
123280
123281     while( pDocid<pEnd ){
123282       sqlite3_int64 iDelta;
123283       pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
123284       iDocid += (iMul * iDelta);
123285       pNext = pDocid;
123286       fts3PoslistCopy(0, &pDocid);
123287       while( pDocid<pEnd && *pDocid==0 ) pDocid++;
123288       iMul = (bDescIdx ? -1 : 1);
123289     }
123290
123291     *pnList = (int)(pEnd - pNext);
123292     *ppIter = pNext;
123293     *piDocid = iDocid;
123294   }else{
123295     int iMul = (bDescIdx ? -1 : 1);
123296     sqlite3_int64 iDelta;
123297     fts3GetReverseVarint(&p, aDoclist, &iDelta);
123298     *piDocid -= (iMul * iDelta);
123299
123300     if( p==aDoclist ){
123301       *pbEof = 1;
123302     }else{
123303       char *pSave = p;
123304       fts3ReversePoslist(aDoclist, &p);
123305       *pnList = (int)(pSave - p);
123306     }
123307     *ppIter = p;
123308   }
123309 }
123310
123311 /*
123312 ** Iterate forwards through a doclist.
123313 */
123314 SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
123315   int bDescIdx,                   /* True if the doclist is desc */
123316   char *aDoclist,                 /* Pointer to entire doclist */
123317   int nDoclist,                   /* Length of aDoclist in bytes */
123318   char **ppIter,                  /* IN/OUT: Iterator pointer */
123319   sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
123320   u8 *pbEof                       /* OUT: End-of-file flag */
123321 ){
123322   char *p = *ppIter;
123323
123324   assert( nDoclist>0 );
123325   assert( *pbEof==0 );
123326   assert( p || *piDocid==0 );
123327   assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
123328
123329   if( p==0 ){
123330     p = aDoclist;
123331     p += sqlite3Fts3GetVarint(p, piDocid);
123332   }else{
123333     fts3PoslistCopy(0, &p);
123334     if( p>=&aDoclist[nDoclist] ){
123335       *pbEof = 1;
123336     }else{
123337       sqlite3_int64 iVar;
123338       p += sqlite3Fts3GetVarint(p, &iVar);
123339       *piDocid += ((bDescIdx ? -1 : 1) * iVar);
123340     }
123341   }
123342
123343   *ppIter = p;
123344 }
123345
123346 /*
123347 ** Attempt to move the phrase iterator to point to the next matching docid. 
123348 ** If an error occurs, return an SQLite error code. Otherwise, return 
123349 ** SQLITE_OK.
123350 **
123351 ** If there is no "next" entry and no error occurs, then *pbEof is set to
123352 ** 1 before returning. Otherwise, if no error occurs and the iterator is
123353 ** successfully advanced, *pbEof is set to 0.
123354 */
123355 static int fts3EvalPhraseNext(
123356   Fts3Cursor *pCsr,               /* FTS Cursor handle */
123357   Fts3Phrase *p,                  /* Phrase object to advance to next docid */
123358   u8 *pbEof                       /* OUT: Set to 1 if EOF */
123359 ){
123360   int rc = SQLITE_OK;
123361   Fts3Doclist *pDL = &p->doclist;
123362   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
123363
123364   if( p->bIncr ){
123365     assert( p->nToken==1 );
123366     assert( pDL->pNextDocid==0 );
123367     rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr, 
123368         &pDL->iDocid, &pDL->pList, &pDL->nList
123369     );
123370     if( rc==SQLITE_OK && !pDL->pList ){
123371       *pbEof = 1;
123372     }
123373   }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
123374     sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll, 
123375         &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
123376     );
123377     pDL->pList = pDL->pNextDocid;
123378   }else{
123379     char *pIter;                            /* Used to iterate through aAll */
123380     char *pEnd = &pDL->aAll[pDL->nAll];     /* 1 byte past end of aAll */
123381     if( pDL->pNextDocid ){
123382       pIter = pDL->pNextDocid;
123383     }else{
123384       pIter = pDL->aAll;
123385     }
123386
123387     if( pIter>=pEnd ){
123388       /* We have already reached the end of this doclist. EOF. */
123389       *pbEof = 1;
123390     }else{
123391       sqlite3_int64 iDelta;
123392       pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
123393       if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
123394         pDL->iDocid += iDelta;
123395       }else{
123396         pDL->iDocid -= iDelta;
123397       }
123398       pDL->pList = pIter;
123399       fts3PoslistCopy(0, &pIter);
123400       pDL->nList = (int)(pIter - pDL->pList);
123401
123402       /* pIter now points just past the 0x00 that terminates the position-
123403       ** list for document pDL->iDocid. However, if this position-list was
123404       ** edited in place by fts3EvalNearTrim(), then pIter may not actually
123405       ** point to the start of the next docid value. The following line deals
123406       ** with this case by advancing pIter past the zero-padding added by
123407       ** fts3EvalNearTrim().  */
123408       while( pIter<pEnd && *pIter==0 ) pIter++;
123409
123410       pDL->pNextDocid = pIter;
123411       assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
123412       *pbEof = 0;
123413     }
123414   }
123415
123416   return rc;
123417 }
123418
123419 /*
123420 **
123421 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
123422 ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
123423 ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
123424 ** expressions for which all descendent tokens are deferred.
123425 **
123426 ** If parameter bOptOk is zero, then it is guaranteed that the
123427 ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
123428 ** each phrase in the expression (subject to deferred token processing).
123429 ** Or, if bOptOk is non-zero, then one or more tokens within the expression
123430 ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
123431 **
123432 ** If an error occurs within this function, *pRc is set to an SQLite error
123433 ** code before returning.
123434 */
123435 static void fts3EvalStartReaders(
123436   Fts3Cursor *pCsr,               /* FTS Cursor handle */
123437   Fts3Expr *pExpr,                /* Expression to initialize phrases in */
123438   int bOptOk,                     /* True to enable incremental loading */
123439   int *pRc                        /* IN/OUT: Error code */
123440 ){
123441   if( pExpr && SQLITE_OK==*pRc ){
123442     if( pExpr->eType==FTSQUERY_PHRASE ){
123443       int i;
123444       int nToken = pExpr->pPhrase->nToken;
123445       for(i=0; i<nToken; i++){
123446         if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
123447       }
123448       pExpr->bDeferred = (i==nToken);
123449       *pRc = fts3EvalPhraseStart(pCsr, bOptOk, pExpr->pPhrase);
123450     }else{
123451       fts3EvalStartReaders(pCsr, pExpr->pLeft, bOptOk, pRc);
123452       fts3EvalStartReaders(pCsr, pExpr->pRight, bOptOk, pRc);
123453       pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
123454     }
123455   }
123456 }
123457
123458 /*
123459 ** An array of the following structures is assembled as part of the process
123460 ** of selecting tokens to defer before the query starts executing (as part
123461 ** of the xFilter() method). There is one element in the array for each
123462 ** token in the FTS expression.
123463 **
123464 ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
123465 ** to phrases that are connected only by AND and NEAR operators (not OR or
123466 ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
123467 ** separately. The root of a tokens AND/NEAR cluster is stored in 
123468 ** Fts3TokenAndCost.pRoot.
123469 */
123470 typedef struct Fts3TokenAndCost Fts3TokenAndCost;
123471 struct Fts3TokenAndCost {
123472   Fts3Phrase *pPhrase;            /* The phrase the token belongs to */
123473   int iToken;                     /* Position of token in phrase */
123474   Fts3PhraseToken *pToken;        /* The token itself */
123475   Fts3Expr *pRoot;                /* Root of NEAR/AND cluster */
123476   int nOvfl;                      /* Number of overflow pages to load doclist */
123477   int iCol;                       /* The column the token must match */
123478 };
123479
123480 /*
123481 ** This function is used to populate an allocated Fts3TokenAndCost array.
123482 **
123483 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
123484 ** Otherwise, if an error occurs during execution, *pRc is set to an
123485 ** SQLite error code.
123486 */
123487 static void fts3EvalTokenCosts(
123488   Fts3Cursor *pCsr,               /* FTS Cursor handle */
123489   Fts3Expr *pRoot,                /* Root of current AND/NEAR cluster */
123490   Fts3Expr *pExpr,                /* Expression to consider */
123491   Fts3TokenAndCost **ppTC,        /* Write new entries to *(*ppTC)++ */
123492   Fts3Expr ***ppOr,               /* Write new OR root to *(*ppOr)++ */
123493   int *pRc                        /* IN/OUT: Error code */
123494 ){
123495   if( *pRc==SQLITE_OK ){
123496     if( pExpr->eType==FTSQUERY_PHRASE ){
123497       Fts3Phrase *pPhrase = pExpr->pPhrase;
123498       int i;
123499       for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
123500         Fts3TokenAndCost *pTC = (*ppTC)++;
123501         pTC->pPhrase = pPhrase;
123502         pTC->iToken = i;
123503         pTC->pRoot = pRoot;
123504         pTC->pToken = &pPhrase->aToken[i];
123505         pTC->iCol = pPhrase->iColumn;
123506         *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
123507       }
123508     }else if( pExpr->eType!=FTSQUERY_NOT ){
123509       assert( pExpr->eType==FTSQUERY_OR
123510            || pExpr->eType==FTSQUERY_AND
123511            || pExpr->eType==FTSQUERY_NEAR
123512       );
123513       assert( pExpr->pLeft && pExpr->pRight );
123514       if( pExpr->eType==FTSQUERY_OR ){
123515         pRoot = pExpr->pLeft;
123516         **ppOr = pRoot;
123517         (*ppOr)++;
123518       }
123519       fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
123520       if( pExpr->eType==FTSQUERY_OR ){
123521         pRoot = pExpr->pRight;
123522         **ppOr = pRoot;
123523         (*ppOr)++;
123524       }
123525       fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
123526     }
123527   }
123528 }
123529
123530 /*
123531 ** Determine the average document (row) size in pages. If successful,
123532 ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
123533 ** an SQLite error code.
123534 **
123535 ** The average document size in pages is calculated by first calculating 
123536 ** determining the average size in bytes, B. If B is less than the amount
123537 ** of data that will fit on a single leaf page of an intkey table in
123538 ** this database, then the average docsize is 1. Otherwise, it is 1 plus
123539 ** the number of overflow pages consumed by a record B bytes in size.
123540 */
123541 static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
123542   if( pCsr->nRowAvg==0 ){
123543     /* The average document size, which is required to calculate the cost
123544     ** of each doclist, has not yet been determined. Read the required 
123545     ** data from the %_stat table to calculate it.
123546     **
123547     ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3 
123548     ** varints, where nCol is the number of columns in the FTS3 table.
123549     ** The first varint is the number of documents currently stored in
123550     ** the table. The following nCol varints contain the total amount of
123551     ** data stored in all rows of each column of the table, from left
123552     ** to right.
123553     */
123554     int rc;
123555     Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
123556     sqlite3_stmt *pStmt;
123557     sqlite3_int64 nDoc = 0;
123558     sqlite3_int64 nByte = 0;
123559     const char *pEnd;
123560     const char *a;
123561
123562     rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
123563     if( rc!=SQLITE_OK ) return rc;
123564     a = sqlite3_column_blob(pStmt, 0);
123565     assert( a );
123566
123567     pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
123568     a += sqlite3Fts3GetVarint(a, &nDoc);
123569     while( a<pEnd ){
123570       a += sqlite3Fts3GetVarint(a, &nByte);
123571     }
123572     if( nDoc==0 || nByte==0 ){
123573       sqlite3_reset(pStmt);
123574       return FTS_CORRUPT_VTAB;
123575     }
123576
123577     pCsr->nDoc = nDoc;
123578     pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
123579     assert( pCsr->nRowAvg>0 ); 
123580     rc = sqlite3_reset(pStmt);
123581     if( rc!=SQLITE_OK ) return rc;
123582   }
123583
123584   *pnPage = pCsr->nRowAvg;
123585   return SQLITE_OK;
123586 }
123587
123588 /*
123589 ** This function is called to select the tokens (if any) that will be 
123590 ** deferred. The array aTC[] has already been populated when this is
123591 ** called.
123592 **
123593 ** This function is called once for each AND/NEAR cluster in the 
123594 ** expression. Each invocation determines which tokens to defer within
123595 ** the cluster with root node pRoot. See comments above the definition
123596 ** of struct Fts3TokenAndCost for more details.
123597 **
123598 ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
123599 ** called on each token to defer. Otherwise, an SQLite error code is
123600 ** returned.
123601 */
123602 static int fts3EvalSelectDeferred(
123603   Fts3Cursor *pCsr,               /* FTS Cursor handle */
123604   Fts3Expr *pRoot,                /* Consider tokens with this root node */
123605   Fts3TokenAndCost *aTC,          /* Array of expression tokens and costs */
123606   int nTC                         /* Number of entries in aTC[] */
123607 ){
123608   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
123609   int nDocSize = 0;               /* Number of pages per doc loaded */
123610   int rc = SQLITE_OK;             /* Return code */
123611   int ii;                         /* Iterator variable for various purposes */
123612   int nOvfl = 0;                  /* Total overflow pages used by doclists */
123613   int nToken = 0;                 /* Total number of tokens in cluster */
123614
123615   int nMinEst = 0;                /* The minimum count for any phrase so far. */
123616   int nLoad4 = 1;                 /* (Phrases that will be loaded)^4. */
123617
123618   /* Tokens are never deferred for FTS tables created using the content=xxx
123619   ** option. The reason being that it is not guaranteed that the content
123620   ** table actually contains the same data as the index. To prevent this from
123621   ** causing any problems, the deferred token optimization is completely
123622   ** disabled for content=xxx tables. */
123623   if( pTab->zContentTbl ){
123624     return SQLITE_OK;
123625   }
123626
123627   /* Count the tokens in this AND/NEAR cluster. If none of the doclists
123628   ** associated with the tokens spill onto overflow pages, or if there is
123629   ** only 1 token, exit early. No tokens to defer in this case. */
123630   for(ii=0; ii<nTC; ii++){
123631     if( aTC[ii].pRoot==pRoot ){
123632       nOvfl += aTC[ii].nOvfl;
123633       nToken++;
123634     }
123635   }
123636   if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
123637
123638   /* Obtain the average docsize (in pages). */
123639   rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
123640   assert( rc!=SQLITE_OK || nDocSize>0 );
123641
123642
123643   /* Iterate through all tokens in this AND/NEAR cluster, in ascending order 
123644   ** of the number of overflow pages that will be loaded by the pager layer 
123645   ** to retrieve the entire doclist for the token from the full-text index.
123646   ** Load the doclists for tokens that are either:
123647   **
123648   **   a. The cheapest token in the entire query (i.e. the one visited by the
123649   **      first iteration of this loop), or
123650   **
123651   **   b. Part of a multi-token phrase.
123652   **
123653   ** After each token doclist is loaded, merge it with the others from the
123654   ** same phrase and count the number of documents that the merged doclist
123655   ** contains. Set variable "nMinEst" to the smallest number of documents in 
123656   ** any phrase doclist for which 1 or more token doclists have been loaded.
123657   ** Let nOther be the number of other phrases for which it is certain that
123658   ** one or more tokens will not be deferred.
123659   **
123660   ** Then, for each token, defer it if loading the doclist would result in
123661   ** loading N or more overflow pages into memory, where N is computed as:
123662   **
123663   **    (nMinEst + 4^nOther - 1) / (4^nOther)
123664   */
123665   for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
123666     int iTC;                      /* Used to iterate through aTC[] array. */
123667     Fts3TokenAndCost *pTC = 0;    /* Set to cheapest remaining token. */
123668
123669     /* Set pTC to point to the cheapest remaining token. */
123670     for(iTC=0; iTC<nTC; iTC++){
123671       if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot 
123672        && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl) 
123673       ){
123674         pTC = &aTC[iTC];
123675       }
123676     }
123677     assert( pTC );
123678
123679     if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
123680       /* The number of overflow pages to load for this (and therefore all
123681       ** subsequent) tokens is greater than the estimated number of pages 
123682       ** that will be loaded if all subsequent tokens are deferred.
123683       */
123684       Fts3PhraseToken *pToken = pTC->pToken;
123685       rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
123686       fts3SegReaderCursorFree(pToken->pSegcsr);
123687       pToken->pSegcsr = 0;
123688     }else{
123689       /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
123690       ** for-loop. Except, limit the value to 2^24 to prevent it from 
123691       ** overflowing the 32-bit integer it is stored in. */
123692       if( ii<12 ) nLoad4 = nLoad4*4;
123693
123694       if( ii==0 || pTC->pPhrase->nToken>1 ){
123695         /* Either this is the cheapest token in the entire query, or it is
123696         ** part of a multi-token phrase. Either way, the entire doclist will
123697         ** (eventually) be loaded into memory. It may as well be now. */
123698         Fts3PhraseToken *pToken = pTC->pToken;
123699         int nList = 0;
123700         char *pList = 0;
123701         rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
123702         assert( rc==SQLITE_OK || pList==0 );
123703         if( rc==SQLITE_OK ){
123704           int nCount;
123705           fts3EvalPhraseMergeToken(pTab, pTC->pPhrase, pTC->iToken,pList,nList);
123706           nCount = fts3DoclistCountDocids(
123707               pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
123708           );
123709           if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
123710         }
123711       }
123712     }
123713     pTC->pToken = 0;
123714   }
123715
123716   return rc;
123717 }
123718
123719 /*
123720 ** This function is called from within the xFilter method. It initializes
123721 ** the full-text query currently stored in pCsr->pExpr. To iterate through
123722 ** the results of a query, the caller does:
123723 **
123724 **    fts3EvalStart(pCsr);
123725 **    while( 1 ){
123726 **      fts3EvalNext(pCsr);
123727 **      if( pCsr->bEof ) break;
123728 **      ... return row pCsr->iPrevId to the caller ...
123729 **    }
123730 */
123731 static int fts3EvalStart(Fts3Cursor *pCsr){
123732   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
123733   int rc = SQLITE_OK;
123734   int nToken = 0;
123735   int nOr = 0;
123736
123737   /* Allocate a MultiSegReader for each token in the expression. */
123738   fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
123739
123740   /* Determine which, if any, tokens in the expression should be deferred. */
123741 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
123742   if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
123743     Fts3TokenAndCost *aTC;
123744     Fts3Expr **apOr;
123745     aTC = (Fts3TokenAndCost *)sqlite3_malloc(
123746         sizeof(Fts3TokenAndCost) * nToken
123747       + sizeof(Fts3Expr *) * nOr * 2
123748     );
123749     apOr = (Fts3Expr **)&aTC[nToken];
123750
123751     if( !aTC ){
123752       rc = SQLITE_NOMEM;
123753     }else{
123754       int ii;
123755       Fts3TokenAndCost *pTC = aTC;
123756       Fts3Expr **ppOr = apOr;
123757
123758       fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
123759       nToken = (int)(pTC-aTC);
123760       nOr = (int)(ppOr-apOr);
123761
123762       if( rc==SQLITE_OK ){
123763         rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
123764         for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
123765           rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
123766         }
123767       }
123768
123769       sqlite3_free(aTC);
123770     }
123771   }
123772 #endif
123773
123774   fts3EvalStartReaders(pCsr, pCsr->pExpr, 1, &rc);
123775   return rc;
123776 }
123777
123778 /*
123779 ** Invalidate the current position list for phrase pPhrase.
123780 */
123781 static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
123782   if( pPhrase->doclist.bFreeList ){
123783     sqlite3_free(pPhrase->doclist.pList);
123784   }
123785   pPhrase->doclist.pList = 0;
123786   pPhrase->doclist.nList = 0;
123787   pPhrase->doclist.bFreeList = 0;
123788 }
123789
123790 /*
123791 ** This function is called to edit the position list associated with
123792 ** the phrase object passed as the fifth argument according to a NEAR
123793 ** condition. For example:
123794 **
123795 **     abc NEAR/5 "def ghi"
123796 **
123797 ** Parameter nNear is passed the NEAR distance of the expression (5 in
123798 ** the example above). When this function is called, *paPoslist points to
123799 ** the position list, and *pnToken is the number of phrase tokens in, the
123800 ** phrase on the other side of the NEAR operator to pPhrase. For example,
123801 ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
123802 ** the position list associated with phrase "abc".
123803 **
123804 ** All positions in the pPhrase position list that are not sufficiently
123805 ** close to a position in the *paPoslist position list are removed. If this
123806 ** leaves 0 positions, zero is returned. Otherwise, non-zero.
123807 **
123808 ** Before returning, *paPoslist is set to point to the position lsit 
123809 ** associated with pPhrase. And *pnToken is set to the number of tokens in
123810 ** pPhrase.
123811 */
123812 static int fts3EvalNearTrim(
123813   int nNear,                      /* NEAR distance. As in "NEAR/nNear". */
123814   char *aTmp,                     /* Temporary space to use */
123815   char **paPoslist,               /* IN/OUT: Position list */
123816   int *pnToken,                   /* IN/OUT: Tokens in phrase of *paPoslist */
123817   Fts3Phrase *pPhrase             /* The phrase object to trim the doclist of */
123818 ){
123819   int nParam1 = nNear + pPhrase->nToken;
123820   int nParam2 = nNear + *pnToken;
123821   int nNew;
123822   char *p2; 
123823   char *pOut; 
123824   int res;
123825
123826   assert( pPhrase->doclist.pList );
123827
123828   p2 = pOut = pPhrase->doclist.pList;
123829   res = fts3PoslistNearMerge(
123830     &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
123831   );
123832   if( res ){
123833     nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
123834     assert( pPhrase->doclist.pList[nNew]=='\0' );
123835     assert( nNew<=pPhrase->doclist.nList && nNew>0 );
123836     memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
123837     pPhrase->doclist.nList = nNew;
123838     *paPoslist = pPhrase->doclist.pList;
123839     *pnToken = pPhrase->nToken;
123840   }
123841
123842   return res;
123843 }
123844
123845 /*
123846 ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
123847 ** Otherwise, it advances the expression passed as the second argument to
123848 ** point to the next matching row in the database. Expressions iterate through
123849 ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
123850 ** or descending if it is non-zero.
123851 **
123852 ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
123853 ** successful, the following variables in pExpr are set:
123854 **
123855 **   Fts3Expr.bEof                (non-zero if EOF - there is no next row)
123856 **   Fts3Expr.iDocid              (valid if bEof==0. The docid of the next row)
123857 **
123858 ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
123859 ** at EOF, then the following variables are populated with the position list
123860 ** for the phrase for the visited row:
123861 **
123862 **   FTs3Expr.pPhrase->doclist.nList        (length of pList in bytes)
123863 **   FTs3Expr.pPhrase->doclist.pList        (pointer to position list)
123864 **
123865 ** It says above that this function advances the expression to the next
123866 ** matching row. This is usually true, but there are the following exceptions:
123867 **
123868 **   1. Deferred tokens are not taken into account. If a phrase consists
123869 **      entirely of deferred tokens, it is assumed to match every row in
123870 **      the db. In this case the position-list is not populated at all. 
123871 **
123872 **      Or, if a phrase contains one or more deferred tokens and one or
123873 **      more non-deferred tokens, then the expression is advanced to the 
123874 **      next possible match, considering only non-deferred tokens. In other
123875 **      words, if the phrase is "A B C", and "B" is deferred, the expression
123876 **      is advanced to the next row that contains an instance of "A * C", 
123877 **      where "*" may match any single token. The position list in this case
123878 **      is populated as for "A * C" before returning.
123879 **
123880 **   2. NEAR is treated as AND. If the expression is "x NEAR y", it is 
123881 **      advanced to point to the next row that matches "x AND y".
123882 ** 
123883 ** See fts3EvalTestDeferredAndNear() for details on testing if a row is
123884 ** really a match, taking into account deferred tokens and NEAR operators.
123885 */
123886 static void fts3EvalNextRow(
123887   Fts3Cursor *pCsr,               /* FTS Cursor handle */
123888   Fts3Expr *pExpr,                /* Expr. to advance to next matching row */
123889   int *pRc                        /* IN/OUT: Error code */
123890 ){
123891   if( *pRc==SQLITE_OK ){
123892     int bDescDoclist = pCsr->bDesc;         /* Used by DOCID_CMP() macro */
123893     assert( pExpr->bEof==0 );
123894     pExpr->bStart = 1;
123895
123896     switch( pExpr->eType ){
123897       case FTSQUERY_NEAR:
123898       case FTSQUERY_AND: {
123899         Fts3Expr *pLeft = pExpr->pLeft;
123900         Fts3Expr *pRight = pExpr->pRight;
123901         assert( !pLeft->bDeferred || !pRight->bDeferred );
123902
123903         if( pLeft->bDeferred ){
123904           /* LHS is entirely deferred. So we assume it matches every row.
123905           ** Advance the RHS iterator to find the next row visited. */
123906           fts3EvalNextRow(pCsr, pRight, pRc);
123907           pExpr->iDocid = pRight->iDocid;
123908           pExpr->bEof = pRight->bEof;
123909         }else if( pRight->bDeferred ){
123910           /* RHS is entirely deferred. So we assume it matches every row.
123911           ** Advance the LHS iterator to find the next row visited. */
123912           fts3EvalNextRow(pCsr, pLeft, pRc);
123913           pExpr->iDocid = pLeft->iDocid;
123914           pExpr->bEof = pLeft->bEof;
123915         }else{
123916           /* Neither the RHS or LHS are deferred. */
123917           fts3EvalNextRow(pCsr, pLeft, pRc);
123918           fts3EvalNextRow(pCsr, pRight, pRc);
123919           while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
123920             sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
123921             if( iDiff==0 ) break;
123922             if( iDiff<0 ){
123923               fts3EvalNextRow(pCsr, pLeft, pRc);
123924             }else{
123925               fts3EvalNextRow(pCsr, pRight, pRc);
123926             }
123927           }
123928           pExpr->iDocid = pLeft->iDocid;
123929           pExpr->bEof = (pLeft->bEof || pRight->bEof);
123930         }
123931         break;
123932       }
123933   
123934       case FTSQUERY_OR: {
123935         Fts3Expr *pLeft = pExpr->pLeft;
123936         Fts3Expr *pRight = pExpr->pRight;
123937         sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
123938
123939         assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
123940         assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
123941
123942         if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
123943           fts3EvalNextRow(pCsr, pLeft, pRc);
123944         }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){
123945           fts3EvalNextRow(pCsr, pRight, pRc);
123946         }else{
123947           fts3EvalNextRow(pCsr, pLeft, pRc);
123948           fts3EvalNextRow(pCsr, pRight, pRc);
123949         }
123950
123951         pExpr->bEof = (pLeft->bEof && pRight->bEof);
123952         iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
123953         if( pRight->bEof || (pLeft->bEof==0 &&  iCmp<0) ){
123954           pExpr->iDocid = pLeft->iDocid;
123955         }else{
123956           pExpr->iDocid = pRight->iDocid;
123957         }
123958
123959         break;
123960       }
123961
123962       case FTSQUERY_NOT: {
123963         Fts3Expr *pLeft = pExpr->pLeft;
123964         Fts3Expr *pRight = pExpr->pRight;
123965
123966         if( pRight->bStart==0 ){
123967           fts3EvalNextRow(pCsr, pRight, pRc);
123968           assert( *pRc!=SQLITE_OK || pRight->bStart );
123969         }
123970
123971         fts3EvalNextRow(pCsr, pLeft, pRc);
123972         if( pLeft->bEof==0 ){
123973           while( !*pRc 
123974               && !pRight->bEof 
123975               && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0 
123976           ){
123977             fts3EvalNextRow(pCsr, pRight, pRc);
123978           }
123979         }
123980         pExpr->iDocid = pLeft->iDocid;
123981         pExpr->bEof = pLeft->bEof;
123982         break;
123983       }
123984
123985       default: {
123986         Fts3Phrase *pPhrase = pExpr->pPhrase;
123987         fts3EvalInvalidatePoslist(pPhrase);
123988         *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
123989         pExpr->iDocid = pPhrase->doclist.iDocid;
123990         break;
123991       }
123992     }
123993   }
123994 }
123995
123996 /*
123997 ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
123998 ** cluster, then this function returns 1 immediately.
123999 **
124000 ** Otherwise, it checks if the current row really does match the NEAR 
124001 ** expression, using the data currently stored in the position lists 
124002 ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression. 
124003 **
124004 ** If the current row is a match, the position list associated with each
124005 ** phrase in the NEAR expression is edited in place to contain only those
124006 ** phrase instances sufficiently close to their peers to satisfy all NEAR
124007 ** constraints. In this case it returns 1. If the NEAR expression does not 
124008 ** match the current row, 0 is returned. The position lists may or may not
124009 ** be edited if 0 is returned.
124010 */
124011 static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
124012   int res = 1;
124013
124014   /* The following block runs if pExpr is the root of a NEAR query.
124015   ** For example, the query:
124016   **
124017   **         "w" NEAR "x" NEAR "y" NEAR "z"
124018   **
124019   ** which is represented in tree form as:
124020   **
124021   **                               |
124022   **                          +--NEAR--+      <-- root of NEAR query
124023   **                          |        |
124024   **                     +--NEAR--+   "z"
124025   **                     |        |
124026   **                +--NEAR--+   "y"
124027   **                |        |
124028   **               "w"      "x"
124029   **
124030   ** The right-hand child of a NEAR node is always a phrase. The 
124031   ** left-hand child may be either a phrase or a NEAR node. There are
124032   ** no exceptions to this - it's the way the parser in fts3_expr.c works.
124033   */
124034   if( *pRc==SQLITE_OK 
124035    && pExpr->eType==FTSQUERY_NEAR 
124036    && pExpr->bEof==0
124037    && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
124038   ){
124039     Fts3Expr *p; 
124040     int nTmp = 0;                 /* Bytes of temp space */
124041     char *aTmp;                   /* Temp space for PoslistNearMerge() */
124042
124043     /* Allocate temporary working space. */
124044     for(p=pExpr; p->pLeft; p=p->pLeft){
124045       nTmp += p->pRight->pPhrase->doclist.nList;
124046     }
124047     nTmp += p->pPhrase->doclist.nList;
124048     if( nTmp==0 ){
124049       res = 0;
124050     }else{
124051       aTmp = sqlite3_malloc(nTmp*2);
124052       if( !aTmp ){
124053         *pRc = SQLITE_NOMEM;
124054         res = 0;
124055       }else{
124056         char *aPoslist = p->pPhrase->doclist.pList;
124057         int nToken = p->pPhrase->nToken;
124058
124059         for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
124060           Fts3Phrase *pPhrase = p->pRight->pPhrase;
124061           int nNear = p->nNear;
124062           res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
124063         }
124064
124065         aPoslist = pExpr->pRight->pPhrase->doclist.pList;
124066         nToken = pExpr->pRight->pPhrase->nToken;
124067         for(p=pExpr->pLeft; p && res; p=p->pLeft){
124068           int nNear;
124069           Fts3Phrase *pPhrase;
124070           assert( p->pParent && p->pParent->pLeft==p );
124071           nNear = p->pParent->nNear;
124072           pPhrase = (
124073               p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
124074               );
124075           res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
124076         }
124077       }
124078
124079       sqlite3_free(aTmp);
124080     }
124081   }
124082
124083   return res;
124084 }
124085
124086 /*
124087 ** This function is a helper function for fts3EvalTestDeferredAndNear().
124088 ** Assuming no error occurs or has occurred, It returns non-zero if the
124089 ** expression passed as the second argument matches the row that pCsr 
124090 ** currently points to, or zero if it does not.
124091 **
124092 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
124093 ** If an error occurs during execution of this function, *pRc is set to 
124094 ** the appropriate SQLite error code. In this case the returned value is 
124095 ** undefined.
124096 */
124097 static int fts3EvalTestExpr(
124098   Fts3Cursor *pCsr,               /* FTS cursor handle */
124099   Fts3Expr *pExpr,                /* Expr to test. May or may not be root. */
124100   int *pRc                        /* IN/OUT: Error code */
124101 ){
124102   int bHit = 1;                   /* Return value */
124103   if( *pRc==SQLITE_OK ){
124104     switch( pExpr->eType ){
124105       case FTSQUERY_NEAR:
124106       case FTSQUERY_AND:
124107         bHit = (
124108             fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
124109          && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
124110          && fts3EvalNearTest(pExpr, pRc)
124111         );
124112
124113         /* If the NEAR expression does not match any rows, zero the doclist for 
124114         ** all phrases involved in the NEAR. This is because the snippet(),
124115         ** offsets() and matchinfo() functions are not supposed to recognize 
124116         ** any instances of phrases that are part of unmatched NEAR queries. 
124117         ** For example if this expression:
124118         **
124119         **    ... MATCH 'a OR (b NEAR c)'
124120         **
124121         ** is matched against a row containing:
124122         **
124123         **        'a b d e'
124124         **
124125         ** then any snippet() should ony highlight the "a" term, not the "b"
124126         ** (as "b" is part of a non-matching NEAR clause).
124127         */
124128         if( bHit==0 
124129          && pExpr->eType==FTSQUERY_NEAR 
124130          && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
124131         ){
124132           Fts3Expr *p;
124133           for(p=pExpr; p->pPhrase==0; p=p->pLeft){
124134             if( p->pRight->iDocid==pCsr->iPrevId ){
124135               fts3EvalInvalidatePoslist(p->pRight->pPhrase);
124136             }
124137           }
124138           if( p->iDocid==pCsr->iPrevId ){
124139             fts3EvalInvalidatePoslist(p->pPhrase);
124140           }
124141         }
124142
124143         break;
124144
124145       case FTSQUERY_OR: {
124146         int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
124147         int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
124148         bHit = bHit1 || bHit2;
124149         break;
124150       }
124151
124152       case FTSQUERY_NOT:
124153         bHit = (
124154             fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
124155          && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
124156         );
124157         break;
124158
124159       default: {
124160 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
124161         if( pCsr->pDeferred 
124162          && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
124163         ){
124164           Fts3Phrase *pPhrase = pExpr->pPhrase;
124165           assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
124166           if( pExpr->bDeferred ){
124167             fts3EvalInvalidatePoslist(pPhrase);
124168           }
124169           *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
124170           bHit = (pPhrase->doclist.pList!=0);
124171           pExpr->iDocid = pCsr->iPrevId;
124172         }else
124173 #endif
124174         {
124175           bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
124176         }
124177         break;
124178       }
124179     }
124180   }
124181   return bHit;
124182 }
124183
124184 /*
124185 ** This function is called as the second part of each xNext operation when
124186 ** iterating through the results of a full-text query. At this point the
124187 ** cursor points to a row that matches the query expression, with the
124188 ** following caveats:
124189 **
124190 **   * Up until this point, "NEAR" operators in the expression have been
124191 **     treated as "AND".
124192 **
124193 **   * Deferred tokens have not yet been considered.
124194 **
124195 ** If *pRc is not SQLITE_OK when this function is called, it immediately
124196 ** returns 0. Otherwise, it tests whether or not after considering NEAR
124197 ** operators and deferred tokens the current row is still a match for the
124198 ** expression. It returns 1 if both of the following are true:
124199 **
124200 **   1. *pRc is SQLITE_OK when this function returns, and
124201 **
124202 **   2. After scanning the current FTS table row for the deferred tokens,
124203 **      it is determined that the row does *not* match the query.
124204 **
124205 ** Or, if no error occurs and it seems the current row does match the FTS
124206 ** query, return 0.
124207 */
124208 static int fts3EvalTestDeferredAndNear(Fts3Cursor *pCsr, int *pRc){
124209   int rc = *pRc;
124210   int bMiss = 0;
124211   if( rc==SQLITE_OK ){
124212
124213     /* If there are one or more deferred tokens, load the current row into
124214     ** memory and scan it to determine the position list for each deferred
124215     ** token. Then, see if this row is really a match, considering deferred
124216     ** tokens and NEAR operators (neither of which were taken into account
124217     ** earlier, by fts3EvalNextRow()). 
124218     */
124219     if( pCsr->pDeferred ){
124220       rc = fts3CursorSeek(0, pCsr);
124221       if( rc==SQLITE_OK ){
124222         rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
124223       }
124224     }
124225     bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
124226
124227     /* Free the position-lists accumulated for each deferred token above. */
124228     sqlite3Fts3FreeDeferredDoclists(pCsr);
124229     *pRc = rc;
124230   }
124231   return (rc==SQLITE_OK && bMiss);
124232 }
124233
124234 /*
124235 ** Advance to the next document that matches the FTS expression in
124236 ** Fts3Cursor.pExpr.
124237 */
124238 static int fts3EvalNext(Fts3Cursor *pCsr){
124239   int rc = SQLITE_OK;             /* Return Code */
124240   Fts3Expr *pExpr = pCsr->pExpr;
124241   assert( pCsr->isEof==0 );
124242   if( pExpr==0 ){
124243     pCsr->isEof = 1;
124244   }else{
124245     do {
124246       if( pCsr->isRequireSeek==0 ){
124247         sqlite3_reset(pCsr->pStmt);
124248       }
124249       assert( sqlite3_data_count(pCsr->pStmt)==0 );
124250       fts3EvalNextRow(pCsr, pExpr, &rc);
124251       pCsr->isEof = pExpr->bEof;
124252       pCsr->isRequireSeek = 1;
124253       pCsr->isMatchinfoNeeded = 1;
124254       pCsr->iPrevId = pExpr->iDocid;
124255     }while( pCsr->isEof==0 && fts3EvalTestDeferredAndNear(pCsr, &rc) );
124256   }
124257   return rc;
124258 }
124259
124260 /*
124261 ** Restart interation for expression pExpr so that the next call to
124262 ** fts3EvalNext() visits the first row. Do not allow incremental 
124263 ** loading or merging of phrase doclists for this iteration.
124264 **
124265 ** If *pRc is other than SQLITE_OK when this function is called, it is
124266 ** a no-op. If an error occurs within this function, *pRc is set to an
124267 ** SQLite error code before returning.
124268 */
124269 static void fts3EvalRestart(
124270   Fts3Cursor *pCsr,
124271   Fts3Expr *pExpr,
124272   int *pRc
124273 ){
124274   if( pExpr && *pRc==SQLITE_OK ){
124275     Fts3Phrase *pPhrase = pExpr->pPhrase;
124276
124277     if( pPhrase ){
124278       fts3EvalInvalidatePoslist(pPhrase);
124279       if( pPhrase->bIncr ){
124280         assert( pPhrase->nToken==1 );
124281         assert( pPhrase->aToken[0].pSegcsr );
124282         sqlite3Fts3MsrIncrRestart(pPhrase->aToken[0].pSegcsr);
124283         *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
124284       }
124285
124286       pPhrase->doclist.pNextDocid = 0;
124287       pPhrase->doclist.iDocid = 0;
124288     }
124289
124290     pExpr->iDocid = 0;
124291     pExpr->bEof = 0;
124292     pExpr->bStart = 0;
124293
124294     fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
124295     fts3EvalRestart(pCsr, pExpr->pRight, pRc);
124296   }
124297 }
124298
124299 /*
124300 ** After allocating the Fts3Expr.aMI[] array for each phrase in the 
124301 ** expression rooted at pExpr, the cursor iterates through all rows matched
124302 ** by pExpr, calling this function for each row. This function increments
124303 ** the values in Fts3Expr.aMI[] according to the position-list currently
124304 ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase 
124305 ** expression nodes.
124306 */
124307 static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
124308   if( pExpr ){
124309     Fts3Phrase *pPhrase = pExpr->pPhrase;
124310     if( pPhrase && pPhrase->doclist.pList ){
124311       int iCol = 0;
124312       char *p = pPhrase->doclist.pList;
124313
124314       assert( *p );
124315       while( 1 ){
124316         u8 c = 0;
124317         int iCnt = 0;
124318         while( 0xFE & (*p | c) ){
124319           if( (c&0x80)==0 ) iCnt++;
124320           c = *p++ & 0x80;
124321         }
124322
124323         /* aMI[iCol*3 + 1] = Number of occurrences
124324         ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
124325         */
124326         pExpr->aMI[iCol*3 + 1] += iCnt;
124327         pExpr->aMI[iCol*3 + 2] += (iCnt>0);
124328         if( *p==0x00 ) break;
124329         p++;
124330         p += sqlite3Fts3GetVarint32(p, &iCol);
124331       }
124332     }
124333
124334     fts3EvalUpdateCounts(pExpr->pLeft);
124335     fts3EvalUpdateCounts(pExpr->pRight);
124336   }
124337 }
124338
124339 /*
124340 ** Expression pExpr must be of type FTSQUERY_PHRASE.
124341 **
124342 ** If it is not already allocated and populated, this function allocates and
124343 ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
124344 ** of a NEAR expression, then it also allocates and populates the same array
124345 ** for all other phrases that are part of the NEAR expression.
124346 **
124347 ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
124348 ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
124349 */
124350 static int fts3EvalGatherStats(
124351   Fts3Cursor *pCsr,               /* Cursor object */
124352   Fts3Expr *pExpr                 /* FTSQUERY_PHRASE expression */
124353 ){
124354   int rc = SQLITE_OK;             /* Return code */
124355
124356   assert( pExpr->eType==FTSQUERY_PHRASE );
124357   if( pExpr->aMI==0 ){
124358     Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
124359     Fts3Expr *pRoot;                /* Root of NEAR expression */
124360     Fts3Expr *p;                    /* Iterator used for several purposes */
124361
124362     sqlite3_int64 iPrevId = pCsr->iPrevId;
124363     sqlite3_int64 iDocid;
124364     u8 bEof;
124365
124366     /* Find the root of the NEAR expression */
124367     pRoot = pExpr;
124368     while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
124369       pRoot = pRoot->pParent;
124370     }
124371     iDocid = pRoot->iDocid;
124372     bEof = pRoot->bEof;
124373     assert( pRoot->bStart );
124374
124375     /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
124376     for(p=pRoot; p; p=p->pLeft){
124377       Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
124378       assert( pE->aMI==0 );
124379       pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
124380       if( !pE->aMI ) return SQLITE_NOMEM;
124381       memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
124382     }
124383
124384     fts3EvalRestart(pCsr, pRoot, &rc);
124385
124386     while( pCsr->isEof==0 && rc==SQLITE_OK ){
124387
124388       do {
124389         /* Ensure the %_content statement is reset. */
124390         if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
124391         assert( sqlite3_data_count(pCsr->pStmt)==0 );
124392
124393         /* Advance to the next document */
124394         fts3EvalNextRow(pCsr, pRoot, &rc);
124395         pCsr->isEof = pRoot->bEof;
124396         pCsr->isRequireSeek = 1;
124397         pCsr->isMatchinfoNeeded = 1;
124398         pCsr->iPrevId = pRoot->iDocid;
124399       }while( pCsr->isEof==0 
124400            && pRoot->eType==FTSQUERY_NEAR 
124401            && fts3EvalTestDeferredAndNear(pCsr, &rc) 
124402       );
124403
124404       if( rc==SQLITE_OK && pCsr->isEof==0 ){
124405         fts3EvalUpdateCounts(pRoot);
124406       }
124407     }
124408
124409     pCsr->isEof = 0;
124410     pCsr->iPrevId = iPrevId;
124411
124412     if( bEof ){
124413       pRoot->bEof = bEof;
124414     }else{
124415       /* Caution: pRoot may iterate through docids in ascending or descending
124416       ** order. For this reason, even though it seems more defensive, the 
124417       ** do loop can not be written:
124418       **
124419       **   do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
124420       */
124421       fts3EvalRestart(pCsr, pRoot, &rc);
124422       do {
124423         fts3EvalNextRow(pCsr, pRoot, &rc);
124424         assert( pRoot->bEof==0 );
124425       }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
124426       fts3EvalTestDeferredAndNear(pCsr, &rc);
124427     }
124428   }
124429   return rc;
124430 }
124431
124432 /*
124433 ** This function is used by the matchinfo() module to query a phrase 
124434 ** expression node for the following information:
124435 **
124436 **   1. The total number of occurrences of the phrase in each column of 
124437 **      the FTS table (considering all rows), and
124438 **
124439 **   2. For each column, the number of rows in the table for which the
124440 **      column contains at least one instance of the phrase.
124441 **
124442 ** If no error occurs, SQLITE_OK is returned and the values for each column
124443 ** written into the array aiOut as follows:
124444 **
124445 **   aiOut[iCol*3 + 1] = Number of occurrences
124446 **   aiOut[iCol*3 + 2] = Number of rows containing at least one instance
124447 **
124448 ** Caveats:
124449 **
124450 **   * If a phrase consists entirely of deferred tokens, then all output 
124451 **     values are set to the number of documents in the table. In other
124452 **     words we assume that very common tokens occur exactly once in each 
124453 **     column of each row of the table.
124454 **
124455 **   * If a phrase contains some deferred tokens (and some non-deferred 
124456 **     tokens), count the potential occurrence identified by considering
124457 **     the non-deferred tokens instead of actual phrase occurrences.
124458 **
124459 **   * If the phrase is part of a NEAR expression, then only phrase instances
124460 **     that meet the NEAR constraint are included in the counts.
124461 */
124462 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
124463   Fts3Cursor *pCsr,               /* FTS cursor handle */
124464   Fts3Expr *pExpr,                /* Phrase expression */
124465   u32 *aiOut                      /* Array to write results into (see above) */
124466 ){
124467   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
124468   int rc = SQLITE_OK;
124469   int iCol;
124470
124471   if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
124472     assert( pCsr->nDoc>0 );
124473     for(iCol=0; iCol<pTab->nColumn; iCol++){
124474       aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
124475       aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
124476     }
124477   }else{
124478     rc = fts3EvalGatherStats(pCsr, pExpr);
124479     if( rc==SQLITE_OK ){
124480       assert( pExpr->aMI );
124481       for(iCol=0; iCol<pTab->nColumn; iCol++){
124482         aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
124483         aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
124484       }
124485     }
124486   }
124487
124488   return rc;
124489 }
124490
124491 /*
124492 ** The expression pExpr passed as the second argument to this function
124493 ** must be of type FTSQUERY_PHRASE. 
124494 **
124495 ** The returned value is either NULL or a pointer to a buffer containing
124496 ** a position-list indicating the occurrences of the phrase in column iCol
124497 ** of the current row. 
124498 **
124499 ** More specifically, the returned buffer contains 1 varint for each 
124500 ** occurrence of the phrase in the column, stored using the normal (delta+2) 
124501 ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
124502 ** if the requested column contains "a b X c d X X" and the position-list
124503 ** for 'X' is requested, the buffer returned may contain:
124504 **
124505 **     0x04 0x05 0x03 0x01   or   0x04 0x05 0x03 0x00
124506 **
124507 ** This function works regardless of whether or not the phrase is deferred,
124508 ** incremental, or neither.
124509 */
124510 SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
124511   Fts3Cursor *pCsr,               /* FTS3 cursor object */
124512   Fts3Expr *pExpr,                /* Phrase to return doclist for */
124513   int iCol,                       /* Column to return position list for */
124514   char **ppOut                    /* OUT: Pointer to position list */
124515 ){
124516   Fts3Phrase *pPhrase = pExpr->pPhrase;
124517   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
124518   char *pIter;
124519   int iThis;
124520   sqlite3_int64 iDocid;
124521
124522   /* If this phrase is applies specifically to some column other than 
124523   ** column iCol, return a NULL pointer.  */
124524   *ppOut = 0;
124525   assert( iCol>=0 && iCol<pTab->nColumn );
124526   if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
124527     return SQLITE_OK;
124528   }
124529
124530   iDocid = pExpr->iDocid;
124531   pIter = pPhrase->doclist.pList;
124532   if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
124533     int bDescDoclist = pTab->bDescIdx;      /* For DOCID_CMP macro */
124534     int bOr = 0;
124535     u8 bEof = 0;
124536     Fts3Expr *p;
124537
124538     /* Check if this phrase descends from an OR expression node. If not, 
124539     ** return NULL. Otherwise, the entry that corresponds to docid 
124540     ** pCsr->iPrevId may lie earlier in the doclist buffer. */
124541     for(p=pExpr->pParent; p; p=p->pParent){
124542       if( p->eType==FTSQUERY_OR ) bOr = 1;
124543     }
124544     if( bOr==0 ) return SQLITE_OK;
124545
124546     /* This is the descendent of an OR node. In this case we cannot use
124547     ** an incremental phrase. Load the entire doclist for the phrase
124548     ** into memory in this case.  */
124549     if( pPhrase->bIncr ){
124550       int rc = SQLITE_OK;
124551       int bEofSave = pExpr->bEof;
124552       fts3EvalRestart(pCsr, pExpr, &rc);
124553       while( rc==SQLITE_OK && !pExpr->bEof ){
124554         fts3EvalNextRow(pCsr, pExpr, &rc);
124555         if( bEofSave==0 && pExpr->iDocid==iDocid ) break;
124556       }
124557       pIter = pPhrase->doclist.pList;
124558       assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
124559       if( rc!=SQLITE_OK ) return rc;
124560     }
124561
124562     if( pExpr->bEof ){
124563       pIter = 0;
124564       iDocid = 0;
124565     }
124566     bEof = (pPhrase->doclist.nAll==0);
124567     assert( bDescDoclist==0 || bDescDoclist==1 );
124568     assert( pCsr->bDesc==0 || pCsr->bDesc==1 );
124569
124570     if( pCsr->bDesc==bDescDoclist ){
124571       int dummy;
124572       while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
124573         sqlite3Fts3DoclistPrev(
124574             bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll, 
124575             &pIter, &iDocid, &dummy, &bEof
124576         );
124577       }
124578     }else{
124579       while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
124580         sqlite3Fts3DoclistNext(
124581             bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll, 
124582             &pIter, &iDocid, &bEof
124583         );
124584       }
124585     }
124586
124587     if( bEof || iDocid!=pCsr->iPrevId ) pIter = 0;
124588   }
124589   if( pIter==0 ) return SQLITE_OK;
124590
124591   if( *pIter==0x01 ){
124592     pIter++;
124593     pIter += sqlite3Fts3GetVarint32(pIter, &iThis);
124594   }else{
124595     iThis = 0;
124596   }
124597   while( iThis<iCol ){
124598     fts3ColumnlistCopy(0, &pIter);
124599     if( *pIter==0x00 ) return 0;
124600     pIter++;
124601     pIter += sqlite3Fts3GetVarint32(pIter, &iThis);
124602   }
124603
124604   *ppOut = ((iCol==iThis)?pIter:0);
124605   return SQLITE_OK;
124606 }
124607
124608 /*
124609 ** Free all components of the Fts3Phrase structure that were allocated by
124610 ** the eval module. Specifically, this means to free:
124611 **
124612 **   * the contents of pPhrase->doclist, and
124613 **   * any Fts3MultiSegReader objects held by phrase tokens.
124614 */
124615 SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
124616   if( pPhrase ){
124617     int i;
124618     sqlite3_free(pPhrase->doclist.aAll);
124619     fts3EvalInvalidatePoslist(pPhrase);
124620     memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
124621     for(i=0; i<pPhrase->nToken; i++){
124622       fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
124623       pPhrase->aToken[i].pSegcsr = 0;
124624     }
124625   }
124626 }
124627
124628
124629 /*
124630 ** Return SQLITE_CORRUPT_VTAB.
124631 */
124632 #ifdef SQLITE_DEBUG
124633 SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
124634   return SQLITE_CORRUPT_VTAB;
124635 }
124636 #endif
124637
124638 #if !SQLITE_CORE
124639 /*
124640 ** Initialize API pointer table, if required.
124641 */
124642 SQLITE_API int sqlite3_extension_init(
124643   sqlite3 *db, 
124644   char **pzErrMsg,
124645   const sqlite3_api_routines *pApi
124646 ){
124647   SQLITE_EXTENSION_INIT2(pApi)
124648   return sqlite3Fts3Init(db);
124649 }
124650 #endif
124651
124652 #endif
124653
124654 /************** End of fts3.c ************************************************/
124655 /************** Begin file fts3_aux.c ****************************************/
124656 /*
124657 ** 2011 Jan 27
124658 **
124659 ** The author disclaims copyright to this source code.  In place of
124660 ** a legal notice, here is a blessing:
124661 **
124662 **    May you do good and not evil.
124663 **    May you find forgiveness for yourself and forgive others.
124664 **    May you share freely, never taking more than you give.
124665 **
124666 ******************************************************************************
124667 **
124668 */
124669 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
124670
124671 /* #include <string.h> */
124672 /* #include <assert.h> */
124673
124674 typedef struct Fts3auxTable Fts3auxTable;
124675 typedef struct Fts3auxCursor Fts3auxCursor;
124676
124677 struct Fts3auxTable {
124678   sqlite3_vtab base;              /* Base class used by SQLite core */
124679   Fts3Table *pFts3Tab;
124680 };
124681
124682 struct Fts3auxCursor {
124683   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
124684   Fts3MultiSegReader csr;        /* Must be right after "base" */
124685   Fts3SegFilter filter;
124686   char *zStop;
124687   int nStop;                      /* Byte-length of string zStop */
124688   int isEof;                      /* True if cursor is at EOF */
124689   sqlite3_int64 iRowid;           /* Current rowid */
124690
124691   int iCol;                       /* Current value of 'col' column */
124692   int nStat;                      /* Size of aStat[] array */
124693   struct Fts3auxColstats {
124694     sqlite3_int64 nDoc;           /* 'documents' values for current csr row */
124695     sqlite3_int64 nOcc;           /* 'occurrences' values for current csr row */
124696   } *aStat;
124697 };
124698
124699 /*
124700 ** Schema of the terms table.
124701 */
124702 #define FTS3_TERMS_SCHEMA "CREATE TABLE x(term, col, documents, occurrences)"
124703
124704 /*
124705 ** This function does all the work for both the xConnect and xCreate methods.
124706 ** These tables have no persistent representation of their own, so xConnect
124707 ** and xCreate are identical operations.
124708 */
124709 static int fts3auxConnectMethod(
124710   sqlite3 *db,                    /* Database connection */
124711   void *pUnused,                  /* Unused */
124712   int argc,                       /* Number of elements in argv array */
124713   const char * const *argv,       /* xCreate/xConnect argument array */
124714   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
124715   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
124716 ){
124717   char const *zDb;                /* Name of database (e.g. "main") */
124718   char const *zFts3;              /* Name of fts3 table */
124719   int nDb;                        /* Result of strlen(zDb) */
124720   int nFts3;                      /* Result of strlen(zFts3) */
124721   int nByte;                      /* Bytes of space to allocate here */
124722   int rc;                         /* value returned by declare_vtab() */
124723   Fts3auxTable *p;                /* Virtual table object to return */
124724
124725   UNUSED_PARAMETER(pUnused);
124726
124727   /* The user should invoke this in one of two forms:
124728   **
124729   **     CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table);
124730   **     CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table);
124731   */
124732   if( argc!=4 && argc!=5 ) goto bad_args;
124733
124734   zDb = argv[1]; 
124735   nDb = (int)strlen(zDb);
124736   if( argc==5 ){
124737     if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){
124738       zDb = argv[3]; 
124739       nDb = (int)strlen(zDb);
124740       zFts3 = argv[4];
124741     }else{
124742       goto bad_args;
124743     }
124744   }else{
124745     zFts3 = argv[3];
124746   }
124747   nFts3 = (int)strlen(zFts3);
124748
124749   rc = sqlite3_declare_vtab(db, FTS3_TERMS_SCHEMA);
124750   if( rc!=SQLITE_OK ) return rc;
124751
124752   nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
124753   p = (Fts3auxTable *)sqlite3_malloc(nByte);
124754   if( !p ) return SQLITE_NOMEM;
124755   memset(p, 0, nByte);
124756
124757   p->pFts3Tab = (Fts3Table *)&p[1];
124758   p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
124759   p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
124760   p->pFts3Tab->db = db;
124761   p->pFts3Tab->nIndex = 1;
124762
124763   memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
124764   memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
124765   sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
124766
124767   *ppVtab = (sqlite3_vtab *)p;
124768   return SQLITE_OK;
124769
124770  bad_args:
124771   *pzErr = sqlite3_mprintf("invalid arguments to fts4aux constructor");
124772   return SQLITE_ERROR;
124773 }
124774
124775 /*
124776 ** This function does the work for both the xDisconnect and xDestroy methods.
124777 ** These tables have no persistent representation of their own, so xDisconnect
124778 ** and xDestroy are identical operations.
124779 */
124780 static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
124781   Fts3auxTable *p = (Fts3auxTable *)pVtab;
124782   Fts3Table *pFts3 = p->pFts3Tab;
124783   int i;
124784
124785   /* Free any prepared statements held */
124786   for(i=0; i<SizeofArray(pFts3->aStmt); i++){
124787     sqlite3_finalize(pFts3->aStmt[i]);
124788   }
124789   sqlite3_free(pFts3->zSegmentsTbl);
124790   sqlite3_free(p);
124791   return SQLITE_OK;
124792 }
124793
124794 #define FTS4AUX_EQ_CONSTRAINT 1
124795 #define FTS4AUX_GE_CONSTRAINT 2
124796 #define FTS4AUX_LE_CONSTRAINT 4
124797
124798 /*
124799 ** xBestIndex - Analyze a WHERE and ORDER BY clause.
124800 */
124801 static int fts3auxBestIndexMethod(
124802   sqlite3_vtab *pVTab, 
124803   sqlite3_index_info *pInfo
124804 ){
124805   int i;
124806   int iEq = -1;
124807   int iGe = -1;
124808   int iLe = -1;
124809
124810   UNUSED_PARAMETER(pVTab);
124811
124812   /* This vtab delivers always results in "ORDER BY term ASC" order. */
124813   if( pInfo->nOrderBy==1 
124814    && pInfo->aOrderBy[0].iColumn==0 
124815    && pInfo->aOrderBy[0].desc==0
124816   ){
124817     pInfo->orderByConsumed = 1;
124818   }
124819
124820   /* Search for equality and range constraints on the "term" column. */
124821   for(i=0; i<pInfo->nConstraint; i++){
124822     if( pInfo->aConstraint[i].usable && pInfo->aConstraint[i].iColumn==0 ){
124823       int op = pInfo->aConstraint[i].op;
124824       if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
124825       if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
124826       if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
124827       if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
124828       if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
124829     }
124830   }
124831
124832   if( iEq>=0 ){
124833     pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
124834     pInfo->aConstraintUsage[iEq].argvIndex = 1;
124835     pInfo->estimatedCost = 5;
124836   }else{
124837     pInfo->idxNum = 0;
124838     pInfo->estimatedCost = 20000;
124839     if( iGe>=0 ){
124840       pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
124841       pInfo->aConstraintUsage[iGe].argvIndex = 1;
124842       pInfo->estimatedCost /= 2;
124843     }
124844     if( iLe>=0 ){
124845       pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
124846       pInfo->aConstraintUsage[iLe].argvIndex = 1 + (iGe>=0);
124847       pInfo->estimatedCost /= 2;
124848     }
124849   }
124850
124851   return SQLITE_OK;
124852 }
124853
124854 /*
124855 ** xOpen - Open a cursor.
124856 */
124857 static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
124858   Fts3auxCursor *pCsr;            /* Pointer to cursor object to return */
124859
124860   UNUSED_PARAMETER(pVTab);
124861
124862   pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
124863   if( !pCsr ) return SQLITE_NOMEM;
124864   memset(pCsr, 0, sizeof(Fts3auxCursor));
124865
124866   *ppCsr = (sqlite3_vtab_cursor *)pCsr;
124867   return SQLITE_OK;
124868 }
124869
124870 /*
124871 ** xClose - Close a cursor.
124872 */
124873 static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
124874   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
124875   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
124876
124877   sqlite3Fts3SegmentsClose(pFts3);
124878   sqlite3Fts3SegReaderFinish(&pCsr->csr);
124879   sqlite3_free((void *)pCsr->filter.zTerm);
124880   sqlite3_free(pCsr->zStop);
124881   sqlite3_free(pCsr->aStat);
124882   sqlite3_free(pCsr);
124883   return SQLITE_OK;
124884 }
124885
124886 static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
124887   if( nSize>pCsr->nStat ){
124888     struct Fts3auxColstats *aNew;
124889     aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat, 
124890         sizeof(struct Fts3auxColstats) * nSize
124891     );
124892     if( aNew==0 ) return SQLITE_NOMEM;
124893     memset(&aNew[pCsr->nStat], 0, 
124894         sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
124895     );
124896     pCsr->aStat = aNew;
124897     pCsr->nStat = nSize;
124898   }
124899   return SQLITE_OK;
124900 }
124901
124902 /*
124903 ** xNext - Advance the cursor to the next row, if any.
124904 */
124905 static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
124906   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
124907   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
124908   int rc;
124909
124910   /* Increment our pretend rowid value. */
124911   pCsr->iRowid++;
124912
124913   for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
124914     if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
124915   }
124916
124917   rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
124918   if( rc==SQLITE_ROW ){
124919     int i = 0;
124920     int nDoclist = pCsr->csr.nDoclist;
124921     char *aDoclist = pCsr->csr.aDoclist;
124922     int iCol;
124923
124924     int eState = 0;
124925
124926     if( pCsr->zStop ){
124927       int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
124928       int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
124929       if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
124930         pCsr->isEof = 1;
124931         return SQLITE_OK;
124932       }
124933     }
124934
124935     if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
124936     memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
124937     iCol = 0;
124938
124939     while( i<nDoclist ){
124940       sqlite3_int64 v = 0;
124941
124942       i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
124943       switch( eState ){
124944         /* State 0. In this state the integer just read was a docid. */
124945         case 0:
124946           pCsr->aStat[0].nDoc++;
124947           eState = 1;
124948           iCol = 0;
124949           break;
124950
124951         /* State 1. In this state we are expecting either a 1, indicating
124952         ** that the following integer will be a column number, or the
124953         ** start of a position list for column 0.  
124954         ** 
124955         ** The only difference between state 1 and state 2 is that if the
124956         ** integer encountered in state 1 is not 0 or 1, then we need to
124957         ** increment the column 0 "nDoc" count for this term.
124958         */
124959         case 1:
124960           assert( iCol==0 );
124961           if( v>1 ){
124962             pCsr->aStat[1].nDoc++;
124963           }
124964           eState = 2;
124965           /* fall through */
124966
124967         case 2:
124968           if( v==0 ){       /* 0x00. Next integer will be a docid. */
124969             eState = 0;
124970           }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
124971             eState = 3;
124972           }else{            /* 2 or greater. A position. */
124973             pCsr->aStat[iCol+1].nOcc++;
124974             pCsr->aStat[0].nOcc++;
124975           }
124976           break;
124977
124978         /* State 3. The integer just read is a column number. */
124979         default: assert( eState==3 );
124980           iCol = (int)v;
124981           if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
124982           pCsr->aStat[iCol+1].nDoc++;
124983           eState = 2;
124984           break;
124985       }
124986     }
124987
124988     pCsr->iCol = 0;
124989     rc = SQLITE_OK;
124990   }else{
124991     pCsr->isEof = 1;
124992   }
124993   return rc;
124994 }
124995
124996 /*
124997 ** xFilter - Initialize a cursor to point at the start of its data.
124998 */
124999 static int fts3auxFilterMethod(
125000   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
125001   int idxNum,                     /* Strategy index */
125002   const char *idxStr,             /* Unused */
125003   int nVal,                       /* Number of elements in apVal */
125004   sqlite3_value **apVal           /* Arguments for the indexing scheme */
125005 ){
125006   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
125007   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
125008   int rc;
125009   int isScan;
125010
125011   UNUSED_PARAMETER(nVal);
125012   UNUSED_PARAMETER(idxStr);
125013
125014   assert( idxStr==0 );
125015   assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
125016        || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
125017        || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
125018   );
125019   isScan = (idxNum!=FTS4AUX_EQ_CONSTRAINT);
125020
125021   /* In case this cursor is being reused, close and zero it. */
125022   testcase(pCsr->filter.zTerm);
125023   sqlite3Fts3SegReaderFinish(&pCsr->csr);
125024   sqlite3_free((void *)pCsr->filter.zTerm);
125025   sqlite3_free(pCsr->aStat);
125026   memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
125027
125028   pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
125029   if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
125030
125031   if( idxNum&(FTS4AUX_EQ_CONSTRAINT|FTS4AUX_GE_CONSTRAINT) ){
125032     const unsigned char *zStr = sqlite3_value_text(apVal[0]);
125033     if( zStr ){
125034       pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
125035       pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
125036       if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
125037     }
125038   }
125039   if( idxNum&FTS4AUX_LE_CONSTRAINT ){
125040     int iIdx = (idxNum&FTS4AUX_GE_CONSTRAINT) ? 1 : 0;
125041     pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iIdx]));
125042     pCsr->nStop = sqlite3_value_bytes(apVal[iIdx]);
125043     if( pCsr->zStop==0 ) return SQLITE_NOMEM;
125044   }
125045
125046   rc = sqlite3Fts3SegReaderCursor(pFts3, 0, 0, FTS3_SEGCURSOR_ALL,
125047       pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
125048   );
125049   if( rc==SQLITE_OK ){
125050     rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
125051   }
125052
125053   if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
125054   return rc;
125055 }
125056
125057 /*
125058 ** xEof - Return true if the cursor is at EOF, or false otherwise.
125059 */
125060 static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
125061   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
125062   return pCsr->isEof;
125063 }
125064
125065 /*
125066 ** xColumn - Return a column value.
125067 */
125068 static int fts3auxColumnMethod(
125069   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
125070   sqlite3_context *pContext,      /* Context for sqlite3_result_xxx() calls */
125071   int iCol                        /* Index of column to read value from */
125072 ){
125073   Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
125074
125075   assert( p->isEof==0 );
125076   if( iCol==0 ){        /* Column "term" */
125077     sqlite3_result_text(pContext, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
125078   }else if( iCol==1 ){  /* Column "col" */
125079     if( p->iCol ){
125080       sqlite3_result_int(pContext, p->iCol-1);
125081     }else{
125082       sqlite3_result_text(pContext, "*", -1, SQLITE_STATIC);
125083     }
125084   }else if( iCol==2 ){  /* Column "documents" */
125085     sqlite3_result_int64(pContext, p->aStat[p->iCol].nDoc);
125086   }else{                /* Column "occurrences" */
125087     sqlite3_result_int64(pContext, p->aStat[p->iCol].nOcc);
125088   }
125089
125090   return SQLITE_OK;
125091 }
125092
125093 /*
125094 ** xRowid - Return the current rowid for the cursor.
125095 */
125096 static int fts3auxRowidMethod(
125097   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
125098   sqlite_int64 *pRowid            /* OUT: Rowid value */
125099 ){
125100   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
125101   *pRowid = pCsr->iRowid;
125102   return SQLITE_OK;
125103 }
125104
125105 /*
125106 ** Register the fts3aux module with database connection db. Return SQLITE_OK
125107 ** if successful or an error code if sqlite3_create_module() fails.
125108 */
125109 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
125110   static const sqlite3_module fts3aux_module = {
125111      0,                           /* iVersion      */
125112      fts3auxConnectMethod,        /* xCreate       */
125113      fts3auxConnectMethod,        /* xConnect      */
125114      fts3auxBestIndexMethod,      /* xBestIndex    */
125115      fts3auxDisconnectMethod,     /* xDisconnect   */
125116      fts3auxDisconnectMethod,     /* xDestroy      */
125117      fts3auxOpenMethod,           /* xOpen         */
125118      fts3auxCloseMethod,          /* xClose        */
125119      fts3auxFilterMethod,         /* xFilter       */
125120      fts3auxNextMethod,           /* xNext         */
125121      fts3auxEofMethod,            /* xEof          */
125122      fts3auxColumnMethod,         /* xColumn       */
125123      fts3auxRowidMethod,          /* xRowid        */
125124      0,                           /* xUpdate       */
125125      0,                           /* xBegin        */
125126      0,                           /* xSync         */
125127      0,                           /* xCommit       */
125128      0,                           /* xRollback     */
125129      0,                           /* xFindFunction */
125130      0,                           /* xRename       */
125131      0,                           /* xSavepoint    */
125132      0,                           /* xRelease      */
125133      0                            /* xRollbackTo   */
125134   };
125135   int rc;                         /* Return code */
125136
125137   rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
125138   return rc;
125139 }
125140
125141 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
125142
125143 /************** End of fts3_aux.c ********************************************/
125144 /************** Begin file fts3_expr.c ***************************************/
125145 /*
125146 ** 2008 Nov 28
125147 **
125148 ** The author disclaims copyright to this source code.  In place of
125149 ** a legal notice, here is a blessing:
125150 **
125151 **    May you do good and not evil.
125152 **    May you find forgiveness for yourself and forgive others.
125153 **    May you share freely, never taking more than you give.
125154 **
125155 ******************************************************************************
125156 **
125157 ** This module contains code that implements a parser for fts3 query strings
125158 ** (the right-hand argument to the MATCH operator). Because the supported 
125159 ** syntax is relatively simple, the whole tokenizer/parser system is
125160 ** hand-coded. 
125161 */
125162 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
125163
125164 /*
125165 ** By default, this module parses the legacy syntax that has been 
125166 ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
125167 ** is defined, then it uses the new syntax. The differences between
125168 ** the new and the old syntaxes are:
125169 **
125170 **  a) The new syntax supports parenthesis. The old does not.
125171 **
125172 **  b) The new syntax supports the AND and NOT operators. The old does not.
125173 **
125174 **  c) The old syntax supports the "-" token qualifier. This is not 
125175 **     supported by the new syntax (it is replaced by the NOT operator).
125176 **
125177 **  d) When using the old syntax, the OR operator has a greater precedence
125178 **     than an implicit AND. When using the new, both implicity and explicit
125179 **     AND operators have a higher precedence than OR.
125180 **
125181 ** If compiled with SQLITE_TEST defined, then this module exports the
125182 ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
125183 ** to zero causes the module to use the old syntax. If it is set to 
125184 ** non-zero the new syntax is activated. This is so both syntaxes can
125185 ** be tested using a single build of testfixture.
125186 **
125187 ** The following describes the syntax supported by the fts3 MATCH
125188 ** operator in a similar format to that used by the lemon parser
125189 ** generator. This module does not use actually lemon, it uses a
125190 ** custom parser.
125191 **
125192 **   query ::= andexpr (OR andexpr)*.
125193 **
125194 **   andexpr ::= notexpr (AND? notexpr)*.
125195 **
125196 **   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
125197 **   notexpr ::= LP query RP.
125198 **
125199 **   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
125200 **
125201 **   distance_opt ::= .
125202 **   distance_opt ::= / INTEGER.
125203 **
125204 **   phrase ::= TOKEN.
125205 **   phrase ::= COLUMN:TOKEN.
125206 **   phrase ::= "TOKEN TOKEN TOKEN...".
125207 */
125208
125209 #ifdef SQLITE_TEST
125210 SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
125211 #else
125212 # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS 
125213 #  define sqlite3_fts3_enable_parentheses 1
125214 # else
125215 #  define sqlite3_fts3_enable_parentheses 0
125216 # endif
125217 #endif
125218
125219 /*
125220 ** Default span for NEAR operators.
125221 */
125222 #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
125223
125224 /* #include <string.h> */
125225 /* #include <assert.h> */
125226
125227 /*
125228 ** isNot:
125229 **   This variable is used by function getNextNode(). When getNextNode() is
125230 **   called, it sets ParseContext.isNot to true if the 'next node' is a 
125231 **   FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
125232 **   FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
125233 **   zero.
125234 */
125235 typedef struct ParseContext ParseContext;
125236 struct ParseContext {
125237   sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */
125238   int iLangid;                        /* Language id used with tokenizer */
125239   const char **azCol;                 /* Array of column names for fts3 table */
125240   int bFts4;                          /* True to allow FTS4-only syntax */
125241   int nCol;                           /* Number of entries in azCol[] */
125242   int iDefaultCol;                    /* Default column to query */
125243   int isNot;                          /* True if getNextNode() sees a unary - */
125244   sqlite3_context *pCtx;              /* Write error message here */
125245   int nNest;                          /* Number of nested brackets */
125246 };
125247
125248 /*
125249 ** This function is equivalent to the standard isspace() function. 
125250 **
125251 ** The standard isspace() can be awkward to use safely, because although it
125252 ** is defined to accept an argument of type int, its behavior when passed
125253 ** an integer that falls outside of the range of the unsigned char type
125254 ** is undefined (and sometimes, "undefined" means segfault). This wrapper
125255 ** is defined to accept an argument of type char, and always returns 0 for
125256 ** any values that fall outside of the range of the unsigned char type (i.e.
125257 ** negative values).
125258 */
125259 static int fts3isspace(char c){
125260   return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
125261 }
125262
125263 /*
125264 ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
125265 ** zero the memory before returning a pointer to it. If unsuccessful, 
125266 ** return NULL.
125267 */
125268 static void *fts3MallocZero(int nByte){
125269   void *pRet = sqlite3_malloc(nByte);
125270   if( pRet ) memset(pRet, 0, nByte);
125271   return pRet;
125272 }
125273
125274 SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
125275   sqlite3_tokenizer *pTokenizer,
125276   int iLangid,
125277   const char *z,
125278   int n,
125279   sqlite3_tokenizer_cursor **ppCsr
125280 ){
125281   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
125282   sqlite3_tokenizer_cursor *pCsr = 0;
125283   int rc;
125284
125285   rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
125286   assert( rc==SQLITE_OK || pCsr==0 );
125287   if( rc==SQLITE_OK ){
125288     pCsr->pTokenizer = pTokenizer;
125289     if( pModule->iVersion>=1 ){
125290       rc = pModule->xLanguageid(pCsr, iLangid);
125291       if( rc!=SQLITE_OK ){
125292         pModule->xClose(pCsr);
125293         pCsr = 0;
125294       }
125295     }
125296   }
125297   *ppCsr = pCsr;
125298   return rc;
125299 }
125300
125301
125302 /*
125303 ** Extract the next token from buffer z (length n) using the tokenizer
125304 ** and other information (column names etc.) in pParse. Create an Fts3Expr
125305 ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
125306 ** single token and set *ppExpr to point to it. If the end of the buffer is
125307 ** reached before a token is found, set *ppExpr to zero. It is the
125308 ** responsibility of the caller to eventually deallocate the allocated 
125309 ** Fts3Expr structure (if any) by passing it to sqlite3_free().
125310 **
125311 ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
125312 ** fails.
125313 */
125314 static int getNextToken(
125315   ParseContext *pParse,                   /* fts3 query parse context */
125316   int iCol,                               /* Value for Fts3Phrase.iColumn */
125317   const char *z, int n,                   /* Input string */
125318   Fts3Expr **ppExpr,                      /* OUT: expression */
125319   int *pnConsumed                         /* OUT: Number of bytes consumed */
125320 ){
125321   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
125322   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
125323   int rc;
125324   sqlite3_tokenizer_cursor *pCursor;
125325   Fts3Expr *pRet = 0;
125326   int nConsumed = 0;
125327
125328   rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, n, &pCursor);
125329   if( rc==SQLITE_OK ){
125330     const char *zToken;
125331     int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
125332     int nByte;                               /* total space to allocate */
125333
125334     rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
125335     if( rc==SQLITE_OK ){
125336       nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
125337       pRet = (Fts3Expr *)fts3MallocZero(nByte);
125338       if( !pRet ){
125339         rc = SQLITE_NOMEM;
125340       }else{
125341         pRet->eType = FTSQUERY_PHRASE;
125342         pRet->pPhrase = (Fts3Phrase *)&pRet[1];
125343         pRet->pPhrase->nToken = 1;
125344         pRet->pPhrase->iColumn = iCol;
125345         pRet->pPhrase->aToken[0].n = nToken;
125346         pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
125347         memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
125348
125349         if( iEnd<n && z[iEnd]=='*' ){
125350           pRet->pPhrase->aToken[0].isPrefix = 1;
125351           iEnd++;
125352         }
125353
125354         while( 1 ){
125355           if( !sqlite3_fts3_enable_parentheses 
125356            && iStart>0 && z[iStart-1]=='-' 
125357           ){
125358             pParse->isNot = 1;
125359             iStart--;
125360           }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
125361             pRet->pPhrase->aToken[0].bFirst = 1;
125362             iStart--;
125363           }else{
125364             break;
125365           }
125366         }
125367
125368       }
125369       nConsumed = iEnd;
125370     }
125371
125372     pModule->xClose(pCursor);
125373   }
125374   
125375   *pnConsumed = nConsumed;
125376   *ppExpr = pRet;
125377   return rc;
125378 }
125379
125380
125381 /*
125382 ** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
125383 ** then free the old allocation.
125384 */
125385 static void *fts3ReallocOrFree(void *pOrig, int nNew){
125386   void *pRet = sqlite3_realloc(pOrig, nNew);
125387   if( !pRet ){
125388     sqlite3_free(pOrig);
125389   }
125390   return pRet;
125391 }
125392
125393 /*
125394 ** Buffer zInput, length nInput, contains the contents of a quoted string
125395 ** that appeared as part of an fts3 query expression. Neither quote character
125396 ** is included in the buffer. This function attempts to tokenize the entire
125397 ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE 
125398 ** containing the results.
125399 **
125400 ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
125401 ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
125402 ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
125403 ** to 0.
125404 */
125405 static int getNextString(
125406   ParseContext *pParse,                   /* fts3 query parse context */
125407   const char *zInput, int nInput,         /* Input string */
125408   Fts3Expr **ppExpr                       /* OUT: expression */
125409 ){
125410   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
125411   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
125412   int rc;
125413   Fts3Expr *p = 0;
125414   sqlite3_tokenizer_cursor *pCursor = 0;
125415   char *zTemp = 0;
125416   int nTemp = 0;
125417
125418   const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
125419   int nToken = 0;
125420
125421   /* The final Fts3Expr data structure, including the Fts3Phrase,
125422   ** Fts3PhraseToken structures token buffers are all stored as a single 
125423   ** allocation so that the expression can be freed with a single call to
125424   ** sqlite3_free(). Setting this up requires a two pass approach.
125425   **
125426   ** The first pass, in the block below, uses a tokenizer cursor to iterate
125427   ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
125428   ** to assemble data in two dynamic buffers:
125429   **
125430   **   Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
125431   **             structure, followed by the array of Fts3PhraseToken 
125432   **             structures. This pass only populates the Fts3PhraseToken array.
125433   **
125434   **   Buffer zTemp: Contains copies of all tokens.
125435   **
125436   ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
125437   ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
125438   ** structures.
125439   */
125440   rc = sqlite3Fts3OpenTokenizer(
125441       pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
125442   if( rc==SQLITE_OK ){
125443     int ii;
125444     for(ii=0; rc==SQLITE_OK; ii++){
125445       const char *zByte;
125446       int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
125447       rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
125448       if( rc==SQLITE_OK ){
125449         Fts3PhraseToken *pToken;
125450
125451         p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
125452         if( !p ) goto no_mem;
125453
125454         zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
125455         if( !zTemp ) goto no_mem;
125456
125457         assert( nToken==ii );
125458         pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
125459         memset(pToken, 0, sizeof(Fts3PhraseToken));
125460
125461         memcpy(&zTemp[nTemp], zByte, nByte);
125462         nTemp += nByte;
125463
125464         pToken->n = nByte;
125465         pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
125466         pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
125467         nToken = ii+1;
125468       }
125469     }
125470
125471     pModule->xClose(pCursor);
125472     pCursor = 0;
125473   }
125474
125475   if( rc==SQLITE_DONE ){
125476     int jj;
125477     char *zBuf = 0;
125478
125479     p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
125480     if( !p ) goto no_mem;
125481     memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
125482     p->eType = FTSQUERY_PHRASE;
125483     p->pPhrase = (Fts3Phrase *)&p[1];
125484     p->pPhrase->iColumn = pParse->iDefaultCol;
125485     p->pPhrase->nToken = nToken;
125486
125487     zBuf = (char *)&p->pPhrase->aToken[nToken];
125488     if( zTemp ){
125489       memcpy(zBuf, zTemp, nTemp);
125490       sqlite3_free(zTemp);
125491     }else{
125492       assert( nTemp==0 );
125493     }
125494
125495     for(jj=0; jj<p->pPhrase->nToken; jj++){
125496       p->pPhrase->aToken[jj].z = zBuf;
125497       zBuf += p->pPhrase->aToken[jj].n;
125498     }
125499     rc = SQLITE_OK;
125500   }
125501
125502   *ppExpr = p;
125503   return rc;
125504 no_mem:
125505
125506   if( pCursor ){
125507     pModule->xClose(pCursor);
125508   }
125509   sqlite3_free(zTemp);
125510   sqlite3_free(p);
125511   *ppExpr = 0;
125512   return SQLITE_NOMEM;
125513 }
125514
125515 /*
125516 ** Function getNextNode(), which is called by fts3ExprParse(), may itself
125517 ** call fts3ExprParse(). So this forward declaration is required.
125518 */
125519 static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
125520
125521 /*
125522 ** The output variable *ppExpr is populated with an allocated Fts3Expr 
125523 ** structure, or set to 0 if the end of the input buffer is reached.
125524 **
125525 ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
125526 ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
125527 ** If SQLITE_ERROR is returned, pContext is populated with an error message.
125528 */
125529 static int getNextNode(
125530   ParseContext *pParse,                   /* fts3 query parse context */
125531   const char *z, int n,                   /* Input string */
125532   Fts3Expr **ppExpr,                      /* OUT: expression */
125533   int *pnConsumed                         /* OUT: Number of bytes consumed */
125534 ){
125535   static const struct Fts3Keyword {
125536     char *z;                              /* Keyword text */
125537     unsigned char n;                      /* Length of the keyword */
125538     unsigned char parenOnly;              /* Only valid in paren mode */
125539     unsigned char eType;                  /* Keyword code */
125540   } aKeyword[] = {
125541     { "OR" ,  2, 0, FTSQUERY_OR   },
125542     { "AND",  3, 1, FTSQUERY_AND  },
125543     { "NOT",  3, 1, FTSQUERY_NOT  },
125544     { "NEAR", 4, 0, FTSQUERY_NEAR }
125545   };
125546   int ii;
125547   int iCol;
125548   int iColLen;
125549   int rc;
125550   Fts3Expr *pRet = 0;
125551
125552   const char *zInput = z;
125553   int nInput = n;
125554
125555   pParse->isNot = 0;
125556
125557   /* Skip over any whitespace before checking for a keyword, an open or
125558   ** close bracket, or a quoted string. 
125559   */
125560   while( nInput>0 && fts3isspace(*zInput) ){
125561     nInput--;
125562     zInput++;
125563   }
125564   if( nInput==0 ){
125565     return SQLITE_DONE;
125566   }
125567
125568   /* See if we are dealing with a keyword. */
125569   for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
125570     const struct Fts3Keyword *pKey = &aKeyword[ii];
125571
125572     if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
125573       continue;
125574     }
125575
125576     if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
125577       int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
125578       int nKey = pKey->n;
125579       char cNext;
125580
125581       /* If this is a "NEAR" keyword, check for an explicit nearness. */
125582       if( pKey->eType==FTSQUERY_NEAR ){
125583         assert( nKey==4 );
125584         if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
125585           nNear = 0;
125586           for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
125587             nNear = nNear * 10 + (zInput[nKey] - '0');
125588           }
125589         }
125590       }
125591
125592       /* At this point this is probably a keyword. But for that to be true,
125593       ** the next byte must contain either whitespace, an open or close
125594       ** parenthesis, a quote character, or EOF. 
125595       */
125596       cNext = zInput[nKey];
125597       if( fts3isspace(cNext) 
125598        || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
125599       ){
125600         pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
125601         if( !pRet ){
125602           return SQLITE_NOMEM;
125603         }
125604         pRet->eType = pKey->eType;
125605         pRet->nNear = nNear;
125606         *ppExpr = pRet;
125607         *pnConsumed = (int)((zInput - z) + nKey);
125608         return SQLITE_OK;
125609       }
125610
125611       /* Turns out that wasn't a keyword after all. This happens if the
125612       ** user has supplied a token such as "ORacle". Continue.
125613       */
125614     }
125615   }
125616
125617   /* Check for an open bracket. */
125618   if( sqlite3_fts3_enable_parentheses ){
125619     if( *zInput=='(' ){
125620       int nConsumed;
125621       pParse->nNest++;
125622       rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed);
125623       if( rc==SQLITE_OK && !*ppExpr ){
125624         rc = SQLITE_DONE;
125625       }
125626       *pnConsumed = (int)((zInput - z) + 1 + nConsumed);
125627       return rc;
125628     }
125629   
125630     /* Check for a close bracket. */
125631     if( *zInput==')' ){
125632       pParse->nNest--;
125633       *pnConsumed = (int)((zInput - z) + 1);
125634       return SQLITE_DONE;
125635     }
125636   }
125637
125638   /* See if we are dealing with a quoted phrase. If this is the case, then
125639   ** search for the closing quote and pass the whole string to getNextString()
125640   ** for processing. This is easy to do, as fts3 has no syntax for escaping
125641   ** a quote character embedded in a string.
125642   */
125643   if( *zInput=='"' ){
125644     for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
125645     *pnConsumed = (int)((zInput - z) + ii + 1);
125646     if( ii==nInput ){
125647       return SQLITE_ERROR;
125648     }
125649     return getNextString(pParse, &zInput[1], ii-1, ppExpr);
125650   }
125651
125652
125653   /* If control flows to this point, this must be a regular token, or 
125654   ** the end of the input. Read a regular token using the sqlite3_tokenizer
125655   ** interface. Before doing so, figure out if there is an explicit
125656   ** column specifier for the token. 
125657   **
125658   ** TODO: Strangely, it is not possible to associate a column specifier
125659   ** with a quoted phrase, only with a single token. Not sure if this was
125660   ** an implementation artifact or an intentional decision when fts3 was
125661   ** first implemented. Whichever it was, this module duplicates the 
125662   ** limitation.
125663   */
125664   iCol = pParse->iDefaultCol;
125665   iColLen = 0;
125666   for(ii=0; ii<pParse->nCol; ii++){
125667     const char *zStr = pParse->azCol[ii];
125668     int nStr = (int)strlen(zStr);
125669     if( nInput>nStr && zInput[nStr]==':' 
125670      && sqlite3_strnicmp(zStr, zInput, nStr)==0 
125671     ){
125672       iCol = ii;
125673       iColLen = (int)((zInput - z) + nStr + 1);
125674       break;
125675     }
125676   }
125677   rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
125678   *pnConsumed += iColLen;
125679   return rc;
125680 }
125681
125682 /*
125683 ** The argument is an Fts3Expr structure for a binary operator (any type
125684 ** except an FTSQUERY_PHRASE). Return an integer value representing the
125685 ** precedence of the operator. Lower values have a higher precedence (i.e.
125686 ** group more tightly). For example, in the C language, the == operator
125687 ** groups more tightly than ||, and would therefore have a higher precedence.
125688 **
125689 ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
125690 ** is defined), the order of the operators in precedence from highest to
125691 ** lowest is:
125692 **
125693 **   NEAR
125694 **   NOT
125695 **   AND (including implicit ANDs)
125696 **   OR
125697 **
125698 ** Note that when using the old query syntax, the OR operator has a higher
125699 ** precedence than the AND operator.
125700 */
125701 static int opPrecedence(Fts3Expr *p){
125702   assert( p->eType!=FTSQUERY_PHRASE );
125703   if( sqlite3_fts3_enable_parentheses ){
125704     return p->eType;
125705   }else if( p->eType==FTSQUERY_NEAR ){
125706     return 1;
125707   }else if( p->eType==FTSQUERY_OR ){
125708     return 2;
125709   }
125710   assert( p->eType==FTSQUERY_AND );
125711   return 3;
125712 }
125713
125714 /*
125715 ** Argument ppHead contains a pointer to the current head of a query 
125716 ** expression tree being parsed. pPrev is the expression node most recently
125717 ** inserted into the tree. This function adds pNew, which is always a binary
125718 ** operator node, into the expression tree based on the relative precedence
125719 ** of pNew and the existing nodes of the tree. This may result in the head
125720 ** of the tree changing, in which case *ppHead is set to the new root node.
125721 */
125722 static void insertBinaryOperator(
125723   Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
125724   Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
125725   Fts3Expr *pNew           /* New binary node to insert into expression tree */
125726 ){
125727   Fts3Expr *pSplit = pPrev;
125728   while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
125729     pSplit = pSplit->pParent;
125730   }
125731
125732   if( pSplit->pParent ){
125733     assert( pSplit->pParent->pRight==pSplit );
125734     pSplit->pParent->pRight = pNew;
125735     pNew->pParent = pSplit->pParent;
125736   }else{
125737     *ppHead = pNew;
125738   }
125739   pNew->pLeft = pSplit;
125740   pSplit->pParent = pNew;
125741 }
125742
125743 /*
125744 ** Parse the fts3 query expression found in buffer z, length n. This function
125745 ** returns either when the end of the buffer is reached or an unmatched 
125746 ** closing bracket - ')' - is encountered.
125747 **
125748 ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
125749 ** parsed form of the expression and *pnConsumed is set to the number of
125750 ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
125751 ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
125752 */
125753 static int fts3ExprParse(
125754   ParseContext *pParse,                   /* fts3 query parse context */
125755   const char *z, int n,                   /* Text of MATCH query */
125756   Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
125757   int *pnConsumed                         /* OUT: Number of bytes consumed */
125758 ){
125759   Fts3Expr *pRet = 0;
125760   Fts3Expr *pPrev = 0;
125761   Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
125762   int nIn = n;
125763   const char *zIn = z;
125764   int rc = SQLITE_OK;
125765   int isRequirePhrase = 1;
125766
125767   while( rc==SQLITE_OK ){
125768     Fts3Expr *p = 0;
125769     int nByte = 0;
125770     rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
125771     if( rc==SQLITE_OK ){
125772       int isPhrase;
125773
125774       if( !sqlite3_fts3_enable_parentheses 
125775        && p->eType==FTSQUERY_PHRASE && pParse->isNot 
125776       ){
125777         /* Create an implicit NOT operator. */
125778         Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
125779         if( !pNot ){
125780           sqlite3Fts3ExprFree(p);
125781           rc = SQLITE_NOMEM;
125782           goto exprparse_out;
125783         }
125784         pNot->eType = FTSQUERY_NOT;
125785         pNot->pRight = p;
125786         p->pParent = pNot;
125787         if( pNotBranch ){
125788           pNot->pLeft = pNotBranch;
125789           pNotBranch->pParent = pNot;
125790         }
125791         pNotBranch = pNot;
125792         p = pPrev;
125793       }else{
125794         int eType = p->eType;
125795         isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
125796
125797         /* The isRequirePhrase variable is set to true if a phrase or
125798         ** an expression contained in parenthesis is required. If a
125799         ** binary operator (AND, OR, NOT or NEAR) is encounted when
125800         ** isRequirePhrase is set, this is a syntax error.
125801         */
125802         if( !isPhrase && isRequirePhrase ){
125803           sqlite3Fts3ExprFree(p);
125804           rc = SQLITE_ERROR;
125805           goto exprparse_out;
125806         }
125807   
125808         if( isPhrase && !isRequirePhrase ){
125809           /* Insert an implicit AND operator. */
125810           Fts3Expr *pAnd;
125811           assert( pRet && pPrev );
125812           pAnd = fts3MallocZero(sizeof(Fts3Expr));
125813           if( !pAnd ){
125814             sqlite3Fts3ExprFree(p);
125815             rc = SQLITE_NOMEM;
125816             goto exprparse_out;
125817           }
125818           pAnd->eType = FTSQUERY_AND;
125819           insertBinaryOperator(&pRet, pPrev, pAnd);
125820           pPrev = pAnd;
125821         }
125822
125823         /* This test catches attempts to make either operand of a NEAR
125824         ** operator something other than a phrase. For example, either of
125825         ** the following:
125826         **
125827         **    (bracketed expression) NEAR phrase
125828         **    phrase NEAR (bracketed expression)
125829         **
125830         ** Return an error in either case.
125831         */
125832         if( pPrev && (
125833             (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
125834          || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
125835         )){
125836           sqlite3Fts3ExprFree(p);
125837           rc = SQLITE_ERROR;
125838           goto exprparse_out;
125839         }
125840   
125841         if( isPhrase ){
125842           if( pRet ){
125843             assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
125844             pPrev->pRight = p;
125845             p->pParent = pPrev;
125846           }else{
125847             pRet = p;
125848           }
125849         }else{
125850           insertBinaryOperator(&pRet, pPrev, p);
125851         }
125852         isRequirePhrase = !isPhrase;
125853       }
125854       assert( nByte>0 );
125855     }
125856     assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
125857     nIn -= nByte;
125858     zIn += nByte;
125859     pPrev = p;
125860   }
125861
125862   if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
125863     rc = SQLITE_ERROR;
125864   }
125865
125866   if( rc==SQLITE_DONE ){
125867     rc = SQLITE_OK;
125868     if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
125869       if( !pRet ){
125870         rc = SQLITE_ERROR;
125871       }else{
125872         Fts3Expr *pIter = pNotBranch;
125873         while( pIter->pLeft ){
125874           pIter = pIter->pLeft;
125875         }
125876         pIter->pLeft = pRet;
125877         pRet->pParent = pIter;
125878         pRet = pNotBranch;
125879       }
125880     }
125881   }
125882   *pnConsumed = n - nIn;
125883
125884 exprparse_out:
125885   if( rc!=SQLITE_OK ){
125886     sqlite3Fts3ExprFree(pRet);
125887     sqlite3Fts3ExprFree(pNotBranch);
125888     pRet = 0;
125889   }
125890   *ppExpr = pRet;
125891   return rc;
125892 }
125893
125894 /*
125895 ** Return SQLITE_ERROR if the maximum depth of the expression tree passed 
125896 ** as the only argument is more than nMaxDepth.
125897 */
125898 static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
125899   int rc = SQLITE_OK;
125900   if( p ){
125901     if( nMaxDepth<0 ){ 
125902       rc = SQLITE_TOOBIG;
125903     }else{
125904       rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);
125905       if( rc==SQLITE_OK ){
125906         rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1);
125907       }
125908     }
125909   }
125910   return rc;
125911 }
125912
125913 /*
125914 ** This function attempts to transform the expression tree at (*pp) to
125915 ** an equivalent but more balanced form. The tree is modified in place.
125916 ** If successful, SQLITE_OK is returned and (*pp) set to point to the 
125917 ** new root expression node. 
125918 **
125919 ** nMaxDepth is the maximum allowable depth of the balanced sub-tree.
125920 **
125921 ** Otherwise, if an error occurs, an SQLite error code is returned and 
125922 ** expression (*pp) freed.
125923 */
125924 static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
125925   int rc = SQLITE_OK;             /* Return code */
125926   Fts3Expr *pRoot = *pp;          /* Initial root node */
125927   Fts3Expr *pFree = 0;            /* List of free nodes. Linked by pParent. */
125928   int eType = pRoot->eType;       /* Type of node in this tree */
125929
125930   if( nMaxDepth==0 ){
125931     rc = SQLITE_ERROR;
125932   }
125933
125934   if( rc==SQLITE_OK && (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){
125935     Fts3Expr **apLeaf;
125936     apLeaf = (Fts3Expr **)sqlite3_malloc(sizeof(Fts3Expr *) * nMaxDepth);
125937     if( 0==apLeaf ){
125938       rc = SQLITE_NOMEM;
125939     }else{
125940       memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth);
125941     }
125942
125943     if( rc==SQLITE_OK ){
125944       int i;
125945       Fts3Expr *p;
125946
125947       /* Set $p to point to the left-most leaf in the tree of eType nodes. */
125948       for(p=pRoot; p->eType==eType; p=p->pLeft){
125949         assert( p->pParent==0 || p->pParent->pLeft==p );
125950         assert( p->pLeft && p->pRight );
125951       }
125952
125953       /* This loop runs once for each leaf in the tree of eType nodes. */
125954       while( 1 ){
125955         int iLvl;
125956         Fts3Expr *pParent = p->pParent;     /* Current parent of p */
125957
125958         assert( pParent==0 || pParent->pLeft==p );
125959         p->pParent = 0;
125960         if( pParent ){
125961           pParent->pLeft = 0;
125962         }else{
125963           pRoot = 0;
125964         }
125965         rc = fts3ExprBalance(&p, nMaxDepth-1);
125966         if( rc!=SQLITE_OK ) break;
125967
125968         for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){
125969           if( apLeaf[iLvl]==0 ){
125970             apLeaf[iLvl] = p;
125971             p = 0;
125972           }else{
125973             assert( pFree );
125974             pFree->pLeft = apLeaf[iLvl];
125975             pFree->pRight = p;
125976             pFree->pLeft->pParent = pFree;
125977             pFree->pRight->pParent = pFree;
125978
125979             p = pFree;
125980             pFree = pFree->pParent;
125981             p->pParent = 0;
125982             apLeaf[iLvl] = 0;
125983           }
125984         }
125985         if( p ){
125986           sqlite3Fts3ExprFree(p);
125987           rc = SQLITE_TOOBIG;
125988           break;
125989         }
125990
125991         /* If that was the last leaf node, break out of the loop */
125992         if( pParent==0 ) break;
125993
125994         /* Set $p to point to the next leaf in the tree of eType nodes */
125995         for(p=pParent->pRight; p->eType==eType; p=p->pLeft);
125996
125997         /* Remove pParent from the original tree. */
125998         assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent );
125999         pParent->pRight->pParent = pParent->pParent;
126000         if( pParent->pParent ){
126001           pParent->pParent->pLeft = pParent->pRight;
126002         }else{
126003           assert( pParent==pRoot );
126004           pRoot = pParent->pRight;
126005         }
126006
126007         /* Link pParent into the free node list. It will be used as an
126008         ** internal node of the new tree.  */
126009         pParent->pParent = pFree;
126010         pFree = pParent;
126011       }
126012
126013       if( rc==SQLITE_OK ){
126014         p = 0;
126015         for(i=0; i<nMaxDepth; i++){
126016           if( apLeaf[i] ){
126017             if( p==0 ){
126018               p = apLeaf[i];
126019               p->pParent = 0;
126020             }else{
126021               assert( pFree!=0 );
126022               pFree->pRight = p;
126023               pFree->pLeft = apLeaf[i];
126024               pFree->pLeft->pParent = pFree;
126025               pFree->pRight->pParent = pFree;
126026
126027               p = pFree;
126028               pFree = pFree->pParent;
126029               p->pParent = 0;
126030             }
126031           }
126032         }
126033         pRoot = p;
126034       }else{
126035         /* An error occurred. Delete the contents of the apLeaf[] array 
126036         ** and pFree list. Everything else is cleaned up by the call to
126037         ** sqlite3Fts3ExprFree(pRoot) below.  */
126038         Fts3Expr *pDel;
126039         for(i=0; i<nMaxDepth; i++){
126040           sqlite3Fts3ExprFree(apLeaf[i]);
126041         }
126042         while( (pDel=pFree)!=0 ){
126043           pFree = pDel->pParent;
126044           sqlite3_free(pDel);
126045         }
126046       }
126047
126048       assert( pFree==0 );
126049       sqlite3_free( apLeaf );
126050     }
126051   }
126052
126053   if( rc!=SQLITE_OK ){
126054     sqlite3Fts3ExprFree(pRoot);
126055     pRoot = 0;
126056   }
126057   *pp = pRoot;
126058   return rc;
126059 }
126060
126061 /*
126062 ** This function is similar to sqlite3Fts3ExprParse(), with the following
126063 ** differences:
126064 **
126065 **   1. It does not do expression rebalancing.
126066 **   2. It does not check that the expression does not exceed the 
126067 **      maximum allowable depth.
126068 **   3. Even if it fails, *ppExpr may still be set to point to an 
126069 **      expression tree. It should be deleted using sqlite3Fts3ExprFree()
126070 **      in this case.
126071 */
126072 static int fts3ExprParseUnbalanced(
126073   sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
126074   int iLangid,                        /* Language id for tokenizer */
126075   char **azCol,                       /* Array of column names for fts3 table */
126076   int bFts4,                          /* True to allow FTS4-only syntax */
126077   int nCol,                           /* Number of entries in azCol[] */
126078   int iDefaultCol,                    /* Default column to query */
126079   const char *z, int n,               /* Text of MATCH query */
126080   Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
126081 ){
126082   int nParsed;
126083   int rc;
126084   ParseContext sParse;
126085
126086   memset(&sParse, 0, sizeof(ParseContext));
126087   sParse.pTokenizer = pTokenizer;
126088   sParse.iLangid = iLangid;
126089   sParse.azCol = (const char **)azCol;
126090   sParse.nCol = nCol;
126091   sParse.iDefaultCol = iDefaultCol;
126092   sParse.bFts4 = bFts4;
126093   if( z==0 ){
126094     *ppExpr = 0;
126095     return SQLITE_OK;
126096   }
126097   if( n<0 ){
126098     n = (int)strlen(z);
126099   }
126100   rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
126101   assert( rc==SQLITE_OK || *ppExpr==0 );
126102
126103   /* Check for mismatched parenthesis */
126104   if( rc==SQLITE_OK && sParse.nNest ){
126105     rc = SQLITE_ERROR;
126106   }
126107   
126108   return rc;
126109 }
126110
126111 /*
126112 ** Parameters z and n contain a pointer to and length of a buffer containing
126113 ** an fts3 query expression, respectively. This function attempts to parse the
126114 ** query expression and create a tree of Fts3Expr structures representing the
126115 ** parsed expression. If successful, *ppExpr is set to point to the head
126116 ** of the parsed expression tree and SQLITE_OK is returned. If an error
126117 ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
126118 ** error) is returned and *ppExpr is set to 0.
126119 **
126120 ** If parameter n is a negative number, then z is assumed to point to a
126121 ** nul-terminated string and the length is determined using strlen().
126122 **
126123 ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
126124 ** use to normalize query tokens while parsing the expression. The azCol[]
126125 ** array, which is assumed to contain nCol entries, should contain the names
126126 ** of each column in the target fts3 table, in order from left to right. 
126127 ** Column names must be nul-terminated strings.
126128 **
126129 ** The iDefaultCol parameter should be passed the index of the table column
126130 ** that appears on the left-hand-side of the MATCH operator (the default
126131 ** column to match against for tokens for which a column name is not explicitly
126132 ** specified as part of the query string), or -1 if tokens may by default
126133 ** match any table column.
126134 */
126135 SQLITE_PRIVATE int sqlite3Fts3ExprParse(
126136   sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
126137   int iLangid,                        /* Language id for tokenizer */
126138   char **azCol,                       /* Array of column names for fts3 table */
126139   int bFts4,                          /* True to allow FTS4-only syntax */
126140   int nCol,                           /* Number of entries in azCol[] */
126141   int iDefaultCol,                    /* Default column to query */
126142   const char *z, int n,               /* Text of MATCH query */
126143   Fts3Expr **ppExpr,                  /* OUT: Parsed query structure */
126144   char **pzErr                        /* OUT: Error message (sqlite3_malloc) */
126145 ){
126146   static const int MAX_EXPR_DEPTH = 12;
126147   int rc = fts3ExprParseUnbalanced(
126148       pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
126149   );
126150   
126151   /* Rebalance the expression. And check that its depth does not exceed
126152   ** MAX_EXPR_DEPTH.  */
126153   if( rc==SQLITE_OK && *ppExpr ){
126154     rc = fts3ExprBalance(ppExpr, MAX_EXPR_DEPTH);
126155     if( rc==SQLITE_OK ){
126156       rc = fts3ExprCheckDepth(*ppExpr, MAX_EXPR_DEPTH);
126157     }
126158   }
126159
126160   if( rc!=SQLITE_OK ){
126161     sqlite3Fts3ExprFree(*ppExpr);
126162     *ppExpr = 0;
126163     if( rc==SQLITE_TOOBIG ){
126164       *pzErr = sqlite3_mprintf(
126165           "FTS expression tree is too large (maximum depth %d)", MAX_EXPR_DEPTH
126166       );
126167       rc = SQLITE_ERROR;
126168     }else if( rc==SQLITE_ERROR ){
126169       *pzErr = sqlite3_mprintf("malformed MATCH expression: [%s]", z);
126170     }
126171   }
126172
126173   return rc;
126174 }
126175
126176 /*
126177 ** Free a single node of an expression tree.
126178 */
126179 static void fts3FreeExprNode(Fts3Expr *p){
126180   assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
126181   sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
126182   sqlite3_free(p->aMI);
126183   sqlite3_free(p);
126184 }
126185
126186 /*
126187 ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
126188 **
126189 ** This function would be simpler if it recursively called itself. But
126190 ** that would mean passing a sufficiently large expression to ExprParse()
126191 ** could cause a stack overflow.
126192 */
126193 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){
126194   Fts3Expr *p;
126195   assert( pDel==0 || pDel->pParent==0 );
126196   for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){
126197     assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft );
126198   }
126199   while( p ){
126200     Fts3Expr *pParent = p->pParent;
126201     fts3FreeExprNode(p);
126202     if( pParent && p==pParent->pLeft && pParent->pRight ){
126203       p = pParent->pRight;
126204       while( p && (p->pLeft || p->pRight) ){
126205         assert( p==p->pParent->pRight || p==p->pParent->pLeft );
126206         p = (p->pLeft ? p->pLeft : p->pRight);
126207       }
126208     }else{
126209       p = pParent;
126210     }
126211   }
126212 }
126213
126214 /****************************************************************************
126215 *****************************************************************************
126216 ** Everything after this point is just test code.
126217 */
126218
126219 #ifdef SQLITE_TEST
126220
126221 /* #include <stdio.h> */
126222
126223 /*
126224 ** Function to query the hash-table of tokenizers (see README.tokenizers).
126225 */
126226 static int queryTestTokenizer(
126227   sqlite3 *db, 
126228   const char *zName,  
126229   const sqlite3_tokenizer_module **pp
126230 ){
126231   int rc;
126232   sqlite3_stmt *pStmt;
126233   const char zSql[] = "SELECT fts3_tokenizer(?)";
126234
126235   *pp = 0;
126236   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
126237   if( rc!=SQLITE_OK ){
126238     return rc;
126239   }
126240
126241   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
126242   if( SQLITE_ROW==sqlite3_step(pStmt) ){
126243     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
126244       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
126245     }
126246   }
126247
126248   return sqlite3_finalize(pStmt);
126249 }
126250
126251 /*
126252 ** Return a pointer to a buffer containing a text representation of the
126253 ** expression passed as the first argument. The buffer is obtained from
126254 ** sqlite3_malloc(). It is the responsibility of the caller to use 
126255 ** sqlite3_free() to release the memory. If an OOM condition is encountered,
126256 ** NULL is returned.
126257 **
126258 ** If the second argument is not NULL, then its contents are prepended to 
126259 ** the returned expression text and then freed using sqlite3_free().
126260 */
126261 static char *exprToString(Fts3Expr *pExpr, char *zBuf){
126262   if( pExpr==0 ){
126263     return sqlite3_mprintf("");
126264   }
126265   switch( pExpr->eType ){
126266     case FTSQUERY_PHRASE: {
126267       Fts3Phrase *pPhrase = pExpr->pPhrase;
126268       int i;
126269       zBuf = sqlite3_mprintf(
126270           "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
126271       for(i=0; zBuf && i<pPhrase->nToken; i++){
126272         zBuf = sqlite3_mprintf("%z %.*s%s", zBuf, 
126273             pPhrase->aToken[i].n, pPhrase->aToken[i].z,
126274             (pPhrase->aToken[i].isPrefix?"+":"")
126275         );
126276       }
126277       return zBuf;
126278     }
126279
126280     case FTSQUERY_NEAR:
126281       zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
126282       break;
126283     case FTSQUERY_NOT:
126284       zBuf = sqlite3_mprintf("%zNOT ", zBuf);
126285       break;
126286     case FTSQUERY_AND:
126287       zBuf = sqlite3_mprintf("%zAND ", zBuf);
126288       break;
126289     case FTSQUERY_OR:
126290       zBuf = sqlite3_mprintf("%zOR ", zBuf);
126291       break;
126292   }
126293
126294   if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
126295   if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
126296   if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
126297
126298   if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
126299   if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
126300
126301   return zBuf;
126302 }
126303
126304 /*
126305 ** This is the implementation of a scalar SQL function used to test the 
126306 ** expression parser. It should be called as follows:
126307 **
126308 **   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
126309 **
126310 ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
126311 ** to parse the query expression (see README.tokenizers). The second argument
126312 ** is the query expression to parse. Each subsequent argument is the name
126313 ** of a column of the fts3 table that the query expression may refer to.
126314 ** For example:
126315 **
126316 **   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
126317 */
126318 static void fts3ExprTest(
126319   sqlite3_context *context,
126320   int argc,
126321   sqlite3_value **argv
126322 ){
126323   sqlite3_tokenizer_module const *pModule = 0;
126324   sqlite3_tokenizer *pTokenizer = 0;
126325   int rc;
126326   char **azCol = 0;
126327   const char *zExpr;
126328   int nExpr;
126329   int nCol;
126330   int ii;
126331   Fts3Expr *pExpr;
126332   char *zBuf = 0;
126333   sqlite3 *db = sqlite3_context_db_handle(context);
126334
126335   if( argc<3 ){
126336     sqlite3_result_error(context, 
126337         "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
126338     );
126339     return;
126340   }
126341
126342   rc = queryTestTokenizer(db,
126343                           (const char *)sqlite3_value_text(argv[0]), &pModule);
126344   if( rc==SQLITE_NOMEM ){
126345     sqlite3_result_error_nomem(context);
126346     goto exprtest_out;
126347   }else if( !pModule ){
126348     sqlite3_result_error(context, "No such tokenizer module", -1);
126349     goto exprtest_out;
126350   }
126351
126352   rc = pModule->xCreate(0, 0, &pTokenizer);
126353   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
126354   if( rc==SQLITE_NOMEM ){
126355     sqlite3_result_error_nomem(context);
126356     goto exprtest_out;
126357   }
126358   pTokenizer->pModule = pModule;
126359
126360   zExpr = (const char *)sqlite3_value_text(argv[1]);
126361   nExpr = sqlite3_value_bytes(argv[1]);
126362   nCol = argc-2;
126363   azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
126364   if( !azCol ){
126365     sqlite3_result_error_nomem(context);
126366     goto exprtest_out;
126367   }
126368   for(ii=0; ii<nCol; ii++){
126369     azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
126370   }
126371
126372   if( sqlite3_user_data(context) ){
126373     char *zDummy = 0;
126374     rc = sqlite3Fts3ExprParse(
126375         pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy
126376     );
126377     assert( rc==SQLITE_OK || pExpr==0 );
126378     sqlite3_free(zDummy);
126379   }else{
126380     rc = fts3ExprParseUnbalanced(
126381         pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
126382     );
126383   }
126384
126385   if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
126386     sqlite3Fts3ExprFree(pExpr);
126387     sqlite3_result_error(context, "Error parsing expression", -1);
126388   }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
126389     sqlite3_result_error_nomem(context);
126390   }else{
126391     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
126392     sqlite3_free(zBuf);
126393   }
126394
126395   sqlite3Fts3ExprFree(pExpr);
126396
126397 exprtest_out:
126398   if( pModule && pTokenizer ){
126399     rc = pModule->xDestroy(pTokenizer);
126400   }
126401   sqlite3_free(azCol);
126402 }
126403
126404 /*
126405 ** Register the query expression parser test function fts3_exprtest() 
126406 ** with database connection db. 
126407 */
126408 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
126409   int rc = sqlite3_create_function(
126410       db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
126411   );
126412   if( rc==SQLITE_OK ){
126413     rc = sqlite3_create_function(db, "fts3_exprtest_rebalance", 
126414         -1, SQLITE_UTF8, (void *)1, fts3ExprTest, 0, 0
126415     );
126416   }
126417   return rc;
126418 }
126419
126420 #endif
126421 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
126422
126423 /************** End of fts3_expr.c *******************************************/
126424 /************** Begin file fts3_hash.c ***************************************/
126425 /*
126426 ** 2001 September 22
126427 **
126428 ** The author disclaims copyright to this source code.  In place of
126429 ** a legal notice, here is a blessing:
126430 **
126431 **    May you do good and not evil.
126432 **    May you find forgiveness for yourself and forgive others.
126433 **    May you share freely, never taking more than you give.
126434 **
126435 *************************************************************************
126436 ** This is the implementation of generic hash-tables used in SQLite.
126437 ** We've modified it slightly to serve as a standalone hash table
126438 ** implementation for the full-text indexing module.
126439 */
126440
126441 /*
126442 ** The code in this file is only compiled if:
126443 **
126444 **     * The FTS3 module is being built as an extension
126445 **       (in which case SQLITE_CORE is not defined), or
126446 **
126447 **     * The FTS3 module is being built into the core of
126448 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
126449 */
126450 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
126451
126452 /* #include <assert.h> */
126453 /* #include <stdlib.h> */
126454 /* #include <string.h> */
126455
126456
126457 /*
126458 ** Malloc and Free functions
126459 */
126460 static void *fts3HashMalloc(int n){
126461   void *p = sqlite3_malloc(n);
126462   if( p ){
126463     memset(p, 0, n);
126464   }
126465   return p;
126466 }
126467 static void fts3HashFree(void *p){
126468   sqlite3_free(p);
126469 }
126470
126471 /* Turn bulk memory into a hash table object by initializing the
126472 ** fields of the Hash structure.
126473 **
126474 ** "pNew" is a pointer to the hash table that is to be initialized.
126475 ** keyClass is one of the constants 
126476 ** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass 
126477 ** determines what kind of key the hash table will use.  "copyKey" is
126478 ** true if the hash table should make its own private copy of keys and
126479 ** false if it should just use the supplied pointer.
126480 */
126481 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
126482   assert( pNew!=0 );
126483   assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
126484   pNew->keyClass = keyClass;
126485   pNew->copyKey = copyKey;
126486   pNew->first = 0;
126487   pNew->count = 0;
126488   pNew->htsize = 0;
126489   pNew->ht = 0;
126490 }
126491
126492 /* Remove all entries from a hash table.  Reclaim all memory.
126493 ** Call this routine to delete a hash table or to reset a hash table
126494 ** to the empty state.
126495 */
126496 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
126497   Fts3HashElem *elem;         /* For looping over all elements of the table */
126498
126499   assert( pH!=0 );
126500   elem = pH->first;
126501   pH->first = 0;
126502   fts3HashFree(pH->ht);
126503   pH->ht = 0;
126504   pH->htsize = 0;
126505   while( elem ){
126506     Fts3HashElem *next_elem = elem->next;
126507     if( pH->copyKey && elem->pKey ){
126508       fts3HashFree(elem->pKey);
126509     }
126510     fts3HashFree(elem);
126511     elem = next_elem;
126512   }
126513   pH->count = 0;
126514 }
126515
126516 /*
126517 ** Hash and comparison functions when the mode is FTS3_HASH_STRING
126518 */
126519 static int fts3StrHash(const void *pKey, int nKey){
126520   const char *z = (const char *)pKey;
126521   int h = 0;
126522   if( nKey<=0 ) nKey = (int) strlen(z);
126523   while( nKey > 0  ){
126524     h = (h<<3) ^ h ^ *z++;
126525     nKey--;
126526   }
126527   return h & 0x7fffffff;
126528 }
126529 static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
126530   if( n1!=n2 ) return 1;
126531   return strncmp((const char*)pKey1,(const char*)pKey2,n1);
126532 }
126533
126534 /*
126535 ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
126536 */
126537 static int fts3BinHash(const void *pKey, int nKey){
126538   int h = 0;
126539   const char *z = (const char *)pKey;
126540   while( nKey-- > 0 ){
126541     h = (h<<3) ^ h ^ *(z++);
126542   }
126543   return h & 0x7fffffff;
126544 }
126545 static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
126546   if( n1!=n2 ) return 1;
126547   return memcmp(pKey1,pKey2,n1);
126548 }
126549
126550 /*
126551 ** Return a pointer to the appropriate hash function given the key class.
126552 **
126553 ** The C syntax in this function definition may be unfamilar to some 
126554 ** programmers, so we provide the following additional explanation:
126555 **
126556 ** The name of the function is "ftsHashFunction".  The function takes a
126557 ** single parameter "keyClass".  The return value of ftsHashFunction()
126558 ** is a pointer to another function.  Specifically, the return value
126559 ** of ftsHashFunction() is a pointer to a function that takes two parameters
126560 ** with types "const void*" and "int" and returns an "int".
126561 */
126562 static int (*ftsHashFunction(int keyClass))(const void*,int){
126563   if( keyClass==FTS3_HASH_STRING ){
126564     return &fts3StrHash;
126565   }else{
126566     assert( keyClass==FTS3_HASH_BINARY );
126567     return &fts3BinHash;
126568   }
126569 }
126570
126571 /*
126572 ** Return a pointer to the appropriate hash function given the key class.
126573 **
126574 ** For help in interpreted the obscure C code in the function definition,
126575 ** see the header comment on the previous function.
126576 */
126577 static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
126578   if( keyClass==FTS3_HASH_STRING ){
126579     return &fts3StrCompare;
126580   }else{
126581     assert( keyClass==FTS3_HASH_BINARY );
126582     return &fts3BinCompare;
126583   }
126584 }
126585
126586 /* Link an element into the hash table
126587 */
126588 static void fts3HashInsertElement(
126589   Fts3Hash *pH,            /* The complete hash table */
126590   struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
126591   Fts3HashElem *pNew       /* The element to be inserted */
126592 ){
126593   Fts3HashElem *pHead;     /* First element already in pEntry */
126594   pHead = pEntry->chain;
126595   if( pHead ){
126596     pNew->next = pHead;
126597     pNew->prev = pHead->prev;
126598     if( pHead->prev ){ pHead->prev->next = pNew; }
126599     else             { pH->first = pNew; }
126600     pHead->prev = pNew;
126601   }else{
126602     pNew->next = pH->first;
126603     if( pH->first ){ pH->first->prev = pNew; }
126604     pNew->prev = 0;
126605     pH->first = pNew;
126606   }
126607   pEntry->count++;
126608   pEntry->chain = pNew;
126609 }
126610
126611
126612 /* Resize the hash table so that it cantains "new_size" buckets.
126613 ** "new_size" must be a power of 2.  The hash table might fail 
126614 ** to resize if sqliteMalloc() fails.
126615 **
126616 ** Return non-zero if a memory allocation error occurs.
126617 */
126618 static int fts3Rehash(Fts3Hash *pH, int new_size){
126619   struct _fts3ht *new_ht;          /* The new hash table */
126620   Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
126621   int (*xHash)(const void*,int);   /* The hash function */
126622
126623   assert( (new_size & (new_size-1))==0 );
126624   new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
126625   if( new_ht==0 ) return 1;
126626   fts3HashFree(pH->ht);
126627   pH->ht = new_ht;
126628   pH->htsize = new_size;
126629   xHash = ftsHashFunction(pH->keyClass);
126630   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
126631     int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
126632     next_elem = elem->next;
126633     fts3HashInsertElement(pH, &new_ht[h], elem);
126634   }
126635   return 0;
126636 }
126637
126638 /* This function (for internal use only) locates an element in an
126639 ** hash table that matches the given key.  The hash for this key has
126640 ** already been computed and is passed as the 4th parameter.
126641 */
126642 static Fts3HashElem *fts3FindElementByHash(
126643   const Fts3Hash *pH, /* The pH to be searched */
126644   const void *pKey,   /* The key we are searching for */
126645   int nKey,
126646   int h               /* The hash for this key. */
126647 ){
126648   Fts3HashElem *elem;            /* Used to loop thru the element list */
126649   int count;                     /* Number of elements left to test */
126650   int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
126651
126652   if( pH->ht ){
126653     struct _fts3ht *pEntry = &pH->ht[h];
126654     elem = pEntry->chain;
126655     count = pEntry->count;
126656     xCompare = ftsCompareFunction(pH->keyClass);
126657     while( count-- && elem ){
126658       if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){ 
126659         return elem;
126660       }
126661       elem = elem->next;
126662     }
126663   }
126664   return 0;
126665 }
126666
126667 /* Remove a single entry from the hash table given a pointer to that
126668 ** element and a hash on the element's key.
126669 */
126670 static void fts3RemoveElementByHash(
126671   Fts3Hash *pH,         /* The pH containing "elem" */
126672   Fts3HashElem* elem,   /* The element to be removed from the pH */
126673   int h                 /* Hash value for the element */
126674 ){
126675   struct _fts3ht *pEntry;
126676   if( elem->prev ){
126677     elem->prev->next = elem->next; 
126678   }else{
126679     pH->first = elem->next;
126680   }
126681   if( elem->next ){
126682     elem->next->prev = elem->prev;
126683   }
126684   pEntry = &pH->ht[h];
126685   if( pEntry->chain==elem ){
126686     pEntry->chain = elem->next;
126687   }
126688   pEntry->count--;
126689   if( pEntry->count<=0 ){
126690     pEntry->chain = 0;
126691   }
126692   if( pH->copyKey && elem->pKey ){
126693     fts3HashFree(elem->pKey);
126694   }
126695   fts3HashFree( elem );
126696   pH->count--;
126697   if( pH->count<=0 ){
126698     assert( pH->first==0 );
126699     assert( pH->count==0 );
126700     fts3HashClear(pH);
126701   }
126702 }
126703
126704 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
126705   const Fts3Hash *pH, 
126706   const void *pKey, 
126707   int nKey
126708 ){
126709   int h;                          /* A hash on key */
126710   int (*xHash)(const void*,int);  /* The hash function */
126711
126712   if( pH==0 || pH->ht==0 ) return 0;
126713   xHash = ftsHashFunction(pH->keyClass);
126714   assert( xHash!=0 );
126715   h = (*xHash)(pKey,nKey);
126716   assert( (pH->htsize & (pH->htsize-1))==0 );
126717   return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
126718 }
126719
126720 /* 
126721 ** Attempt to locate an element of the hash table pH with a key
126722 ** that matches pKey,nKey.  Return the data for this element if it is
126723 ** found, or NULL if there is no match.
126724 */
126725 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
126726   Fts3HashElem *pElem;            /* The element that matches key (if any) */
126727
126728   pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
126729   return pElem ? pElem->data : 0;
126730 }
126731
126732 /* Insert an element into the hash table pH.  The key is pKey,nKey
126733 ** and the data is "data".
126734 **
126735 ** If no element exists with a matching key, then a new
126736 ** element is created.  A copy of the key is made if the copyKey
126737 ** flag is set.  NULL is returned.
126738 **
126739 ** If another element already exists with the same key, then the
126740 ** new data replaces the old data and the old data is returned.
126741 ** The key is not copied in this instance.  If a malloc fails, then
126742 ** the new data is returned and the hash table is unchanged.
126743 **
126744 ** If the "data" parameter to this function is NULL, then the
126745 ** element corresponding to "key" is removed from the hash table.
126746 */
126747 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
126748   Fts3Hash *pH,        /* The hash table to insert into */
126749   const void *pKey,    /* The key */
126750   int nKey,            /* Number of bytes in the key */
126751   void *data           /* The data */
126752 ){
126753   int hraw;                 /* Raw hash value of the key */
126754   int h;                    /* the hash of the key modulo hash table size */
126755   Fts3HashElem *elem;       /* Used to loop thru the element list */
126756   Fts3HashElem *new_elem;   /* New element added to the pH */
126757   int (*xHash)(const void*,int);  /* The hash function */
126758
126759   assert( pH!=0 );
126760   xHash = ftsHashFunction(pH->keyClass);
126761   assert( xHash!=0 );
126762   hraw = (*xHash)(pKey, nKey);
126763   assert( (pH->htsize & (pH->htsize-1))==0 );
126764   h = hraw & (pH->htsize-1);
126765   elem = fts3FindElementByHash(pH,pKey,nKey,h);
126766   if( elem ){
126767     void *old_data = elem->data;
126768     if( data==0 ){
126769       fts3RemoveElementByHash(pH,elem,h);
126770     }else{
126771       elem->data = data;
126772     }
126773     return old_data;
126774   }
126775   if( data==0 ) return 0;
126776   if( (pH->htsize==0 && fts3Rehash(pH,8))
126777    || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
126778   ){
126779     pH->count = 0;
126780     return data;
126781   }
126782   assert( pH->htsize>0 );
126783   new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
126784   if( new_elem==0 ) return data;
126785   if( pH->copyKey && pKey!=0 ){
126786     new_elem->pKey = fts3HashMalloc( nKey );
126787     if( new_elem->pKey==0 ){
126788       fts3HashFree(new_elem);
126789       return data;
126790     }
126791     memcpy((void*)new_elem->pKey, pKey, nKey);
126792   }else{
126793     new_elem->pKey = (void*)pKey;
126794   }
126795   new_elem->nKey = nKey;
126796   pH->count++;
126797   assert( pH->htsize>0 );
126798   assert( (pH->htsize & (pH->htsize-1))==0 );
126799   h = hraw & (pH->htsize-1);
126800   fts3HashInsertElement(pH, &pH->ht[h], new_elem);
126801   new_elem->data = data;
126802   return 0;
126803 }
126804
126805 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
126806
126807 /************** End of fts3_hash.c *******************************************/
126808 /************** Begin file fts3_porter.c *************************************/
126809 /*
126810 ** 2006 September 30
126811 **
126812 ** The author disclaims copyright to this source code.  In place of
126813 ** a legal notice, here is a blessing:
126814 **
126815 **    May you do good and not evil.
126816 **    May you find forgiveness for yourself and forgive others.
126817 **    May you share freely, never taking more than you give.
126818 **
126819 *************************************************************************
126820 ** Implementation of the full-text-search tokenizer that implements
126821 ** a Porter stemmer.
126822 */
126823
126824 /*
126825 ** The code in this file is only compiled if:
126826 **
126827 **     * The FTS3 module is being built as an extension
126828 **       (in which case SQLITE_CORE is not defined), or
126829 **
126830 **     * The FTS3 module is being built into the core of
126831 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
126832 */
126833 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
126834
126835 /* #include <assert.h> */
126836 /* #include <stdlib.h> */
126837 /* #include <stdio.h> */
126838 /* #include <string.h> */
126839
126840
126841 /*
126842 ** Class derived from sqlite3_tokenizer
126843 */
126844 typedef struct porter_tokenizer {
126845   sqlite3_tokenizer base;      /* Base class */
126846 } porter_tokenizer;
126847
126848 /*
126849 ** Class derived from sqlite3_tokenizer_cursor
126850 */
126851 typedef struct porter_tokenizer_cursor {
126852   sqlite3_tokenizer_cursor base;
126853   const char *zInput;          /* input we are tokenizing */
126854   int nInput;                  /* size of the input */
126855   int iOffset;                 /* current position in zInput */
126856   int iToken;                  /* index of next token to be returned */
126857   char *zToken;                /* storage for current token */
126858   int nAllocated;              /* space allocated to zToken buffer */
126859 } porter_tokenizer_cursor;
126860
126861
126862 /*
126863 ** Create a new tokenizer instance.
126864 */
126865 static int porterCreate(
126866   int argc, const char * const *argv,
126867   sqlite3_tokenizer **ppTokenizer
126868 ){
126869   porter_tokenizer *t;
126870
126871   UNUSED_PARAMETER(argc);
126872   UNUSED_PARAMETER(argv);
126873
126874   t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
126875   if( t==NULL ) return SQLITE_NOMEM;
126876   memset(t, 0, sizeof(*t));
126877   *ppTokenizer = &t->base;
126878   return SQLITE_OK;
126879 }
126880
126881 /*
126882 ** Destroy a tokenizer
126883 */
126884 static int porterDestroy(sqlite3_tokenizer *pTokenizer){
126885   sqlite3_free(pTokenizer);
126886   return SQLITE_OK;
126887 }
126888
126889 /*
126890 ** Prepare to begin tokenizing a particular string.  The input
126891 ** string to be tokenized is zInput[0..nInput-1].  A cursor
126892 ** used to incrementally tokenize this string is returned in 
126893 ** *ppCursor.
126894 */
126895 static int porterOpen(
126896   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
126897   const char *zInput, int nInput,        /* String to be tokenized */
126898   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
126899 ){
126900   porter_tokenizer_cursor *c;
126901
126902   UNUSED_PARAMETER(pTokenizer);
126903
126904   c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
126905   if( c==NULL ) return SQLITE_NOMEM;
126906
126907   c->zInput = zInput;
126908   if( zInput==0 ){
126909     c->nInput = 0;
126910   }else if( nInput<0 ){
126911     c->nInput = (int)strlen(zInput);
126912   }else{
126913     c->nInput = nInput;
126914   }
126915   c->iOffset = 0;                 /* start tokenizing at the beginning */
126916   c->iToken = 0;
126917   c->zToken = NULL;               /* no space allocated, yet. */
126918   c->nAllocated = 0;
126919
126920   *ppCursor = &c->base;
126921   return SQLITE_OK;
126922 }
126923
126924 /*
126925 ** Close a tokenization cursor previously opened by a call to
126926 ** porterOpen() above.
126927 */
126928 static int porterClose(sqlite3_tokenizer_cursor *pCursor){
126929   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
126930   sqlite3_free(c->zToken);
126931   sqlite3_free(c);
126932   return SQLITE_OK;
126933 }
126934 /*
126935 ** Vowel or consonant
126936 */
126937 static const char cType[] = {
126938    0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
126939    1, 1, 1, 2, 1
126940 };
126941
126942 /*
126943 ** isConsonant() and isVowel() determine if their first character in
126944 ** the string they point to is a consonant or a vowel, according
126945 ** to Porter ruls.  
126946 **
126947 ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
126948 ** 'Y' is a consonant unless it follows another consonant,
126949 ** in which case it is a vowel.
126950 **
126951 ** In these routine, the letters are in reverse order.  So the 'y' rule
126952 ** is that 'y' is a consonant unless it is followed by another
126953 ** consonent.
126954 */
126955 static int isVowel(const char*);
126956 static int isConsonant(const char *z){
126957   int j;
126958   char x = *z;
126959   if( x==0 ) return 0;
126960   assert( x>='a' && x<='z' );
126961   j = cType[x-'a'];
126962   if( j<2 ) return j;
126963   return z[1]==0 || isVowel(z + 1);
126964 }
126965 static int isVowel(const char *z){
126966   int j;
126967   char x = *z;
126968   if( x==0 ) return 0;
126969   assert( x>='a' && x<='z' );
126970   j = cType[x-'a'];
126971   if( j<2 ) return 1-j;
126972   return isConsonant(z + 1);
126973 }
126974
126975 /*
126976 ** Let any sequence of one or more vowels be represented by V and let
126977 ** C be sequence of one or more consonants.  Then every word can be
126978 ** represented as:
126979 **
126980 **           [C] (VC){m} [V]
126981 **
126982 ** In prose:  A word is an optional consonant followed by zero or
126983 ** vowel-consonant pairs followed by an optional vowel.  "m" is the
126984 ** number of vowel consonant pairs.  This routine computes the value
126985 ** of m for the first i bytes of a word.
126986 **
126987 ** Return true if the m-value for z is 1 or more.  In other words,
126988 ** return true if z contains at least one vowel that is followed
126989 ** by a consonant.
126990 **
126991 ** In this routine z[] is in reverse order.  So we are really looking
126992 ** for an instance of of a consonant followed by a vowel.
126993 */
126994 static int m_gt_0(const char *z){
126995   while( isVowel(z) ){ z++; }
126996   if( *z==0 ) return 0;
126997   while( isConsonant(z) ){ z++; }
126998   return *z!=0;
126999 }
127000
127001 /* Like mgt0 above except we are looking for a value of m which is
127002 ** exactly 1
127003 */
127004 static int m_eq_1(const char *z){
127005   while( isVowel(z) ){ z++; }
127006   if( *z==0 ) return 0;
127007   while( isConsonant(z) ){ z++; }
127008   if( *z==0 ) return 0;
127009   while( isVowel(z) ){ z++; }
127010   if( *z==0 ) return 1;
127011   while( isConsonant(z) ){ z++; }
127012   return *z==0;
127013 }
127014
127015 /* Like mgt0 above except we are looking for a value of m>1 instead
127016 ** or m>0
127017 */
127018 static int m_gt_1(const char *z){
127019   while( isVowel(z) ){ z++; }
127020   if( *z==0 ) return 0;
127021   while( isConsonant(z) ){ z++; }
127022   if( *z==0 ) return 0;
127023   while( isVowel(z) ){ z++; }
127024   if( *z==0 ) return 0;
127025   while( isConsonant(z) ){ z++; }
127026   return *z!=0;
127027 }
127028
127029 /*
127030 ** Return TRUE if there is a vowel anywhere within z[0..n-1]
127031 */
127032 static int hasVowel(const char *z){
127033   while( isConsonant(z) ){ z++; }
127034   return *z!=0;
127035 }
127036
127037 /*
127038 ** Return TRUE if the word ends in a double consonant.
127039 **
127040 ** The text is reversed here. So we are really looking at
127041 ** the first two characters of z[].
127042 */
127043 static int doubleConsonant(const char *z){
127044   return isConsonant(z) && z[0]==z[1];
127045 }
127046
127047 /*
127048 ** Return TRUE if the word ends with three letters which
127049 ** are consonant-vowel-consonent and where the final consonant
127050 ** is not 'w', 'x', or 'y'.
127051 **
127052 ** The word is reversed here.  So we are really checking the
127053 ** first three letters and the first one cannot be in [wxy].
127054 */
127055 static int star_oh(const char *z){
127056   return
127057     isConsonant(z) &&
127058     z[0]!='w' && z[0]!='x' && z[0]!='y' &&
127059     isVowel(z+1) &&
127060     isConsonant(z+2);
127061 }
127062
127063 /*
127064 ** If the word ends with zFrom and xCond() is true for the stem
127065 ** of the word that preceeds the zFrom ending, then change the 
127066 ** ending to zTo.
127067 **
127068 ** The input word *pz and zFrom are both in reverse order.  zTo
127069 ** is in normal order. 
127070 **
127071 ** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
127072 ** match.  Not that TRUE is returned even if xCond() fails and
127073 ** no substitution occurs.
127074 */
127075 static int stem(
127076   char **pz,             /* The word being stemmed (Reversed) */
127077   const char *zFrom,     /* If the ending matches this... (Reversed) */
127078   const char *zTo,       /* ... change the ending to this (not reversed) */
127079   int (*xCond)(const char*)   /* Condition that must be true */
127080 ){
127081   char *z = *pz;
127082   while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
127083   if( *zFrom!=0 ) return 0;
127084   if( xCond && !xCond(z) ) return 1;
127085   while( *zTo ){
127086     *(--z) = *(zTo++);
127087   }
127088   *pz = z;
127089   return 1;
127090 }
127091
127092 /*
127093 ** This is the fallback stemmer used when the porter stemmer is
127094 ** inappropriate.  The input word is copied into the output with
127095 ** US-ASCII case folding.  If the input word is too long (more
127096 ** than 20 bytes if it contains no digits or more than 6 bytes if
127097 ** it contains digits) then word is truncated to 20 or 6 bytes
127098 ** by taking 10 or 3 bytes from the beginning and end.
127099 */
127100 static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
127101   int i, mx, j;
127102   int hasDigit = 0;
127103   for(i=0; i<nIn; i++){
127104     char c = zIn[i];
127105     if( c>='A' && c<='Z' ){
127106       zOut[i] = c - 'A' + 'a';
127107     }else{
127108       if( c>='0' && c<='9' ) hasDigit = 1;
127109       zOut[i] = c;
127110     }
127111   }
127112   mx = hasDigit ? 3 : 10;
127113   if( nIn>mx*2 ){
127114     for(j=mx, i=nIn-mx; i<nIn; i++, j++){
127115       zOut[j] = zOut[i];
127116     }
127117     i = j;
127118   }
127119   zOut[i] = 0;
127120   *pnOut = i;
127121 }
127122
127123
127124 /*
127125 ** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
127126 ** zOut is at least big enough to hold nIn bytes.  Write the actual
127127 ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
127128 **
127129 ** Any upper-case characters in the US-ASCII character set ([A-Z])
127130 ** are converted to lower case.  Upper-case UTF characters are
127131 ** unchanged.
127132 **
127133 ** Words that are longer than about 20 bytes are stemmed by retaining
127134 ** a few bytes from the beginning and the end of the word.  If the
127135 ** word contains digits, 3 bytes are taken from the beginning and
127136 ** 3 bytes from the end.  For long words without digits, 10 bytes
127137 ** are taken from each end.  US-ASCII case folding still applies.
127138 ** 
127139 ** If the input word contains not digits but does characters not 
127140 ** in [a-zA-Z] then no stemming is attempted and this routine just 
127141 ** copies the input into the input into the output with US-ASCII
127142 ** case folding.
127143 **
127144 ** Stemming never increases the length of the word.  So there is
127145 ** no chance of overflowing the zOut buffer.
127146 */
127147 static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
127148   int i, j;
127149   char zReverse[28];
127150   char *z, *z2;
127151   if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
127152     /* The word is too big or too small for the porter stemmer.
127153     ** Fallback to the copy stemmer */
127154     copy_stemmer(zIn, nIn, zOut, pnOut);
127155     return;
127156   }
127157   for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
127158     char c = zIn[i];
127159     if( c>='A' && c<='Z' ){
127160       zReverse[j] = c + 'a' - 'A';
127161     }else if( c>='a' && c<='z' ){
127162       zReverse[j] = c;
127163     }else{
127164       /* The use of a character not in [a-zA-Z] means that we fallback
127165       ** to the copy stemmer */
127166       copy_stemmer(zIn, nIn, zOut, pnOut);
127167       return;
127168     }
127169   }
127170   memset(&zReverse[sizeof(zReverse)-5], 0, 5);
127171   z = &zReverse[j+1];
127172
127173
127174   /* Step 1a */
127175   if( z[0]=='s' ){
127176     if(
127177      !stem(&z, "sess", "ss", 0) &&
127178      !stem(&z, "sei", "i", 0)  &&
127179      !stem(&z, "ss", "ss", 0)
127180     ){
127181       z++;
127182     }
127183   }
127184
127185   /* Step 1b */  
127186   z2 = z;
127187   if( stem(&z, "dee", "ee", m_gt_0) ){
127188     /* Do nothing.  The work was all in the test */
127189   }else if( 
127190      (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
127191       && z!=z2
127192   ){
127193      if( stem(&z, "ta", "ate", 0) ||
127194          stem(&z, "lb", "ble", 0) ||
127195          stem(&z, "zi", "ize", 0) ){
127196        /* Do nothing.  The work was all in the test */
127197      }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
127198        z++;
127199      }else if( m_eq_1(z) && star_oh(z) ){
127200        *(--z) = 'e';
127201      }
127202   }
127203
127204   /* Step 1c */
127205   if( z[0]=='y' && hasVowel(z+1) ){
127206     z[0] = 'i';
127207   }
127208
127209   /* Step 2 */
127210   switch( z[1] ){
127211    case 'a':
127212      stem(&z, "lanoita", "ate", m_gt_0) ||
127213      stem(&z, "lanoit", "tion", m_gt_0);
127214      break;
127215    case 'c':
127216      stem(&z, "icne", "ence", m_gt_0) ||
127217      stem(&z, "icna", "ance", m_gt_0);
127218      break;
127219    case 'e':
127220      stem(&z, "rezi", "ize", m_gt_0);
127221      break;
127222    case 'g':
127223      stem(&z, "igol", "log", m_gt_0);
127224      break;
127225    case 'l':
127226      stem(&z, "ilb", "ble", m_gt_0) ||
127227      stem(&z, "illa", "al", m_gt_0) ||
127228      stem(&z, "iltne", "ent", m_gt_0) ||
127229      stem(&z, "ile", "e", m_gt_0) ||
127230      stem(&z, "ilsuo", "ous", m_gt_0);
127231      break;
127232    case 'o':
127233      stem(&z, "noitazi", "ize", m_gt_0) ||
127234      stem(&z, "noita", "ate", m_gt_0) ||
127235      stem(&z, "rota", "ate", m_gt_0);
127236      break;
127237    case 's':
127238      stem(&z, "msila", "al", m_gt_0) ||
127239      stem(&z, "ssenevi", "ive", m_gt_0) ||
127240      stem(&z, "ssenluf", "ful", m_gt_0) ||
127241      stem(&z, "ssensuo", "ous", m_gt_0);
127242      break;
127243    case 't':
127244      stem(&z, "itila", "al", m_gt_0) ||
127245      stem(&z, "itivi", "ive", m_gt_0) ||
127246      stem(&z, "itilib", "ble", m_gt_0);
127247      break;
127248   }
127249
127250   /* Step 3 */
127251   switch( z[0] ){
127252    case 'e':
127253      stem(&z, "etaci", "ic", m_gt_0) ||
127254      stem(&z, "evita", "", m_gt_0)   ||
127255      stem(&z, "ezila", "al", m_gt_0);
127256      break;
127257    case 'i':
127258      stem(&z, "itici", "ic", m_gt_0);
127259      break;
127260    case 'l':
127261      stem(&z, "laci", "ic", m_gt_0) ||
127262      stem(&z, "luf", "", m_gt_0);
127263      break;
127264    case 's':
127265      stem(&z, "ssen", "", m_gt_0);
127266      break;
127267   }
127268
127269   /* Step 4 */
127270   switch( z[1] ){
127271    case 'a':
127272      if( z[0]=='l' && m_gt_1(z+2) ){
127273        z += 2;
127274      }
127275      break;
127276    case 'c':
127277      if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
127278        z += 4;
127279      }
127280      break;
127281    case 'e':
127282      if( z[0]=='r' && m_gt_1(z+2) ){
127283        z += 2;
127284      }
127285      break;
127286    case 'i':
127287      if( z[0]=='c' && m_gt_1(z+2) ){
127288        z += 2;
127289      }
127290      break;
127291    case 'l':
127292      if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
127293        z += 4;
127294      }
127295      break;
127296    case 'n':
127297      if( z[0]=='t' ){
127298        if( z[2]=='a' ){
127299          if( m_gt_1(z+3) ){
127300            z += 3;
127301          }
127302        }else if( z[2]=='e' ){
127303          stem(&z, "tneme", "", m_gt_1) ||
127304          stem(&z, "tnem", "", m_gt_1) ||
127305          stem(&z, "tne", "", m_gt_1);
127306        }
127307      }
127308      break;
127309    case 'o':
127310      if( z[0]=='u' ){
127311        if( m_gt_1(z+2) ){
127312          z += 2;
127313        }
127314      }else if( z[3]=='s' || z[3]=='t' ){
127315        stem(&z, "noi", "", m_gt_1);
127316      }
127317      break;
127318    case 's':
127319      if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
127320        z += 3;
127321      }
127322      break;
127323    case 't':
127324      stem(&z, "eta", "", m_gt_1) ||
127325      stem(&z, "iti", "", m_gt_1);
127326      break;
127327    case 'u':
127328      if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
127329        z += 3;
127330      }
127331      break;
127332    case 'v':
127333    case 'z':
127334      if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
127335        z += 3;
127336      }
127337      break;
127338   }
127339
127340   /* Step 5a */
127341   if( z[0]=='e' ){
127342     if( m_gt_1(z+1) ){
127343       z++;
127344     }else if( m_eq_1(z+1) && !star_oh(z+1) ){
127345       z++;
127346     }
127347   }
127348
127349   /* Step 5b */
127350   if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
127351     z++;
127352   }
127353
127354   /* z[] is now the stemmed word in reverse order.  Flip it back
127355   ** around into forward order and return.
127356   */
127357   *pnOut = i = (int)strlen(z);
127358   zOut[i] = 0;
127359   while( *z ){
127360     zOut[--i] = *(z++);
127361   }
127362 }
127363
127364 /*
127365 ** Characters that can be part of a token.  We assume any character
127366 ** whose value is greater than 0x80 (any UTF character) can be
127367 ** part of a token.  In other words, delimiters all must have
127368 ** values of 0x7f or lower.
127369 */
127370 static const char porterIdChar[] = {
127371 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
127372     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
127373     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
127374     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
127375     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
127376     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
127377 };
127378 #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
127379
127380 /*
127381 ** Extract the next token from a tokenization cursor.  The cursor must
127382 ** have been opened by a prior call to porterOpen().
127383 */
127384 static int porterNext(
127385   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
127386   const char **pzToken,               /* OUT: *pzToken is the token text */
127387   int *pnBytes,                       /* OUT: Number of bytes in token */
127388   int *piStartOffset,                 /* OUT: Starting offset of token */
127389   int *piEndOffset,                   /* OUT: Ending offset of token */
127390   int *piPosition                     /* OUT: Position integer of token */
127391 ){
127392   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
127393   const char *z = c->zInput;
127394
127395   while( c->iOffset<c->nInput ){
127396     int iStartOffset, ch;
127397
127398     /* Scan past delimiter characters */
127399     while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
127400       c->iOffset++;
127401     }
127402
127403     /* Count non-delimiter characters. */
127404     iStartOffset = c->iOffset;
127405     while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
127406       c->iOffset++;
127407     }
127408
127409     if( c->iOffset>iStartOffset ){
127410       int n = c->iOffset-iStartOffset;
127411       if( n>c->nAllocated ){
127412         char *pNew;
127413         c->nAllocated = n+20;
127414         pNew = sqlite3_realloc(c->zToken, c->nAllocated);
127415         if( !pNew ) return SQLITE_NOMEM;
127416         c->zToken = pNew;
127417       }
127418       porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
127419       *pzToken = c->zToken;
127420       *piStartOffset = iStartOffset;
127421       *piEndOffset = c->iOffset;
127422       *piPosition = c->iToken++;
127423       return SQLITE_OK;
127424     }
127425   }
127426   return SQLITE_DONE;
127427 }
127428
127429 /*
127430 ** The set of routines that implement the porter-stemmer tokenizer
127431 */
127432 static const sqlite3_tokenizer_module porterTokenizerModule = {
127433   0,
127434   porterCreate,
127435   porterDestroy,
127436   porterOpen,
127437   porterClose,
127438   porterNext,
127439   0
127440 };
127441
127442 /*
127443 ** Allocate a new porter tokenizer.  Return a pointer to the new
127444 ** tokenizer in *ppModule
127445 */
127446 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
127447   sqlite3_tokenizer_module const**ppModule
127448 ){
127449   *ppModule = &porterTokenizerModule;
127450 }
127451
127452 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
127453
127454 /************** End of fts3_porter.c *****************************************/
127455 /************** Begin file fts3_tokenizer.c **********************************/
127456 /*
127457 ** 2007 June 22
127458 **
127459 ** The author disclaims copyright to this source code.  In place of
127460 ** a legal notice, here is a blessing:
127461 **
127462 **    May you do good and not evil.
127463 **    May you find forgiveness for yourself and forgive others.
127464 **    May you share freely, never taking more than you give.
127465 **
127466 ******************************************************************************
127467 **
127468 ** This is part of an SQLite module implementing full-text search.
127469 ** This particular file implements the generic tokenizer interface.
127470 */
127471
127472 /*
127473 ** The code in this file is only compiled if:
127474 **
127475 **     * The FTS3 module is being built as an extension
127476 **       (in which case SQLITE_CORE is not defined), or
127477 **
127478 **     * The FTS3 module is being built into the core of
127479 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
127480 */
127481 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
127482
127483 /* #include <assert.h> */
127484 /* #include <string.h> */
127485
127486 /*
127487 ** Implementation of the SQL scalar function for accessing the underlying 
127488 ** hash table. This function may be called as follows:
127489 **
127490 **   SELECT <function-name>(<key-name>);
127491 **   SELECT <function-name>(<key-name>, <pointer>);
127492 **
127493 ** where <function-name> is the name passed as the second argument
127494 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
127495 **
127496 ** If the <pointer> argument is specified, it must be a blob value
127497 ** containing a pointer to be stored as the hash data corresponding
127498 ** to the string <key-name>. If <pointer> is not specified, then
127499 ** the string <key-name> must already exist in the has table. Otherwise,
127500 ** an error is returned.
127501 **
127502 ** Whether or not the <pointer> argument is specified, the value returned
127503 ** is a blob containing the pointer stored as the hash data corresponding
127504 ** to string <key-name> (after the hash-table is updated, if applicable).
127505 */
127506 static void scalarFunc(
127507   sqlite3_context *context,
127508   int argc,
127509   sqlite3_value **argv
127510 ){
127511   Fts3Hash *pHash;
127512   void *pPtr = 0;
127513   const unsigned char *zName;
127514   int nName;
127515
127516   assert( argc==1 || argc==2 );
127517
127518   pHash = (Fts3Hash *)sqlite3_user_data(context);
127519
127520   zName = sqlite3_value_text(argv[0]);
127521   nName = sqlite3_value_bytes(argv[0])+1;
127522
127523   if( argc==2 ){
127524     void *pOld;
127525     int n = sqlite3_value_bytes(argv[1]);
127526     if( n!=sizeof(pPtr) ){
127527       sqlite3_result_error(context, "argument type mismatch", -1);
127528       return;
127529     }
127530     pPtr = *(void **)sqlite3_value_blob(argv[1]);
127531     pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
127532     if( pOld==pPtr ){
127533       sqlite3_result_error(context, "out of memory", -1);
127534       return;
127535     }
127536   }else{
127537     pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
127538     if( !pPtr ){
127539       char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
127540       sqlite3_result_error(context, zErr, -1);
127541       sqlite3_free(zErr);
127542       return;
127543     }
127544   }
127545
127546   sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
127547 }
127548
127549 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
127550   static const char isFtsIdChar[] = {
127551       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
127552       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
127553       0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
127554       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
127555       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
127556       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
127557       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
127558       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
127559   };
127560   return (c&0x80 || isFtsIdChar[(int)(c)]);
127561 }
127562
127563 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
127564   const char *z1;
127565   const char *z2 = 0;
127566
127567   /* Find the start of the next token. */
127568   z1 = zStr;
127569   while( z2==0 ){
127570     char c = *z1;
127571     switch( c ){
127572       case '\0': return 0;        /* No more tokens here */
127573       case '\'':
127574       case '"':
127575       case '`': {
127576         z2 = z1;
127577         while( *++z2 && (*z2!=c || *++z2==c) );
127578         break;
127579       }
127580       case '[':
127581         z2 = &z1[1];
127582         while( *z2 && z2[0]!=']' ) z2++;
127583         if( *z2 ) z2++;
127584         break;
127585
127586       default:
127587         if( sqlite3Fts3IsIdChar(*z1) ){
127588           z2 = &z1[1];
127589           while( sqlite3Fts3IsIdChar(*z2) ) z2++;
127590         }else{
127591           z1++;
127592         }
127593     }
127594   }
127595
127596   *pn = (int)(z2-z1);
127597   return z1;
127598 }
127599
127600 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
127601   Fts3Hash *pHash,                /* Tokenizer hash table */
127602   const char *zArg,               /* Tokenizer name */
127603   sqlite3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */
127604   char **pzErr                    /* OUT: Set to malloced error message */
127605 ){
127606   int rc;
127607   char *z = (char *)zArg;
127608   int n = 0;
127609   char *zCopy;
127610   char *zEnd;                     /* Pointer to nul-term of zCopy */
127611   sqlite3_tokenizer_module *m;
127612
127613   zCopy = sqlite3_mprintf("%s", zArg);
127614   if( !zCopy ) return SQLITE_NOMEM;
127615   zEnd = &zCopy[strlen(zCopy)];
127616
127617   z = (char *)sqlite3Fts3NextToken(zCopy, &n);
127618   z[n] = '\0';
127619   sqlite3Fts3Dequote(z);
127620
127621   m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
127622   if( !m ){
127623     *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
127624     rc = SQLITE_ERROR;
127625   }else{
127626     char const **aArg = 0;
127627     int iArg = 0;
127628     z = &z[n+1];
127629     while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
127630       int nNew = sizeof(char *)*(iArg+1);
127631       char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
127632       if( !aNew ){
127633         sqlite3_free(zCopy);
127634         sqlite3_free((void *)aArg);
127635         return SQLITE_NOMEM;
127636       }
127637       aArg = aNew;
127638       aArg[iArg++] = z;
127639       z[n] = '\0';
127640       sqlite3Fts3Dequote(z);
127641       z = &z[n+1];
127642     }
127643     rc = m->xCreate(iArg, aArg, ppTok);
127644     assert( rc!=SQLITE_OK || *ppTok );
127645     if( rc!=SQLITE_OK ){
127646       *pzErr = sqlite3_mprintf("unknown tokenizer");
127647     }else{
127648       (*ppTok)->pModule = m; 
127649     }
127650     sqlite3_free((void *)aArg);
127651   }
127652
127653   sqlite3_free(zCopy);
127654   return rc;
127655 }
127656
127657
127658 #ifdef SQLITE_TEST
127659
127660 /* #include <tcl.h> */
127661 /* #include <string.h> */
127662
127663 /*
127664 ** Implementation of a special SQL scalar function for testing tokenizers 
127665 ** designed to be used in concert with the Tcl testing framework. This
127666 ** function must be called with two or more arguments:
127667 **
127668 **   SELECT <function-name>(<key-name>, ..., <input-string>);
127669 **
127670 ** where <function-name> is the name passed as the second argument
127671 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
127672 ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
127673 **
127674 ** The return value is a string that may be interpreted as a Tcl
127675 ** list. For each token in the <input-string>, three elements are
127676 ** added to the returned list. The first is the token position, the 
127677 ** second is the token text (folded, stemmed, etc.) and the third is the
127678 ** substring of <input-string> associated with the token. For example, 
127679 ** using the built-in "simple" tokenizer:
127680 **
127681 **   SELECT fts_tokenizer_test('simple', 'I don't see how');
127682 **
127683 ** will return the string:
127684 **
127685 **   "{0 i I 1 dont don't 2 see see 3 how how}"
127686 **   
127687 */
127688 static void testFunc(
127689   sqlite3_context *context,
127690   int argc,
127691   sqlite3_value **argv
127692 ){
127693   Fts3Hash *pHash;
127694   sqlite3_tokenizer_module *p;
127695   sqlite3_tokenizer *pTokenizer = 0;
127696   sqlite3_tokenizer_cursor *pCsr = 0;
127697
127698   const char *zErr = 0;
127699
127700   const char *zName;
127701   int nName;
127702   const char *zInput;
127703   int nInput;
127704
127705   const char *azArg[64];
127706
127707   const char *zToken;
127708   int nToken = 0;
127709   int iStart = 0;
127710   int iEnd = 0;
127711   int iPos = 0;
127712   int i;
127713
127714   Tcl_Obj *pRet;
127715
127716   if( argc<2 ){
127717     sqlite3_result_error(context, "insufficient arguments", -1);
127718     return;
127719   }
127720
127721   nName = sqlite3_value_bytes(argv[0]);
127722   zName = (const char *)sqlite3_value_text(argv[0]);
127723   nInput = sqlite3_value_bytes(argv[argc-1]);
127724   zInput = (const char *)sqlite3_value_text(argv[argc-1]);
127725
127726   pHash = (Fts3Hash *)sqlite3_user_data(context);
127727   p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
127728
127729   if( !p ){
127730     char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
127731     sqlite3_result_error(context, zErr, -1);
127732     sqlite3_free(zErr);
127733     return;
127734   }
127735
127736   pRet = Tcl_NewObj();
127737   Tcl_IncrRefCount(pRet);
127738
127739   for(i=1; i<argc-1; i++){
127740     azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
127741   }
127742
127743   if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
127744     zErr = "error in xCreate()";
127745     goto finish;
127746   }
127747   pTokenizer->pModule = p;
127748   if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
127749     zErr = "error in xOpen()";
127750     goto finish;
127751   }
127752
127753   while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
127754     Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
127755     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
127756     zToken = &zInput[iStart];
127757     nToken = iEnd-iStart;
127758     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
127759   }
127760
127761   if( SQLITE_OK!=p->xClose(pCsr) ){
127762     zErr = "error in xClose()";
127763     goto finish;
127764   }
127765   if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
127766     zErr = "error in xDestroy()";
127767     goto finish;
127768   }
127769
127770 finish:
127771   if( zErr ){
127772     sqlite3_result_error(context, zErr, -1);
127773   }else{
127774     sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
127775   }
127776   Tcl_DecrRefCount(pRet);
127777 }
127778
127779 static
127780 int registerTokenizer(
127781   sqlite3 *db, 
127782   char *zName, 
127783   const sqlite3_tokenizer_module *p
127784 ){
127785   int rc;
127786   sqlite3_stmt *pStmt;
127787   const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
127788
127789   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
127790   if( rc!=SQLITE_OK ){
127791     return rc;
127792   }
127793
127794   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
127795   sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
127796   sqlite3_step(pStmt);
127797
127798   return sqlite3_finalize(pStmt);
127799 }
127800
127801 static
127802 int queryTokenizer(
127803   sqlite3 *db, 
127804   char *zName,  
127805   const sqlite3_tokenizer_module **pp
127806 ){
127807   int rc;
127808   sqlite3_stmt *pStmt;
127809   const char zSql[] = "SELECT fts3_tokenizer(?)";
127810
127811   *pp = 0;
127812   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
127813   if( rc!=SQLITE_OK ){
127814     return rc;
127815   }
127816
127817   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
127818   if( SQLITE_ROW==sqlite3_step(pStmt) ){
127819     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
127820       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
127821     }
127822   }
127823
127824   return sqlite3_finalize(pStmt);
127825 }
127826
127827 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
127828
127829 /*
127830 ** Implementation of the scalar function fts3_tokenizer_internal_test().
127831 ** This function is used for testing only, it is not included in the
127832 ** build unless SQLITE_TEST is defined.
127833 **
127834 ** The purpose of this is to test that the fts3_tokenizer() function
127835 ** can be used as designed by the C-code in the queryTokenizer and
127836 ** registerTokenizer() functions above. These two functions are repeated
127837 ** in the README.tokenizer file as an example, so it is important to
127838 ** test them.
127839 **
127840 ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
127841 ** function with no arguments. An assert() will fail if a problem is
127842 ** detected. i.e.:
127843 **
127844 **     SELECT fts3_tokenizer_internal_test();
127845 **
127846 */
127847 static void intTestFunc(
127848   sqlite3_context *context,
127849   int argc,
127850   sqlite3_value **argv
127851 ){
127852   int rc;
127853   const sqlite3_tokenizer_module *p1;
127854   const sqlite3_tokenizer_module *p2;
127855   sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
127856
127857   UNUSED_PARAMETER(argc);
127858   UNUSED_PARAMETER(argv);
127859
127860   /* Test the query function */
127861   sqlite3Fts3SimpleTokenizerModule(&p1);
127862   rc = queryTokenizer(db, "simple", &p2);
127863   assert( rc==SQLITE_OK );
127864   assert( p1==p2 );
127865   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
127866   assert( rc==SQLITE_ERROR );
127867   assert( p2==0 );
127868   assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
127869
127870   /* Test the storage function */
127871   rc = registerTokenizer(db, "nosuchtokenizer", p1);
127872   assert( rc==SQLITE_OK );
127873   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
127874   assert( rc==SQLITE_OK );
127875   assert( p2==p1 );
127876
127877   sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
127878 }
127879
127880 #endif
127881
127882 /*
127883 ** Set up SQL objects in database db used to access the contents of
127884 ** the hash table pointed to by argument pHash. The hash table must
127885 ** been initialized to use string keys, and to take a private copy 
127886 ** of the key when a value is inserted. i.e. by a call similar to:
127887 **
127888 **    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
127889 **
127890 ** This function adds a scalar function (see header comment above
127891 ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
127892 ** defined at compilation time, a temporary virtual table (see header 
127893 ** comment above struct HashTableVtab) to the database schema. Both 
127894 ** provide read/write access to the contents of *pHash.
127895 **
127896 ** The third argument to this function, zName, is used as the name
127897 ** of both the scalar and, if created, the virtual table.
127898 */
127899 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
127900   sqlite3 *db, 
127901   Fts3Hash *pHash, 
127902   const char *zName
127903 ){
127904   int rc = SQLITE_OK;
127905   void *p = (void *)pHash;
127906   const int any = SQLITE_ANY;
127907
127908 #ifdef SQLITE_TEST
127909   char *zTest = 0;
127910   char *zTest2 = 0;
127911   void *pdb = (void *)db;
127912   zTest = sqlite3_mprintf("%s_test", zName);
127913   zTest2 = sqlite3_mprintf("%s_internal_test", zName);
127914   if( !zTest || !zTest2 ){
127915     rc = SQLITE_NOMEM;
127916   }
127917 #endif
127918
127919   if( SQLITE_OK==rc ){
127920     rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);
127921   }
127922   if( SQLITE_OK==rc ){
127923     rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);
127924   }
127925 #ifdef SQLITE_TEST
127926   if( SQLITE_OK==rc ){
127927     rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
127928   }
127929   if( SQLITE_OK==rc ){
127930     rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
127931   }
127932 #endif
127933
127934 #ifdef SQLITE_TEST
127935   sqlite3_free(zTest);
127936   sqlite3_free(zTest2);
127937 #endif
127938
127939   return rc;
127940 }
127941
127942 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
127943
127944 /************** End of fts3_tokenizer.c **************************************/
127945 /************** Begin file fts3_tokenizer1.c *********************************/
127946 /*
127947 ** 2006 Oct 10
127948 **
127949 ** The author disclaims copyright to this source code.  In place of
127950 ** a legal notice, here is a blessing:
127951 **
127952 **    May you do good and not evil.
127953 **    May you find forgiveness for yourself and forgive others.
127954 **    May you share freely, never taking more than you give.
127955 **
127956 ******************************************************************************
127957 **
127958 ** Implementation of the "simple" full-text-search tokenizer.
127959 */
127960
127961 /*
127962 ** The code in this file is only compiled if:
127963 **
127964 **     * The FTS3 module is being built as an extension
127965 **       (in which case SQLITE_CORE is not defined), or
127966 **
127967 **     * The FTS3 module is being built into the core of
127968 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
127969 */
127970 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
127971
127972 /* #include <assert.h> */
127973 /* #include <stdlib.h> */
127974 /* #include <stdio.h> */
127975 /* #include <string.h> */
127976
127977
127978 typedef struct simple_tokenizer {
127979   sqlite3_tokenizer base;
127980   char delim[128];             /* flag ASCII delimiters */
127981 } simple_tokenizer;
127982
127983 typedef struct simple_tokenizer_cursor {
127984   sqlite3_tokenizer_cursor base;
127985   const char *pInput;          /* input we are tokenizing */
127986   int nBytes;                  /* size of the input */
127987   int iOffset;                 /* current position in pInput */
127988   int iToken;                  /* index of next token to be returned */
127989   char *pToken;                /* storage for current token */
127990   int nTokenAllocated;         /* space allocated to zToken buffer */
127991 } simple_tokenizer_cursor;
127992
127993
127994 static int simpleDelim(simple_tokenizer *t, unsigned char c){
127995   return c<0x80 && t->delim[c];
127996 }
127997 static int fts3_isalnum(int x){
127998   return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
127999 }
128000
128001 /*
128002 ** Create a new tokenizer instance.
128003 */
128004 static int simpleCreate(
128005   int argc, const char * const *argv,
128006   sqlite3_tokenizer **ppTokenizer
128007 ){
128008   simple_tokenizer *t;
128009
128010   t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
128011   if( t==NULL ) return SQLITE_NOMEM;
128012   memset(t, 0, sizeof(*t));
128013
128014   /* TODO(shess) Delimiters need to remain the same from run to run,
128015   ** else we need to reindex.  One solution would be a meta-table to
128016   ** track such information in the database, then we'd only want this
128017   ** information on the initial create.
128018   */
128019   if( argc>1 ){
128020     int i, n = (int)strlen(argv[1]);
128021     for(i=0; i<n; i++){
128022       unsigned char ch = argv[1][i];
128023       /* We explicitly don't support UTF-8 delimiters for now. */
128024       if( ch>=0x80 ){
128025         sqlite3_free(t);
128026         return SQLITE_ERROR;
128027       }
128028       t->delim[ch] = 1;
128029     }
128030   } else {
128031     /* Mark non-alphanumeric ASCII characters as delimiters */
128032     int i;
128033     for(i=1; i<0x80; i++){
128034       t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
128035     }
128036   }
128037
128038   *ppTokenizer = &t->base;
128039   return SQLITE_OK;
128040 }
128041
128042 /*
128043 ** Destroy a tokenizer
128044 */
128045 static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
128046   sqlite3_free(pTokenizer);
128047   return SQLITE_OK;
128048 }
128049
128050 /*
128051 ** Prepare to begin tokenizing a particular string.  The input
128052 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
128053 ** used to incrementally tokenize this string is returned in 
128054 ** *ppCursor.
128055 */
128056 static int simpleOpen(
128057   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
128058   const char *pInput, int nBytes,        /* String to be tokenized */
128059   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
128060 ){
128061   simple_tokenizer_cursor *c;
128062
128063   UNUSED_PARAMETER(pTokenizer);
128064
128065   c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
128066   if( c==NULL ) return SQLITE_NOMEM;
128067
128068   c->pInput = pInput;
128069   if( pInput==0 ){
128070     c->nBytes = 0;
128071   }else if( nBytes<0 ){
128072     c->nBytes = (int)strlen(pInput);
128073   }else{
128074     c->nBytes = nBytes;
128075   }
128076   c->iOffset = 0;                 /* start tokenizing at the beginning */
128077   c->iToken = 0;
128078   c->pToken = NULL;               /* no space allocated, yet. */
128079   c->nTokenAllocated = 0;
128080
128081   *ppCursor = &c->base;
128082   return SQLITE_OK;
128083 }
128084
128085 /*
128086 ** Close a tokenization cursor previously opened by a call to
128087 ** simpleOpen() above.
128088 */
128089 static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
128090   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
128091   sqlite3_free(c->pToken);
128092   sqlite3_free(c);
128093   return SQLITE_OK;
128094 }
128095
128096 /*
128097 ** Extract the next token from a tokenization cursor.  The cursor must
128098 ** have been opened by a prior call to simpleOpen().
128099 */
128100 static int simpleNext(
128101   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
128102   const char **ppToken,               /* OUT: *ppToken is the token text */
128103   int *pnBytes,                       /* OUT: Number of bytes in token */
128104   int *piStartOffset,                 /* OUT: Starting offset of token */
128105   int *piEndOffset,                   /* OUT: Ending offset of token */
128106   int *piPosition                     /* OUT: Position integer of token */
128107 ){
128108   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
128109   simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
128110   unsigned char *p = (unsigned char *)c->pInput;
128111
128112   while( c->iOffset<c->nBytes ){
128113     int iStartOffset;
128114
128115     /* Scan past delimiter characters */
128116     while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
128117       c->iOffset++;
128118     }
128119
128120     /* Count non-delimiter characters. */
128121     iStartOffset = c->iOffset;
128122     while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
128123       c->iOffset++;
128124     }
128125
128126     if( c->iOffset>iStartOffset ){
128127       int i, n = c->iOffset-iStartOffset;
128128       if( n>c->nTokenAllocated ){
128129         char *pNew;
128130         c->nTokenAllocated = n+20;
128131         pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
128132         if( !pNew ) return SQLITE_NOMEM;
128133         c->pToken = pNew;
128134       }
128135       for(i=0; i<n; i++){
128136         /* TODO(shess) This needs expansion to handle UTF-8
128137         ** case-insensitivity.
128138         */
128139         unsigned char ch = p[iStartOffset+i];
128140         c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
128141       }
128142       *ppToken = c->pToken;
128143       *pnBytes = n;
128144       *piStartOffset = iStartOffset;
128145       *piEndOffset = c->iOffset;
128146       *piPosition = c->iToken++;
128147
128148       return SQLITE_OK;
128149     }
128150   }
128151   return SQLITE_DONE;
128152 }
128153
128154 /*
128155 ** The set of routines that implement the simple tokenizer
128156 */
128157 static const sqlite3_tokenizer_module simpleTokenizerModule = {
128158   0,
128159   simpleCreate,
128160   simpleDestroy,
128161   simpleOpen,
128162   simpleClose,
128163   simpleNext,
128164   0,
128165 };
128166
128167 /*
128168 ** Allocate a new simple tokenizer.  Return a pointer to the new
128169 ** tokenizer in *ppModule
128170 */
128171 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
128172   sqlite3_tokenizer_module const**ppModule
128173 ){
128174   *ppModule = &simpleTokenizerModule;
128175 }
128176
128177 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
128178
128179 /************** End of fts3_tokenizer1.c *************************************/
128180 /************** Begin file fts3_tokenize_vtab.c ******************************/
128181 /*
128182 ** 2013 Apr 22
128183 **
128184 ** The author disclaims copyright to this source code.  In place of
128185 ** a legal notice, here is a blessing:
128186 **
128187 **    May you do good and not evil.
128188 **    May you find forgiveness for yourself and forgive others.
128189 **    May you share freely, never taking more than you give.
128190 **
128191 ******************************************************************************
128192 **
128193 ** This file contains code for the "fts3tokenize" virtual table module.
128194 ** An fts3tokenize virtual table is created as follows:
128195 **
128196 **   CREATE VIRTUAL TABLE <tbl> USING fts3tokenize(
128197 **       <tokenizer-name>, <arg-1>, ...
128198 **   );
128199 **
128200 ** The table created has the following schema:
128201 **
128202 **   CREATE TABLE <tbl>(input, token, start, end, position)
128203 **
128204 ** When queried, the query must include a WHERE clause of type:
128205 **
128206 **   input = <string>
128207 **
128208 ** The virtual table module tokenizes this <string>, using the FTS3 
128209 ** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE 
128210 ** statement and returns one row for each token in the result. With
128211 ** fields set as follows:
128212 **
128213 **   input:   Always set to a copy of <string>
128214 **   token:   A token from the input.
128215 **   start:   Byte offset of the token within the input <string>.
128216 **   end:     Byte offset of the byte immediately following the end of the
128217 **            token within the input string.
128218 **   pos:     Token offset of token within input.
128219 **
128220 */
128221 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
128222
128223 /* #include <string.h> */
128224 /* #include <assert.h> */
128225
128226 typedef struct Fts3tokTable Fts3tokTable;
128227 typedef struct Fts3tokCursor Fts3tokCursor;
128228
128229 /*
128230 ** Virtual table structure.
128231 */
128232 struct Fts3tokTable {
128233   sqlite3_vtab base;              /* Base class used by SQLite core */
128234   const sqlite3_tokenizer_module *pMod;
128235   sqlite3_tokenizer *pTok;
128236 };
128237
128238 /*
128239 ** Virtual table cursor structure.
128240 */
128241 struct Fts3tokCursor {
128242   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
128243   char *zInput;                   /* Input string */
128244   sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */
128245   int iRowid;                     /* Current 'rowid' value */
128246   const char *zToken;             /* Current 'token' value */
128247   int nToken;                     /* Size of zToken in bytes */
128248   int iStart;                     /* Current 'start' value */
128249   int iEnd;                       /* Current 'end' value */
128250   int iPos;                       /* Current 'pos' value */
128251 };
128252
128253 /*
128254 ** Query FTS for the tokenizer implementation named zName.
128255 */
128256 static int fts3tokQueryTokenizer(
128257   Fts3Hash *pHash,
128258   const char *zName,
128259   const sqlite3_tokenizer_module **pp,
128260   char **pzErr
128261 ){
128262   sqlite3_tokenizer_module *p;
128263   int nName = (int)strlen(zName);
128264
128265   p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
128266   if( !p ){
128267     *pzErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
128268     return SQLITE_ERROR;
128269   }
128270
128271   *pp = p;
128272   return SQLITE_OK;
128273 }
128274
128275 /*
128276 ** The second argument, argv[], is an array of pointers to nul-terminated
128277 ** strings. This function makes a copy of the array and strings into a 
128278 ** single block of memory. It then dequotes any of the strings that appear
128279 ** to be quoted.
128280 **
128281 ** If successful, output parameter *pazDequote is set to point at the
128282 ** array of dequoted strings and SQLITE_OK is returned. The caller is
128283 ** responsible for eventually calling sqlite3_free() to free the array
128284 ** in this case. Or, if an error occurs, an SQLite error code is returned.
128285 ** The final value of *pazDequote is undefined in this case.
128286 */
128287 static int fts3tokDequoteArray(
128288   int argc,                       /* Number of elements in argv[] */
128289   const char * const *argv,       /* Input array */
128290   char ***pazDequote              /* Output array */
128291 ){
128292   int rc = SQLITE_OK;             /* Return code */
128293   if( argc==0 ){
128294     *pazDequote = 0;
128295   }else{
128296     int i;
128297     int nByte = 0;
128298     char **azDequote;
128299
128300     for(i=0; i<argc; i++){
128301       nByte += (int)(strlen(argv[i]) + 1);
128302     }
128303
128304     *pazDequote = azDequote = sqlite3_malloc(sizeof(char *)*argc + nByte);
128305     if( azDequote==0 ){
128306       rc = SQLITE_NOMEM;
128307     }else{
128308       char *pSpace = (char *)&azDequote[argc];
128309       for(i=0; i<argc; i++){
128310         int n = (int)strlen(argv[i]);
128311         azDequote[i] = pSpace;
128312         memcpy(pSpace, argv[i], n+1);
128313         sqlite3Fts3Dequote(pSpace);
128314         pSpace += (n+1);
128315       }
128316     }
128317   }
128318
128319   return rc;
128320 }
128321
128322 /*
128323 ** Schema of the tokenizer table.
128324 */
128325 #define FTS3_TOK_SCHEMA "CREATE TABLE x(input, token, start, end, position)"
128326
128327 /*
128328 ** This function does all the work for both the xConnect and xCreate methods.
128329 ** These tables have no persistent representation of their own, so xConnect
128330 ** and xCreate are identical operations.
128331 **
128332 **   argv[0]: module name
128333 **   argv[1]: database name 
128334 **   argv[2]: table name
128335 **   argv[3]: first argument (tokenizer name)
128336 */
128337 static int fts3tokConnectMethod(
128338   sqlite3 *db,                    /* Database connection */
128339   void *pHash,                    /* Hash table of tokenizers */
128340   int argc,                       /* Number of elements in argv array */
128341   const char * const *argv,       /* xCreate/xConnect argument array */
128342   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
128343   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
128344 ){
128345   Fts3tokTable *pTab;
128346   const sqlite3_tokenizer_module *pMod = 0;
128347   sqlite3_tokenizer *pTok = 0;
128348   int rc;
128349   char **azDequote = 0;
128350   int nDequote;
128351
128352   rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA);
128353   if( rc!=SQLITE_OK ) return rc;
128354
128355   nDequote = argc-3;
128356   rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote);
128357
128358   if( rc==SQLITE_OK ){
128359     const char *zModule;
128360     if( nDequote<1 ){
128361       zModule = "simple";
128362     }else{
128363       zModule = azDequote[0];
128364     }
128365     rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr);
128366   }
128367
128368   assert( (rc==SQLITE_OK)==(pMod!=0) );
128369   if( rc==SQLITE_OK ){
128370     const char * const *azArg = (const char * const *)&azDequote[1];
128371     rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);
128372   }
128373
128374   if( rc==SQLITE_OK ){
128375     pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable));
128376     if( pTab==0 ){
128377       rc = SQLITE_NOMEM;
128378     }
128379   }
128380
128381   if( rc==SQLITE_OK ){
128382     memset(pTab, 0, sizeof(Fts3tokTable));
128383     pTab->pMod = pMod;
128384     pTab->pTok = pTok;
128385     *ppVtab = &pTab->base;
128386   }else{
128387     if( pTok ){
128388       pMod->xDestroy(pTok);
128389     }
128390   }
128391
128392   sqlite3_free(azDequote);
128393   return rc;
128394 }
128395
128396 /*
128397 ** This function does the work for both the xDisconnect and xDestroy methods.
128398 ** These tables have no persistent representation of their own, so xDisconnect
128399 ** and xDestroy are identical operations.
128400 */
128401 static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){
128402   Fts3tokTable *pTab = (Fts3tokTable *)pVtab;
128403
128404   pTab->pMod->xDestroy(pTab->pTok);
128405   sqlite3_free(pTab);
128406   return SQLITE_OK;
128407 }
128408
128409 /*
128410 ** xBestIndex - Analyze a WHERE and ORDER BY clause.
128411 */
128412 static int fts3tokBestIndexMethod(
128413   sqlite3_vtab *pVTab, 
128414   sqlite3_index_info *pInfo
128415 ){
128416   int i;
128417   UNUSED_PARAMETER(pVTab);
128418
128419   for(i=0; i<pInfo->nConstraint; i++){
128420     if( pInfo->aConstraint[i].usable 
128421      && pInfo->aConstraint[i].iColumn==0 
128422      && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ 
128423     ){
128424       pInfo->idxNum = 1;
128425       pInfo->aConstraintUsage[i].argvIndex = 1;
128426       pInfo->aConstraintUsage[i].omit = 1;
128427       pInfo->estimatedCost = 1;
128428       return SQLITE_OK;
128429     }
128430   }
128431
128432   pInfo->idxNum = 0;
128433   assert( pInfo->estimatedCost>1000000.0 );
128434
128435   return SQLITE_OK;
128436 }
128437
128438 /*
128439 ** xOpen - Open a cursor.
128440 */
128441 static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
128442   Fts3tokCursor *pCsr;
128443   UNUSED_PARAMETER(pVTab);
128444
128445   pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor));
128446   if( pCsr==0 ){
128447     return SQLITE_NOMEM;
128448   }
128449   memset(pCsr, 0, sizeof(Fts3tokCursor));
128450
128451   *ppCsr = (sqlite3_vtab_cursor *)pCsr;
128452   return SQLITE_OK;
128453 }
128454
128455 /*
128456 ** Reset the tokenizer cursor passed as the only argument. As if it had
128457 ** just been returned by fts3tokOpenMethod().
128458 */
128459 static void fts3tokResetCursor(Fts3tokCursor *pCsr){
128460   if( pCsr->pCsr ){
128461     Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab);
128462     pTab->pMod->xClose(pCsr->pCsr);
128463     pCsr->pCsr = 0;
128464   }
128465   sqlite3_free(pCsr->zInput);
128466   pCsr->zInput = 0;
128467   pCsr->zToken = 0;
128468   pCsr->nToken = 0;
128469   pCsr->iStart = 0;
128470   pCsr->iEnd = 0;
128471   pCsr->iPos = 0;
128472   pCsr->iRowid = 0;
128473 }
128474
128475 /*
128476 ** xClose - Close a cursor.
128477 */
128478 static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){
128479   Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
128480
128481   fts3tokResetCursor(pCsr);
128482   sqlite3_free(pCsr);
128483   return SQLITE_OK;
128484 }
128485
128486 /*
128487 ** xNext - Advance the cursor to the next row, if any.
128488 */
128489 static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){
128490   Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
128491   Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
128492   int rc;                         /* Return code */
128493
128494   pCsr->iRowid++;
128495   rc = pTab->pMod->xNext(pCsr->pCsr,
128496       &pCsr->zToken, &pCsr->nToken,
128497       &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos
128498   );
128499
128500   if( rc!=SQLITE_OK ){
128501     fts3tokResetCursor(pCsr);
128502     if( rc==SQLITE_DONE ) rc = SQLITE_OK;
128503   }
128504
128505   return rc;
128506 }
128507
128508 /*
128509 ** xFilter - Initialize a cursor to point at the start of its data.
128510 */
128511 static int fts3tokFilterMethod(
128512   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
128513   int idxNum,                     /* Strategy index */
128514   const char *idxStr,             /* Unused */
128515   int nVal,                       /* Number of elements in apVal */
128516   sqlite3_value **apVal           /* Arguments for the indexing scheme */
128517 ){
128518   int rc = SQLITE_ERROR;
128519   Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
128520   Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
128521   UNUSED_PARAMETER(idxStr);
128522   UNUSED_PARAMETER(nVal);
128523
128524   fts3tokResetCursor(pCsr);
128525   if( idxNum==1 ){
128526     const char *zByte = (const char *)sqlite3_value_text(apVal[0]);
128527     int nByte = sqlite3_value_bytes(apVal[0]);
128528     pCsr->zInput = sqlite3_malloc(nByte+1);
128529     if( pCsr->zInput==0 ){
128530       rc = SQLITE_NOMEM;
128531     }else{
128532       memcpy(pCsr->zInput, zByte, nByte);
128533       pCsr->zInput[nByte] = 0;
128534       rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);
128535       if( rc==SQLITE_OK ){
128536         pCsr->pCsr->pTokenizer = pTab->pTok;
128537       }
128538     }
128539   }
128540
128541   if( rc!=SQLITE_OK ) return rc;
128542   return fts3tokNextMethod(pCursor);
128543 }
128544
128545 /*
128546 ** xEof - Return true if the cursor is at EOF, or false otherwise.
128547 */
128548 static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){
128549   Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
128550   return (pCsr->zToken==0);
128551 }
128552
128553 /*
128554 ** xColumn - Return a column value.
128555 */
128556 static int fts3tokColumnMethod(
128557   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
128558   sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
128559   int iCol                        /* Index of column to read value from */
128560 ){
128561   Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
128562
128563   /* CREATE TABLE x(input, token, start, end, position) */
128564   switch( iCol ){
128565     case 0:
128566       sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT);
128567       break;
128568     case 1:
128569       sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT);
128570       break;
128571     case 2:
128572       sqlite3_result_int(pCtx, pCsr->iStart);
128573       break;
128574     case 3:
128575       sqlite3_result_int(pCtx, pCsr->iEnd);
128576       break;
128577     default:
128578       assert( iCol==4 );
128579       sqlite3_result_int(pCtx, pCsr->iPos);
128580       break;
128581   }
128582   return SQLITE_OK;
128583 }
128584
128585 /*
128586 ** xRowid - Return the current rowid for the cursor.
128587 */
128588 static int fts3tokRowidMethod(
128589   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
128590   sqlite_int64 *pRowid            /* OUT: Rowid value */
128591 ){
128592   Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
128593   *pRowid = (sqlite3_int64)pCsr->iRowid;
128594   return SQLITE_OK;
128595 }
128596
128597 /*
128598 ** Register the fts3tok module with database connection db. Return SQLITE_OK
128599 ** if successful or an error code if sqlite3_create_module() fails.
128600 */
128601 SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
128602   static const sqlite3_module fts3tok_module = {
128603      0,                           /* iVersion      */
128604      fts3tokConnectMethod,        /* xCreate       */
128605      fts3tokConnectMethod,        /* xConnect      */
128606      fts3tokBestIndexMethod,      /* xBestIndex    */
128607      fts3tokDisconnectMethod,     /* xDisconnect   */
128608      fts3tokDisconnectMethod,     /* xDestroy      */
128609      fts3tokOpenMethod,           /* xOpen         */
128610      fts3tokCloseMethod,          /* xClose        */
128611      fts3tokFilterMethod,         /* xFilter       */
128612      fts3tokNextMethod,           /* xNext         */
128613      fts3tokEofMethod,            /* xEof          */
128614      fts3tokColumnMethod,         /* xColumn       */
128615      fts3tokRowidMethod,          /* xRowid        */
128616      0,                           /* xUpdate       */
128617      0,                           /* xBegin        */
128618      0,                           /* xSync         */
128619      0,                           /* xCommit       */
128620      0,                           /* xRollback     */
128621      0,                           /* xFindFunction */
128622      0,                           /* xRename       */
128623      0,                           /* xSavepoint    */
128624      0,                           /* xRelease      */
128625      0                            /* xRollbackTo   */
128626   };
128627   int rc;                         /* Return code */
128628
128629   rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash);
128630   return rc;
128631 }
128632
128633 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
128634
128635 /************** End of fts3_tokenize_vtab.c **********************************/
128636 /************** Begin file fts3_write.c **************************************/
128637 /*
128638 ** 2009 Oct 23
128639 **
128640 ** The author disclaims copyright to this source code.  In place of
128641 ** a legal notice, here is a blessing:
128642 **
128643 **    May you do good and not evil.
128644 **    May you find forgiveness for yourself and forgive others.
128645 **    May you share freely, never taking more than you give.
128646 **
128647 ******************************************************************************
128648 **
128649 ** This file is part of the SQLite FTS3 extension module. Specifically,
128650 ** this file contains code to insert, update and delete rows from FTS3
128651 ** tables. It also contains code to merge FTS3 b-tree segments. Some
128652 ** of the sub-routines used to merge segments are also used by the query 
128653 ** code in fts3.c.
128654 */
128655
128656 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
128657
128658 /* #include <string.h> */
128659 /* #include <assert.h> */
128660 /* #include <stdlib.h> */
128661
128662
128663 #define FTS_MAX_APPENDABLE_HEIGHT 16
128664
128665 /*
128666 ** When full-text index nodes are loaded from disk, the buffer that they
128667 ** are loaded into has the following number of bytes of padding at the end 
128668 ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
128669 ** of 920 bytes is allocated for it.
128670 **
128671 ** This means that if we have a pointer into a buffer containing node data,
128672 ** it is always safe to read up to two varints from it without risking an
128673 ** overread, even if the node data is corrupted.
128674 */
128675 #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
128676
128677 /*
128678 ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
128679 ** memory incrementally instead of all at once. This can be a big performance
128680 ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
128681 ** method before retrieving all query results (as may happen, for example,
128682 ** if a query has a LIMIT clause).
128683 **
128684 ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD 
128685 ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
128686 ** The code is written so that the hard lower-limit for each of these values 
128687 ** is 1. Clearly such small values would be inefficient, but can be useful 
128688 ** for testing purposes.
128689 **
128690 ** If this module is built with SQLITE_TEST defined, these constants may
128691 ** be overridden at runtime for testing purposes. File fts3_test.c contains
128692 ** a Tcl interface to read and write the values.
128693 */
128694 #ifdef SQLITE_TEST
128695 int test_fts3_node_chunksize = (4*1024);
128696 int test_fts3_node_chunk_threshold = (4*1024)*4;
128697 # define FTS3_NODE_CHUNKSIZE       test_fts3_node_chunksize
128698 # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
128699 #else
128700 # define FTS3_NODE_CHUNKSIZE (4*1024) 
128701 # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
128702 #endif
128703
128704 /*
128705 ** The two values that may be meaningfully bound to the :1 parameter in
128706 ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
128707 */
128708 #define FTS_STAT_DOCTOTAL      0
128709 #define FTS_STAT_INCRMERGEHINT 1
128710 #define FTS_STAT_AUTOINCRMERGE 2
128711
128712 /*
128713 ** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
128714 ** and incremental merge operation that takes place. This is used for 
128715 ** debugging FTS only, it should not usually be turned on in production
128716 ** systems.
128717 */
128718 #ifdef FTS3_LOG_MERGES
128719 static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
128720   sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
128721 }
128722 #else
128723 #define fts3LogMerge(x, y)
128724 #endif
128725
128726
128727 typedef struct PendingList PendingList;
128728 typedef struct SegmentNode SegmentNode;
128729 typedef struct SegmentWriter SegmentWriter;
128730
128731 /*
128732 ** An instance of the following data structure is used to build doclists
128733 ** incrementally. See function fts3PendingListAppend() for details.
128734 */
128735 struct PendingList {
128736   int nData;
128737   char *aData;
128738   int nSpace;
128739   sqlite3_int64 iLastDocid;
128740   sqlite3_int64 iLastCol;
128741   sqlite3_int64 iLastPos;
128742 };
128743
128744
128745 /*
128746 ** Each cursor has a (possibly empty) linked list of the following objects.
128747 */
128748 struct Fts3DeferredToken {
128749   Fts3PhraseToken *pToken;        /* Pointer to corresponding expr token */
128750   int iCol;                       /* Column token must occur in */
128751   Fts3DeferredToken *pNext;       /* Next in list of deferred tokens */
128752   PendingList *pList;             /* Doclist is assembled here */
128753 };
128754
128755 /*
128756 ** An instance of this structure is used to iterate through the terms on
128757 ** a contiguous set of segment b-tree leaf nodes. Although the details of
128758 ** this structure are only manipulated by code in this file, opaque handles
128759 ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
128760 ** terms when querying the full-text index. See functions:
128761 **
128762 **   sqlite3Fts3SegReaderNew()
128763 **   sqlite3Fts3SegReaderFree()
128764 **   sqlite3Fts3SegReaderIterate()
128765 **
128766 ** Methods used to manipulate Fts3SegReader structures:
128767 **
128768 **   fts3SegReaderNext()
128769 **   fts3SegReaderFirstDocid()
128770 **   fts3SegReaderNextDocid()
128771 */
128772 struct Fts3SegReader {
128773   int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
128774   u8 bLookup;                     /* True for a lookup only */
128775   u8 rootOnly;                    /* True for a root-only reader */
128776
128777   sqlite3_int64 iStartBlock;      /* Rowid of first leaf block to traverse */
128778   sqlite3_int64 iLeafEndBlock;    /* Rowid of final leaf block to traverse */
128779   sqlite3_int64 iEndBlock;        /* Rowid of final block in segment (or 0) */
128780   sqlite3_int64 iCurrentBlock;    /* Current leaf block (or 0) */
128781
128782   char *aNode;                    /* Pointer to node data (or NULL) */
128783   int nNode;                      /* Size of buffer at aNode (or 0) */
128784   int nPopulate;                  /* If >0, bytes of buffer aNode[] loaded */
128785   sqlite3_blob *pBlob;            /* If not NULL, blob handle to read node */
128786
128787   Fts3HashElem **ppNextElem;
128788
128789   /* Variables set by fts3SegReaderNext(). These may be read directly
128790   ** by the caller. They are valid from the time SegmentReaderNew() returns
128791   ** until SegmentReaderNext() returns something other than SQLITE_OK
128792   ** (i.e. SQLITE_DONE).
128793   */
128794   int nTerm;                      /* Number of bytes in current term */
128795   char *zTerm;                    /* Pointer to current term */
128796   int nTermAlloc;                 /* Allocated size of zTerm buffer */
128797   char *aDoclist;                 /* Pointer to doclist of current entry */
128798   int nDoclist;                   /* Size of doclist in current entry */
128799
128800   /* The following variables are used by fts3SegReaderNextDocid() to iterate 
128801   ** through the current doclist (aDoclist/nDoclist).
128802   */
128803   char *pOffsetList;
128804   int nOffsetList;                /* For descending pending seg-readers only */
128805   sqlite3_int64 iDocid;
128806 };
128807
128808 #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
128809 #define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
128810
128811 /*
128812 ** An instance of this structure is used to create a segment b-tree in the
128813 ** database. The internal details of this type are only accessed by the
128814 ** following functions:
128815 **
128816 **   fts3SegWriterAdd()
128817 **   fts3SegWriterFlush()
128818 **   fts3SegWriterFree()
128819 */
128820 struct SegmentWriter {
128821   SegmentNode *pTree;             /* Pointer to interior tree structure */
128822   sqlite3_int64 iFirst;           /* First slot in %_segments written */
128823   sqlite3_int64 iFree;            /* Next free slot in %_segments */
128824   char *zTerm;                    /* Pointer to previous term buffer */
128825   int nTerm;                      /* Number of bytes in zTerm */
128826   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
128827   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
128828   int nSize;                      /* Size of allocation at aData */
128829   int nData;                      /* Bytes of data in aData */
128830   char *aData;                    /* Pointer to block from malloc() */
128831 };
128832
128833 /*
128834 ** Type SegmentNode is used by the following three functions to create
128835 ** the interior part of the segment b+-tree structures (everything except
128836 ** the leaf nodes). These functions and type are only ever used by code
128837 ** within the fts3SegWriterXXX() family of functions described above.
128838 **
128839 **   fts3NodeAddTerm()
128840 **   fts3NodeWrite()
128841 **   fts3NodeFree()
128842 **
128843 ** When a b+tree is written to the database (either as a result of a merge
128844 ** or the pending-terms table being flushed), leaves are written into the 
128845 ** database file as soon as they are completely populated. The interior of
128846 ** the tree is assembled in memory and written out only once all leaves have
128847 ** been populated and stored. This is Ok, as the b+-tree fanout is usually
128848 ** very large, meaning that the interior of the tree consumes relatively 
128849 ** little memory.
128850 */
128851 struct SegmentNode {
128852   SegmentNode *pParent;           /* Parent node (or NULL for root node) */
128853   SegmentNode *pRight;            /* Pointer to right-sibling */
128854   SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
128855   int nEntry;                     /* Number of terms written to node so far */
128856   char *zTerm;                    /* Pointer to previous term buffer */
128857   int nTerm;                      /* Number of bytes in zTerm */
128858   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
128859   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
128860   int nData;                      /* Bytes of valid data so far */
128861   char *aData;                    /* Node data */
128862 };
128863
128864 /*
128865 ** Valid values for the second argument to fts3SqlStmt().
128866 */
128867 #define SQL_DELETE_CONTENT             0
128868 #define SQL_IS_EMPTY                   1
128869 #define SQL_DELETE_ALL_CONTENT         2 
128870 #define SQL_DELETE_ALL_SEGMENTS        3
128871 #define SQL_DELETE_ALL_SEGDIR          4
128872 #define SQL_DELETE_ALL_DOCSIZE         5
128873 #define SQL_DELETE_ALL_STAT            6
128874 #define SQL_SELECT_CONTENT_BY_ROWID    7
128875 #define SQL_NEXT_SEGMENT_INDEX         8
128876 #define SQL_INSERT_SEGMENTS            9
128877 #define SQL_NEXT_SEGMENTS_ID          10
128878 #define SQL_INSERT_SEGDIR             11
128879 #define SQL_SELECT_LEVEL              12
128880 #define SQL_SELECT_LEVEL_RANGE        13
128881 #define SQL_SELECT_LEVEL_COUNT        14
128882 #define SQL_SELECT_SEGDIR_MAX_LEVEL   15
128883 #define SQL_DELETE_SEGDIR_LEVEL       16
128884 #define SQL_DELETE_SEGMENTS_RANGE     17
128885 #define SQL_CONTENT_INSERT            18
128886 #define SQL_DELETE_DOCSIZE            19
128887 #define SQL_REPLACE_DOCSIZE           20
128888 #define SQL_SELECT_DOCSIZE            21
128889 #define SQL_SELECT_STAT               22
128890 #define SQL_REPLACE_STAT              23
128891
128892 #define SQL_SELECT_ALL_PREFIX_LEVEL   24
128893 #define SQL_DELETE_ALL_TERMS_SEGDIR   25
128894 #define SQL_DELETE_SEGDIR_RANGE       26
128895 #define SQL_SELECT_ALL_LANGID         27
128896 #define SQL_FIND_MERGE_LEVEL          28
128897 #define SQL_MAX_LEAF_NODE_ESTIMATE    29
128898 #define SQL_DELETE_SEGDIR_ENTRY       30
128899 #define SQL_SHIFT_SEGDIR_ENTRY        31
128900 #define SQL_SELECT_SEGDIR             32
128901 #define SQL_CHOMP_SEGDIR              33
128902 #define SQL_SEGMENT_IS_APPENDABLE     34
128903 #define SQL_SELECT_INDEXES            35
128904 #define SQL_SELECT_MXLEVEL            36
128905
128906 /*
128907 ** This function is used to obtain an SQLite prepared statement handle
128908 ** for the statement identified by the second argument. If successful,
128909 ** *pp is set to the requested statement handle and SQLITE_OK returned.
128910 ** Otherwise, an SQLite error code is returned and *pp is set to 0.
128911 **
128912 ** If argument apVal is not NULL, then it must point to an array with
128913 ** at least as many entries as the requested statement has bound 
128914 ** parameters. The values are bound to the statements parameters before
128915 ** returning.
128916 */
128917 static int fts3SqlStmt(
128918   Fts3Table *p,                   /* Virtual table handle */
128919   int eStmt,                      /* One of the SQL_XXX constants above */
128920   sqlite3_stmt **pp,              /* OUT: Statement handle */
128921   sqlite3_value **apVal           /* Values to bind to statement */
128922 ){
128923   const char *azSql[] = {
128924 /* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
128925 /* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
128926 /* 2  */  "DELETE FROM %Q.'%q_content'",
128927 /* 3  */  "DELETE FROM %Q.'%q_segments'",
128928 /* 4  */  "DELETE FROM %Q.'%q_segdir'",
128929 /* 5  */  "DELETE FROM %Q.'%q_docsize'",
128930 /* 6  */  "DELETE FROM %Q.'%q_stat'",
128931 /* 7  */  "SELECT %s WHERE rowid=?",
128932 /* 8  */  "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
128933 /* 9  */  "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
128934 /* 10 */  "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
128935 /* 11 */  "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
128936
128937           /* Return segments in order from oldest to newest.*/ 
128938 /* 12 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
128939             "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
128940 /* 13 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
128941             "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
128942             "ORDER BY level DESC, idx ASC",
128943
128944 /* 14 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
128945 /* 15 */  "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
128946
128947 /* 16 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
128948 /* 17 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
128949 /* 18 */  "INSERT INTO %Q.'%q_content' VALUES(%s)",
128950 /* 19 */  "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
128951 /* 20 */  "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
128952 /* 21 */  "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
128953 /* 22 */  "SELECT value FROM %Q.'%q_stat' WHERE id=?",
128954 /* 23 */  "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
128955 /* 24 */  "",
128956 /* 25 */  "",
128957
128958 /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
128959 /* 27 */ "SELECT DISTINCT level / (1024 * ?) FROM %Q.'%q_segdir'",
128960
128961 /* This statement is used to determine which level to read the input from
128962 ** when performing an incremental merge. It returns the absolute level number
128963 ** of the oldest level in the db that contains at least ? segments. Or,
128964 ** if no level in the FTS index contains more than ? segments, the statement
128965 ** returns zero rows.  */
128966 /* 28 */ "SELECT level FROM %Q.'%q_segdir' GROUP BY level HAVING count(*)>=?"
128967          "  ORDER BY (level %% 1024) ASC LIMIT 1",
128968
128969 /* Estimate the upper limit on the number of leaf nodes in a new segment
128970 ** created by merging the oldest :2 segments from absolute level :1. See 
128971 ** function sqlite3Fts3Incrmerge() for details.  */
128972 /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
128973          "  FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
128974
128975 /* SQL_DELETE_SEGDIR_ENTRY
128976 **   Delete the %_segdir entry on absolute level :1 with index :2.  */
128977 /* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
128978
128979 /* SQL_SHIFT_SEGDIR_ENTRY
128980 **   Modify the idx value for the segment with idx=:3 on absolute level :2
128981 **   to :1.  */
128982 /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
128983
128984 /* SQL_SELECT_SEGDIR
128985 **   Read a single entry from the %_segdir table. The entry from absolute 
128986 **   level :1 with index value :2.  */
128987 /* 32 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
128988             "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
128989
128990 /* SQL_CHOMP_SEGDIR
128991 **   Update the start_block (:1) and root (:2) fields of the %_segdir
128992 **   entry located on absolute level :3 with index :4.  */
128993 /* 33 */  "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
128994             "WHERE level = ? AND idx = ?",
128995
128996 /* SQL_SEGMENT_IS_APPENDABLE
128997 **   Return a single row if the segment with end_block=? is appendable. Or
128998 **   no rows otherwise.  */
128999 /* 34 */  "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
129000
129001 /* SQL_SELECT_INDEXES
129002 **   Return the list of valid segment indexes for absolute level ?  */
129003 /* 35 */  "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
129004
129005 /* SQL_SELECT_MXLEVEL
129006 **   Return the largest relative level in the FTS index or indexes.  */
129007 /* 36 */  "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'"
129008   };
129009   int rc = SQLITE_OK;
129010   sqlite3_stmt *pStmt;
129011
129012   assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
129013   assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
129014   
129015   pStmt = p->aStmt[eStmt];
129016   if( !pStmt ){
129017     char *zSql;
129018     if( eStmt==SQL_CONTENT_INSERT ){
129019       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
129020     }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
129021       zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
129022     }else{
129023       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
129024     }
129025     if( !zSql ){
129026       rc = SQLITE_NOMEM;
129027     }else{
129028       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
129029       sqlite3_free(zSql);
129030       assert( rc==SQLITE_OK || pStmt==0 );
129031       p->aStmt[eStmt] = pStmt;
129032     }
129033   }
129034   if( apVal ){
129035     int i;
129036     int nParam = sqlite3_bind_parameter_count(pStmt);
129037     for(i=0; rc==SQLITE_OK && i<nParam; i++){
129038       rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
129039     }
129040   }
129041   *pp = pStmt;
129042   return rc;
129043 }
129044
129045
129046 static int fts3SelectDocsize(
129047   Fts3Table *pTab,                /* FTS3 table handle */
129048   sqlite3_int64 iDocid,           /* Docid to bind for SQL_SELECT_DOCSIZE */
129049   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
129050 ){
129051   sqlite3_stmt *pStmt = 0;        /* Statement requested from fts3SqlStmt() */
129052   int rc;                         /* Return code */
129053
129054   rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
129055   if( rc==SQLITE_OK ){
129056     sqlite3_bind_int64(pStmt, 1, iDocid);
129057     rc = sqlite3_step(pStmt);
129058     if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
129059       rc = sqlite3_reset(pStmt);
129060       if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
129061       pStmt = 0;
129062     }else{
129063       rc = SQLITE_OK;
129064     }
129065   }
129066
129067   *ppStmt = pStmt;
129068   return rc;
129069 }
129070
129071 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
129072   Fts3Table *pTab,                /* Fts3 table handle */
129073   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
129074 ){
129075   sqlite3_stmt *pStmt = 0;
129076   int rc;
129077   rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
129078   if( rc==SQLITE_OK ){
129079     sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
129080     if( sqlite3_step(pStmt)!=SQLITE_ROW
129081      || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
129082     ){
129083       rc = sqlite3_reset(pStmt);
129084       if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
129085       pStmt = 0;
129086     }
129087   }
129088   *ppStmt = pStmt;
129089   return rc;
129090 }
129091
129092 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
129093   Fts3Table *pTab,                /* Fts3 table handle */
129094   sqlite3_int64 iDocid,           /* Docid to read size data for */
129095   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
129096 ){
129097   return fts3SelectDocsize(pTab, iDocid, ppStmt);
129098 }
129099
129100 /*
129101 ** Similar to fts3SqlStmt(). Except, after binding the parameters in
129102 ** array apVal[] to the SQL statement identified by eStmt, the statement
129103 ** is executed.
129104 **
129105 ** Returns SQLITE_OK if the statement is successfully executed, or an
129106 ** SQLite error code otherwise.
129107 */
129108 static void fts3SqlExec(
129109   int *pRC,                /* Result code */
129110   Fts3Table *p,            /* The FTS3 table */
129111   int eStmt,               /* Index of statement to evaluate */
129112   sqlite3_value **apVal    /* Parameters to bind */
129113 ){
129114   sqlite3_stmt *pStmt;
129115   int rc;
129116   if( *pRC ) return;
129117   rc = fts3SqlStmt(p, eStmt, &pStmt, apVal); 
129118   if( rc==SQLITE_OK ){
129119     sqlite3_step(pStmt);
129120     rc = sqlite3_reset(pStmt);
129121   }
129122   *pRC = rc;
129123 }
129124
129125
129126 /*
129127 ** This function ensures that the caller has obtained a shared-cache
129128 ** table-lock on the %_content table. This is required before reading
129129 ** data from the fts3 table. If this lock is not acquired first, then
129130 ** the caller may end up holding read-locks on the %_segments and %_segdir
129131 ** tables, but no read-lock on the %_content table. If this happens 
129132 ** a second connection will be able to write to the fts3 table, but
129133 ** attempting to commit those writes might return SQLITE_LOCKED or
129134 ** SQLITE_LOCKED_SHAREDCACHE (because the commit attempts to obtain 
129135 ** write-locks on the %_segments and %_segdir ** tables). 
129136 **
129137 ** We try to avoid this because if FTS3 returns any error when committing
129138 ** a transaction, the whole transaction will be rolled back. And this is
129139 ** not what users expect when they get SQLITE_LOCKED_SHAREDCACHE. It can
129140 ** still happen if the user reads data directly from the %_segments or
129141 ** %_segdir tables instead of going through FTS3 though.
129142 **
129143 ** This reasoning does not apply to a content=xxx table.
129144 */
129145 SQLITE_PRIVATE int sqlite3Fts3ReadLock(Fts3Table *p){
129146   int rc;                         /* Return code */
129147   sqlite3_stmt *pStmt;            /* Statement used to obtain lock */
129148
129149   if( p->zContentTbl==0 ){
129150     rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pStmt, 0);
129151     if( rc==SQLITE_OK ){
129152       sqlite3_bind_null(pStmt, 1);
129153       sqlite3_step(pStmt);
129154       rc = sqlite3_reset(pStmt);
129155     }
129156   }else{
129157     rc = SQLITE_OK;
129158   }
129159
129160   return rc;
129161 }
129162
129163 /*
129164 ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
129165 ** Within each language id, a separate index is maintained to store the
129166 ** document terms, and each configured prefix size (configured the FTS 
129167 ** "prefix=" option). And each index consists of multiple levels ("relative
129168 ** levels").
129169 **
129170 ** All three of these values (the language id, the specific index and the
129171 ** level within the index) are encoded in 64-bit integer values stored
129172 ** in the %_segdir table on disk. This function is used to convert three
129173 ** separate component values into the single 64-bit integer value that
129174 ** can be used to query the %_segdir table.
129175 **
129176 ** Specifically, each language-id/index combination is allocated 1024 
129177 ** 64-bit integer level values ("absolute levels"). The main terms index
129178 ** for language-id 0 is allocate values 0-1023. The first prefix index
129179 ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
129180 ** Language 1 indexes are allocated immediately following language 0.
129181 **
129182 ** So, for a system with nPrefix prefix indexes configured, the block of
129183 ** absolute levels that corresponds to language-id iLangid and index 
129184 ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
129185 */
129186 static sqlite3_int64 getAbsoluteLevel(
129187   Fts3Table *p,                   /* FTS3 table handle */
129188   int iLangid,                    /* Language id */
129189   int iIndex,                     /* Index in p->aIndex[] */
129190   int iLevel                      /* Level of segments */
129191 ){
129192   sqlite3_int64 iBase;            /* First absolute level for iLangid/iIndex */
129193   assert( iLangid>=0 );
129194   assert( p->nIndex>0 );
129195   assert( iIndex>=0 && iIndex<p->nIndex );
129196
129197   iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
129198   return iBase + iLevel;
129199 }
129200
129201 /*
129202 ** Set *ppStmt to a statement handle that may be used to iterate through
129203 ** all rows in the %_segdir table, from oldest to newest. If successful,
129204 ** return SQLITE_OK. If an error occurs while preparing the statement, 
129205 ** return an SQLite error code.
129206 **
129207 ** There is only ever one instance of this SQL statement compiled for
129208 ** each FTS3 table.
129209 **
129210 ** The statement returns the following columns from the %_segdir table:
129211 **
129212 **   0: idx
129213 **   1: start_block
129214 **   2: leaves_end_block
129215 **   3: end_block
129216 **   4: root
129217 */
129218 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
129219   Fts3Table *p,                   /* FTS3 table */
129220   int iLangid,                    /* Language being queried */
129221   int iIndex,                     /* Index for p->aIndex[] */
129222   int iLevel,                     /* Level to select (relative level) */
129223   sqlite3_stmt **ppStmt           /* OUT: Compiled statement */
129224 ){
129225   int rc;
129226   sqlite3_stmt *pStmt = 0;
129227
129228   assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
129229   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
129230   assert( iIndex>=0 && iIndex<p->nIndex );
129231
129232   if( iLevel<0 ){
129233     /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
129234     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
129235     if( rc==SQLITE_OK ){ 
129236       sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
129237       sqlite3_bind_int64(pStmt, 2, 
129238           getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
129239       );
129240     }
129241   }else{
129242     /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
129243     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
129244     if( rc==SQLITE_OK ){ 
129245       sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
129246     }
129247   }
129248   *ppStmt = pStmt;
129249   return rc;
129250 }
129251
129252
129253 /*
129254 ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
129255 ** if successful, or an SQLite error code otherwise.
129256 **
129257 ** This function also serves to allocate the PendingList structure itself.
129258 ** For example, to create a new PendingList structure containing two
129259 ** varints:
129260 **
129261 **   PendingList *p = 0;
129262 **   fts3PendingListAppendVarint(&p, 1);
129263 **   fts3PendingListAppendVarint(&p, 2);
129264 */
129265 static int fts3PendingListAppendVarint(
129266   PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
129267   sqlite3_int64 i                 /* Value to append to data */
129268 ){
129269   PendingList *p = *pp;
129270
129271   /* Allocate or grow the PendingList as required. */
129272   if( !p ){
129273     p = sqlite3_malloc(sizeof(*p) + 100);
129274     if( !p ){
129275       return SQLITE_NOMEM;
129276     }
129277     p->nSpace = 100;
129278     p->aData = (char *)&p[1];
129279     p->nData = 0;
129280   }
129281   else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
129282     int nNew = p->nSpace * 2;
129283     p = sqlite3_realloc(p, sizeof(*p) + nNew);
129284     if( !p ){
129285       sqlite3_free(*pp);
129286       *pp = 0;
129287       return SQLITE_NOMEM;
129288     }
129289     p->nSpace = nNew;
129290     p->aData = (char *)&p[1];
129291   }
129292
129293   /* Append the new serialized varint to the end of the list. */
129294   p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
129295   p->aData[p->nData] = '\0';
129296   *pp = p;
129297   return SQLITE_OK;
129298 }
129299
129300 /*
129301 ** Add a docid/column/position entry to a PendingList structure. Non-zero
129302 ** is returned if the structure is sqlite3_realloced as part of adding
129303 ** the entry. Otherwise, zero.
129304 **
129305 ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
129306 ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
129307 ** it is set to SQLITE_OK.
129308 */
129309 static int fts3PendingListAppend(
129310   PendingList **pp,               /* IN/OUT: PendingList structure */
129311   sqlite3_int64 iDocid,           /* Docid for entry to add */
129312   sqlite3_int64 iCol,             /* Column for entry to add */
129313   sqlite3_int64 iPos,             /* Position of term for entry to add */
129314   int *pRc                        /* OUT: Return code */
129315 ){
129316   PendingList *p = *pp;
129317   int rc = SQLITE_OK;
129318
129319   assert( !p || p->iLastDocid<=iDocid );
129320
129321   if( !p || p->iLastDocid!=iDocid ){
129322     sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
129323     if( p ){
129324       assert( p->nData<p->nSpace );
129325       assert( p->aData[p->nData]==0 );
129326       p->nData++;
129327     }
129328     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
129329       goto pendinglistappend_out;
129330     }
129331     p->iLastCol = -1;
129332     p->iLastPos = 0;
129333     p->iLastDocid = iDocid;
129334   }
129335   if( iCol>0 && p->iLastCol!=iCol ){
129336     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
129337      || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
129338     ){
129339       goto pendinglistappend_out;
129340     }
129341     p->iLastCol = iCol;
129342     p->iLastPos = 0;
129343   }
129344   if( iCol>=0 ){
129345     assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
129346     rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
129347     if( rc==SQLITE_OK ){
129348       p->iLastPos = iPos;
129349     }
129350   }
129351
129352  pendinglistappend_out:
129353   *pRc = rc;
129354   if( p!=*pp ){
129355     *pp = p;
129356     return 1;
129357   }
129358   return 0;
129359 }
129360
129361 /*
129362 ** Free a PendingList object allocated by fts3PendingListAppend().
129363 */
129364 static void fts3PendingListDelete(PendingList *pList){
129365   sqlite3_free(pList);
129366 }
129367
129368 /*
129369 ** Add an entry to one of the pending-terms hash tables.
129370 */
129371 static int fts3PendingTermsAddOne(
129372   Fts3Table *p,
129373   int iCol,
129374   int iPos,
129375   Fts3Hash *pHash,                /* Pending terms hash table to add entry to */
129376   const char *zToken,
129377   int nToken
129378 ){
129379   PendingList *pList;
129380   int rc = SQLITE_OK;
129381
129382   pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
129383   if( pList ){
129384     p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
129385   }
129386   if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
129387     if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
129388       /* Malloc failed while inserting the new entry. This can only 
129389       ** happen if there was no previous entry for this token.
129390       */
129391       assert( 0==fts3HashFind(pHash, zToken, nToken) );
129392       sqlite3_free(pList);
129393       rc = SQLITE_NOMEM;
129394     }
129395   }
129396   if( rc==SQLITE_OK ){
129397     p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
129398   }
129399   return rc;
129400 }
129401
129402 /*
129403 ** Tokenize the nul-terminated string zText and add all tokens to the
129404 ** pending-terms hash-table. The docid used is that currently stored in
129405 ** p->iPrevDocid, and the column is specified by argument iCol.
129406 **
129407 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
129408 */
129409 static int fts3PendingTermsAdd(
129410   Fts3Table *p,                   /* Table into which text will be inserted */
129411   int iLangid,                    /* Language id to use */
129412   const char *zText,              /* Text of document to be inserted */
129413   int iCol,                       /* Column into which text is being inserted */
129414   u32 *pnWord                     /* IN/OUT: Incr. by number tokens inserted */
129415 ){
129416   int rc;
129417   int iStart = 0;
129418   int iEnd = 0;
129419   int iPos = 0;
129420   int nWord = 0;
129421
129422   char const *zToken;
129423   int nToken = 0;
129424
129425   sqlite3_tokenizer *pTokenizer = p->pTokenizer;
129426   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
129427   sqlite3_tokenizer_cursor *pCsr;
129428   int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
129429       const char**,int*,int*,int*,int*);
129430
129431   assert( pTokenizer && pModule );
129432
129433   /* If the user has inserted a NULL value, this function may be called with
129434   ** zText==0. In this case, add zero token entries to the hash table and 
129435   ** return early. */
129436   if( zText==0 ){
129437     *pnWord = 0;
129438     return SQLITE_OK;
129439   }
129440
129441   rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
129442   if( rc!=SQLITE_OK ){
129443     return rc;
129444   }
129445
129446   xNext = pModule->xNext;
129447   while( SQLITE_OK==rc
129448       && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
129449   ){
129450     int i;
129451     if( iPos>=nWord ) nWord = iPos+1;
129452
129453     /* Positions cannot be negative; we use -1 as a terminator internally.
129454     ** Tokens must have a non-zero length.
129455     */
129456     if( iPos<0 || !zToken || nToken<=0 ){
129457       rc = SQLITE_ERROR;
129458       break;
129459     }
129460
129461     /* Add the term to the terms index */
129462     rc = fts3PendingTermsAddOne(
129463         p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
129464     );
129465     
129466     /* Add the term to each of the prefix indexes that it is not too 
129467     ** short for. */
129468     for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
129469       struct Fts3Index *pIndex = &p->aIndex[i];
129470       if( nToken<pIndex->nPrefix ) continue;
129471       rc = fts3PendingTermsAddOne(
129472           p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
129473       );
129474     }
129475   }
129476
129477   pModule->xClose(pCsr);
129478   *pnWord += nWord;
129479   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
129480 }
129481
129482 /* 
129483 ** Calling this function indicates that subsequent calls to 
129484 ** fts3PendingTermsAdd() are to add term/position-list pairs for the
129485 ** contents of the document with docid iDocid.
129486 */
129487 static int fts3PendingTermsDocid(
129488   Fts3Table *p,                   /* Full-text table handle */
129489   int iLangid,                    /* Language id of row being written */
129490   sqlite_int64 iDocid             /* Docid of row being written */
129491 ){
129492   assert( iLangid>=0 );
129493
129494   /* TODO(shess) Explore whether partially flushing the buffer on
129495   ** forced-flush would provide better performance.  I suspect that if
129496   ** we ordered the doclists by size and flushed the largest until the
129497   ** buffer was half empty, that would let the less frequent terms
129498   ** generate longer doclists.
129499   */
129500   if( iDocid<=p->iPrevDocid 
129501    || p->iPrevLangid!=iLangid
129502    || p->nPendingData>p->nMaxPendingData 
129503   ){
129504     int rc = sqlite3Fts3PendingTermsFlush(p);
129505     if( rc!=SQLITE_OK ) return rc;
129506   }
129507   p->iPrevDocid = iDocid;
129508   p->iPrevLangid = iLangid;
129509   return SQLITE_OK;
129510 }
129511
129512 /*
129513 ** Discard the contents of the pending-terms hash tables. 
129514 */
129515 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
129516   int i;
129517   for(i=0; i<p->nIndex; i++){
129518     Fts3HashElem *pElem;
129519     Fts3Hash *pHash = &p->aIndex[i].hPending;
129520     for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
129521       PendingList *pList = (PendingList *)fts3HashData(pElem);
129522       fts3PendingListDelete(pList);
129523     }
129524     fts3HashClear(pHash);
129525   }
129526   p->nPendingData = 0;
129527 }
129528
129529 /*
129530 ** This function is called by the xUpdate() method as part of an INSERT
129531 ** operation. It adds entries for each term in the new record to the
129532 ** pendingTerms hash table.
129533 **
129534 ** Argument apVal is the same as the similarly named argument passed to
129535 ** fts3InsertData(). Parameter iDocid is the docid of the new row.
129536 */
129537 static int fts3InsertTerms(
129538   Fts3Table *p, 
129539   int iLangid, 
129540   sqlite3_value **apVal, 
129541   u32 *aSz
129542 ){
129543   int i;                          /* Iterator variable */
129544   for(i=2; i<p->nColumn+2; i++){
129545     const char *zText = (const char *)sqlite3_value_text(apVal[i]);
129546     int rc = fts3PendingTermsAdd(p, iLangid, zText, i-2, &aSz[i-2]);
129547     if( rc!=SQLITE_OK ){
129548       return rc;
129549     }
129550     aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
129551   }
129552   return SQLITE_OK;
129553 }
129554
129555 /*
129556 ** This function is called by the xUpdate() method for an INSERT operation.
129557 ** The apVal parameter is passed a copy of the apVal argument passed by
129558 ** SQLite to the xUpdate() method. i.e:
129559 **
129560 **   apVal[0]                Not used for INSERT.
129561 **   apVal[1]                rowid
129562 **   apVal[2]                Left-most user-defined column
129563 **   ...
129564 **   apVal[p->nColumn+1]     Right-most user-defined column
129565 **   apVal[p->nColumn+2]     Hidden column with same name as table
129566 **   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
129567 **   apVal[p->nColumn+4]     Hidden languageid column
129568 */
129569 static int fts3InsertData(
129570   Fts3Table *p,                   /* Full-text table */
129571   sqlite3_value **apVal,          /* Array of values to insert */
129572   sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */
129573 ){
129574   int rc;                         /* Return code */
129575   sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
129576
129577   if( p->zContentTbl ){
129578     sqlite3_value *pRowid = apVal[p->nColumn+3];
129579     if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
129580       pRowid = apVal[1];
129581     }
129582     if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
129583       return SQLITE_CONSTRAINT;
129584     }
129585     *piDocid = sqlite3_value_int64(pRowid);
129586     return SQLITE_OK;
129587   }
129588
129589   /* Locate the statement handle used to insert data into the %_content
129590   ** table. The SQL for this statement is:
129591   **
129592   **   INSERT INTO %_content VALUES(?, ?, ?, ...)
129593   **
129594   ** The statement features N '?' variables, where N is the number of user
129595   ** defined columns in the FTS3 table, plus one for the docid field.
129596   */
129597   rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
129598   if( rc==SQLITE_OK && p->zLanguageid ){
129599     rc = sqlite3_bind_int(
129600         pContentInsert, p->nColumn+2, 
129601         sqlite3_value_int(apVal[p->nColumn+4])
129602     );
129603   }
129604   if( rc!=SQLITE_OK ) return rc;
129605
129606   /* There is a quirk here. The users INSERT statement may have specified
129607   ** a value for the "rowid" field, for the "docid" field, or for both.
129608   ** Which is a problem, since "rowid" and "docid" are aliases for the
129609   ** same value. For example:
129610   **
129611   **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
129612   **
129613   ** In FTS3, this is an error. It is an error to specify non-NULL values
129614   ** for both docid and some other rowid alias.
129615   */
129616   if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
129617     if( SQLITE_NULL==sqlite3_value_type(apVal[0])
129618      && SQLITE_NULL!=sqlite3_value_type(apVal[1])
129619     ){
129620       /* A rowid/docid conflict. */
129621       return SQLITE_ERROR;
129622     }
129623     rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
129624     if( rc!=SQLITE_OK ) return rc;
129625   }
129626
129627   /* Execute the statement to insert the record. Set *piDocid to the 
129628   ** new docid value. 
129629   */
129630   sqlite3_step(pContentInsert);
129631   rc = sqlite3_reset(pContentInsert);
129632
129633   *piDocid = sqlite3_last_insert_rowid(p->db);
129634   return rc;
129635 }
129636
129637
129638
129639 /*
129640 ** Remove all data from the FTS3 table. Clear the hash table containing
129641 ** pending terms.
129642 */
129643 static int fts3DeleteAll(Fts3Table *p, int bContent){
129644   int rc = SQLITE_OK;             /* Return code */
129645
129646   /* Discard the contents of the pending-terms hash table. */
129647   sqlite3Fts3PendingTermsClear(p);
129648
129649   /* Delete everything from the shadow tables. Except, leave %_content as
129650   ** is if bContent is false.  */
129651   assert( p->zContentTbl==0 || bContent==0 );
129652   if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
129653   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
129654   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
129655   if( p->bHasDocsize ){
129656     fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
129657   }
129658   if( p->bHasStat ){
129659     fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
129660   }
129661   return rc;
129662 }
129663
129664 /*
129665 **
129666 */
129667 static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
129668   int iLangid = 0;
129669   if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
129670   return iLangid;
129671 }
129672
129673 /*
129674 ** The first element in the apVal[] array is assumed to contain the docid
129675 ** (an integer) of a row about to be deleted. Remove all terms from the
129676 ** full-text index.
129677 */
129678 static void fts3DeleteTerms( 
129679   int *pRC,               /* Result code */
129680   Fts3Table *p,           /* The FTS table to delete from */
129681   sqlite3_value *pRowid,  /* The docid to be deleted */
129682   u32 *aSz,               /* Sizes of deleted document written here */
129683   int *pbFound            /* OUT: Set to true if row really does exist */
129684 ){
129685   int rc;
129686   sqlite3_stmt *pSelect;
129687
129688   assert( *pbFound==0 );
129689   if( *pRC ) return;
129690   rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
129691   if( rc==SQLITE_OK ){
129692     if( SQLITE_ROW==sqlite3_step(pSelect) ){
129693       int i;
129694       int iLangid = langidFromSelect(p, pSelect);
129695       rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pSelect, 0));
129696       for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
129697         const char *zText = (const char *)sqlite3_column_text(pSelect, i);
129698         rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[i-1]);
129699         aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
129700       }
129701       if( rc!=SQLITE_OK ){
129702         sqlite3_reset(pSelect);
129703         *pRC = rc;
129704         return;
129705       }
129706       *pbFound = 1;
129707     }
129708     rc = sqlite3_reset(pSelect);
129709   }else{
129710     sqlite3_reset(pSelect);
129711   }
129712   *pRC = rc;
129713 }
129714
129715 /*
129716 ** Forward declaration to account for the circular dependency between
129717 ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
129718 */
129719 static int fts3SegmentMerge(Fts3Table *, int, int, int);
129720
129721 /* 
129722 ** This function allocates a new level iLevel index in the segdir table.
129723 ** Usually, indexes are allocated within a level sequentially starting
129724 ** with 0, so the allocated index is one greater than the value returned
129725 ** by:
129726 **
129727 **   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
129728 **
129729 ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
129730 ** level, they are merged into a single level (iLevel+1) segment and the 
129731 ** allocated index is 0.
129732 **
129733 ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
129734 ** returned. Otherwise, an SQLite error code is returned.
129735 */
129736 static int fts3AllocateSegdirIdx(
129737   Fts3Table *p, 
129738   int iLangid,                    /* Language id */
129739   int iIndex,                     /* Index for p->aIndex */
129740   int iLevel, 
129741   int *piIdx
129742 ){
129743   int rc;                         /* Return Code */
129744   sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
129745   int iNext = 0;                  /* Result of query pNextIdx */
129746
129747   assert( iLangid>=0 );
129748   assert( p->nIndex>=1 );
129749
129750   /* Set variable iNext to the next available segdir index at level iLevel. */
129751   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
129752   if( rc==SQLITE_OK ){
129753     sqlite3_bind_int64(
129754         pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
129755     );
129756     if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
129757       iNext = sqlite3_column_int(pNextIdx, 0);
129758     }
129759     rc = sqlite3_reset(pNextIdx);
129760   }
129761
129762   if( rc==SQLITE_OK ){
129763     /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
129764     ** full, merge all segments in level iLevel into a single iLevel+1
129765     ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
129766     ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
129767     */
129768     if( iNext>=FTS3_MERGE_COUNT ){
129769       fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
129770       rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
129771       *piIdx = 0;
129772     }else{
129773       *piIdx = iNext;
129774     }
129775   }
129776
129777   return rc;
129778 }
129779
129780 /*
129781 ** The %_segments table is declared as follows:
129782 **
129783 **   CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
129784 **
129785 ** This function reads data from a single row of the %_segments table. The
129786 ** specific row is identified by the iBlockid parameter. If paBlob is not
129787 ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
129788 ** with the contents of the blob stored in the "block" column of the 
129789 ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
129790 ** to the size of the blob in bytes before returning.
129791 **
129792 ** If an error occurs, or the table does not contain the specified row,
129793 ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
129794 ** paBlob is non-NULL, then it is the responsibility of the caller to
129795 ** eventually free the returned buffer.
129796 **
129797 ** This function may leave an open sqlite3_blob* handle in the
129798 ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
129799 ** to this function. The handle may be closed by calling the
129800 ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
129801 ** performance improvement, but the blob handle should always be closed
129802 ** before control is returned to the user (to prevent a lock being held
129803 ** on the database file for longer than necessary). Thus, any virtual table
129804 ** method (xFilter etc.) that may directly or indirectly call this function
129805 ** must call sqlite3Fts3SegmentsClose() before returning.
129806 */
129807 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
129808   Fts3Table *p,                   /* FTS3 table handle */
129809   sqlite3_int64 iBlockid,         /* Access the row with blockid=$iBlockid */
129810   char **paBlob,                  /* OUT: Blob data in malloc'd buffer */
129811   int *pnBlob,                    /* OUT: Size of blob data */
129812   int *pnLoad                     /* OUT: Bytes actually loaded */
129813 ){
129814   int rc;                         /* Return code */
129815
129816   /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
129817   assert( pnBlob );
129818
129819   if( p->pSegments ){
129820     rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
129821   }else{
129822     if( 0==p->zSegmentsTbl ){
129823       p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
129824       if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
129825     }
129826     rc = sqlite3_blob_open(
129827        p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
129828     );
129829   }
129830
129831   if( rc==SQLITE_OK ){
129832     int nByte = sqlite3_blob_bytes(p->pSegments);
129833     *pnBlob = nByte;
129834     if( paBlob ){
129835       char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
129836       if( !aByte ){
129837         rc = SQLITE_NOMEM;
129838       }else{
129839         if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
129840           nByte = FTS3_NODE_CHUNKSIZE;
129841           *pnLoad = nByte;
129842         }
129843         rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
129844         memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
129845         if( rc!=SQLITE_OK ){
129846           sqlite3_free(aByte);
129847           aByte = 0;
129848         }
129849       }
129850       *paBlob = aByte;
129851     }
129852   }
129853
129854   return rc;
129855 }
129856
129857 /*
129858 ** Close the blob handle at p->pSegments, if it is open. See comments above
129859 ** the sqlite3Fts3ReadBlock() function for details.
129860 */
129861 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
129862   sqlite3_blob_close(p->pSegments);
129863   p->pSegments = 0;
129864 }
129865     
129866 static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
129867   int nRead;                      /* Number of bytes to read */
129868   int rc;                         /* Return code */
129869
129870   nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
129871   rc = sqlite3_blob_read(
129872       pReader->pBlob, 
129873       &pReader->aNode[pReader->nPopulate],
129874       nRead,
129875       pReader->nPopulate
129876   );
129877
129878   if( rc==SQLITE_OK ){
129879     pReader->nPopulate += nRead;
129880     memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
129881     if( pReader->nPopulate==pReader->nNode ){
129882       sqlite3_blob_close(pReader->pBlob);
129883       pReader->pBlob = 0;
129884       pReader->nPopulate = 0;
129885     }
129886   }
129887   return rc;
129888 }
129889
129890 static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
129891   int rc = SQLITE_OK;
129892   assert( !pReader->pBlob 
129893        || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
129894   );
129895   while( pReader->pBlob && rc==SQLITE_OK 
129896      &&  (pFrom - pReader->aNode + nByte)>pReader->nPopulate
129897   ){
129898     rc = fts3SegReaderIncrRead(pReader);
129899   }
129900   return rc;
129901 }
129902
129903 /*
129904 ** Set an Fts3SegReader cursor to point at EOF.
129905 */
129906 static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
129907   if( !fts3SegReaderIsRootOnly(pSeg) ){
129908     sqlite3_free(pSeg->aNode);
129909     sqlite3_blob_close(pSeg->pBlob);
129910     pSeg->pBlob = 0;
129911   }
129912   pSeg->aNode = 0;
129913 }
129914
129915 /*
129916 ** Move the iterator passed as the first argument to the next term in the
129917 ** segment. If successful, SQLITE_OK is returned. If there is no next term,
129918 ** SQLITE_DONE. Otherwise, an SQLite error code.
129919 */
129920 static int fts3SegReaderNext(
129921   Fts3Table *p, 
129922   Fts3SegReader *pReader,
129923   int bIncr
129924 ){
129925   int rc;                         /* Return code of various sub-routines */
129926   char *pNext;                    /* Cursor variable */
129927   int nPrefix;                    /* Number of bytes in term prefix */
129928   int nSuffix;                    /* Number of bytes in term suffix */
129929
129930   if( !pReader->aDoclist ){
129931     pNext = pReader->aNode;
129932   }else{
129933     pNext = &pReader->aDoclist[pReader->nDoclist];
129934   }
129935
129936   if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
129937
129938     if( fts3SegReaderIsPending(pReader) ){
129939       Fts3HashElem *pElem = *(pReader->ppNextElem);
129940       if( pElem==0 ){
129941         pReader->aNode = 0;
129942       }else{
129943         PendingList *pList = (PendingList *)fts3HashData(pElem);
129944         pReader->zTerm = (char *)fts3HashKey(pElem);
129945         pReader->nTerm = fts3HashKeysize(pElem);
129946         pReader->nNode = pReader->nDoclist = pList->nData + 1;
129947         pReader->aNode = pReader->aDoclist = pList->aData;
129948         pReader->ppNextElem++;
129949         assert( pReader->aNode );
129950       }
129951       return SQLITE_OK;
129952     }
129953
129954     fts3SegReaderSetEof(pReader);
129955
129956     /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf 
129957     ** blocks have already been traversed.  */
129958     assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
129959     if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
129960       return SQLITE_OK;
129961     }
129962
129963     rc = sqlite3Fts3ReadBlock(
129964         p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode, 
129965         (bIncr ? &pReader->nPopulate : 0)
129966     );
129967     if( rc!=SQLITE_OK ) return rc;
129968     assert( pReader->pBlob==0 );
129969     if( bIncr && pReader->nPopulate<pReader->nNode ){
129970       pReader->pBlob = p->pSegments;
129971       p->pSegments = 0;
129972     }
129973     pNext = pReader->aNode;
129974   }
129975
129976   assert( !fts3SegReaderIsPending(pReader) );
129977
129978   rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
129979   if( rc!=SQLITE_OK ) return rc;
129980   
129981   /* Because of the FTS3_NODE_PADDING bytes of padding, the following is 
129982   ** safe (no risk of overread) even if the node data is corrupted. */
129983   pNext += sqlite3Fts3GetVarint32(pNext, &nPrefix);
129984   pNext += sqlite3Fts3GetVarint32(pNext, &nSuffix);
129985   if( nPrefix<0 || nSuffix<=0 
129986    || &pNext[nSuffix]>&pReader->aNode[pReader->nNode] 
129987   ){
129988     return FTS_CORRUPT_VTAB;
129989   }
129990
129991   if( nPrefix+nSuffix>pReader->nTermAlloc ){
129992     int nNew = (nPrefix+nSuffix)*2;
129993     char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
129994     if( !zNew ){
129995       return SQLITE_NOMEM;
129996     }
129997     pReader->zTerm = zNew;
129998     pReader->nTermAlloc = nNew;
129999   }
130000
130001   rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
130002   if( rc!=SQLITE_OK ) return rc;
130003
130004   memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
130005   pReader->nTerm = nPrefix+nSuffix;
130006   pNext += nSuffix;
130007   pNext += sqlite3Fts3GetVarint32(pNext, &pReader->nDoclist);
130008   pReader->aDoclist = pNext;
130009   pReader->pOffsetList = 0;
130010
130011   /* Check that the doclist does not appear to extend past the end of the
130012   ** b-tree node. And that the final byte of the doclist is 0x00. If either 
130013   ** of these statements is untrue, then the data structure is corrupt.
130014   */
130015   if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode] 
130016    || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
130017   ){
130018     return FTS_CORRUPT_VTAB;
130019   }
130020   return SQLITE_OK;
130021 }
130022
130023 /*
130024 ** Set the SegReader to point to the first docid in the doclist associated
130025 ** with the current term.
130026 */
130027 static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
130028   int rc = SQLITE_OK;
130029   assert( pReader->aDoclist );
130030   assert( !pReader->pOffsetList );
130031   if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
130032     u8 bEof = 0;
130033     pReader->iDocid = 0;
130034     pReader->nOffsetList = 0;
130035     sqlite3Fts3DoclistPrev(0,
130036         pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList, 
130037         &pReader->iDocid, &pReader->nOffsetList, &bEof
130038     );
130039   }else{
130040     rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
130041     if( rc==SQLITE_OK ){
130042       int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
130043       pReader->pOffsetList = &pReader->aDoclist[n];
130044     }
130045   }
130046   return rc;
130047 }
130048
130049 /*
130050 ** Advance the SegReader to point to the next docid in the doclist
130051 ** associated with the current term.
130052 ** 
130053 ** If arguments ppOffsetList and pnOffsetList are not NULL, then 
130054 ** *ppOffsetList is set to point to the first column-offset list
130055 ** in the doclist entry (i.e. immediately past the docid varint).
130056 ** *pnOffsetList is set to the length of the set of column-offset
130057 ** lists, not including the nul-terminator byte. For example:
130058 */
130059 static int fts3SegReaderNextDocid(
130060   Fts3Table *pTab,
130061   Fts3SegReader *pReader,         /* Reader to advance to next docid */
130062   char **ppOffsetList,            /* OUT: Pointer to current position-list */
130063   int *pnOffsetList               /* OUT: Length of *ppOffsetList in bytes */
130064 ){
130065   int rc = SQLITE_OK;
130066   char *p = pReader->pOffsetList;
130067   char c = 0;
130068
130069   assert( p );
130070
130071   if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
130072     /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
130073     ** Pending-terms doclists are always built up in ascending order, so
130074     ** we have to iterate through them backwards here. */
130075     u8 bEof = 0;
130076     if( ppOffsetList ){
130077       *ppOffsetList = pReader->pOffsetList;
130078       *pnOffsetList = pReader->nOffsetList - 1;
130079     }
130080     sqlite3Fts3DoclistPrev(0,
130081         pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
130082         &pReader->nOffsetList, &bEof
130083     );
130084     if( bEof ){
130085       pReader->pOffsetList = 0;
130086     }else{
130087       pReader->pOffsetList = p;
130088     }
130089   }else{
130090     char *pEnd = &pReader->aDoclist[pReader->nDoclist];
130091
130092     /* Pointer p currently points at the first byte of an offset list. The
130093     ** following block advances it to point one byte past the end of
130094     ** the same offset list. */
130095     while( 1 ){
130096   
130097       /* The following line of code (and the "p++" below the while() loop) is
130098       ** normally all that is required to move pointer p to the desired 
130099       ** position. The exception is if this node is being loaded from disk
130100       ** incrementally and pointer "p" now points to the first byte passed
130101       ** the populated part of pReader->aNode[].
130102       */
130103       while( *p | c ) c = *p++ & 0x80;
130104       assert( *p==0 );
130105   
130106       if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
130107       rc = fts3SegReaderIncrRead(pReader);
130108       if( rc!=SQLITE_OK ) return rc;
130109     }
130110     p++;
130111   
130112     /* If required, populate the output variables with a pointer to and the
130113     ** size of the previous offset-list.
130114     */
130115     if( ppOffsetList ){
130116       *ppOffsetList = pReader->pOffsetList;
130117       *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
130118     }
130119
130120     /* List may have been edited in place by fts3EvalNearTrim() */
130121     while( p<pEnd && *p==0 ) p++;
130122   
130123     /* If there are no more entries in the doclist, set pOffsetList to
130124     ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
130125     ** Fts3SegReader.pOffsetList to point to the next offset list before
130126     ** returning.
130127     */
130128     if( p>=pEnd ){
130129       pReader->pOffsetList = 0;
130130     }else{
130131       rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
130132       if( rc==SQLITE_OK ){
130133         sqlite3_int64 iDelta;
130134         pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
130135         if( pTab->bDescIdx ){
130136           pReader->iDocid -= iDelta;
130137         }else{
130138           pReader->iDocid += iDelta;
130139         }
130140       }
130141     }
130142   }
130143
130144   return SQLITE_OK;
130145 }
130146
130147
130148 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
130149   Fts3Cursor *pCsr, 
130150   Fts3MultiSegReader *pMsr,
130151   int *pnOvfl
130152 ){
130153   Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
130154   int nOvfl = 0;
130155   int ii;
130156   int rc = SQLITE_OK;
130157   int pgsz = p->nPgsz;
130158
130159   assert( p->bFts4 );
130160   assert( pgsz>0 );
130161
130162   for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
130163     Fts3SegReader *pReader = pMsr->apSegment[ii];
130164     if( !fts3SegReaderIsPending(pReader) 
130165      && !fts3SegReaderIsRootOnly(pReader) 
130166     ){
130167       sqlite3_int64 jj;
130168       for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
130169         int nBlob;
130170         rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
130171         if( rc!=SQLITE_OK ) break;
130172         if( (nBlob+35)>pgsz ){
130173           nOvfl += (nBlob + 34)/pgsz;
130174         }
130175       }
130176     }
130177   }
130178   *pnOvfl = nOvfl;
130179   return rc;
130180 }
130181
130182 /*
130183 ** Free all allocations associated with the iterator passed as the 
130184 ** second argument.
130185 */
130186 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
130187   if( pReader && !fts3SegReaderIsPending(pReader) ){
130188     sqlite3_free(pReader->zTerm);
130189     if( !fts3SegReaderIsRootOnly(pReader) ){
130190       sqlite3_free(pReader->aNode);
130191       sqlite3_blob_close(pReader->pBlob);
130192     }
130193   }
130194   sqlite3_free(pReader);
130195 }
130196
130197 /*
130198 ** Allocate a new SegReader object.
130199 */
130200 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
130201   int iAge,                       /* Segment "age". */
130202   int bLookup,                    /* True for a lookup only */
130203   sqlite3_int64 iStartLeaf,       /* First leaf to traverse */
130204   sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */
130205   sqlite3_int64 iEndBlock,        /* Final block of segment */
130206   const char *zRoot,              /* Buffer containing root node */
130207   int nRoot,                      /* Size of buffer containing root node */
130208   Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
130209 ){
130210   Fts3SegReader *pReader;         /* Newly allocated SegReader object */
130211   int nExtra = 0;                 /* Bytes to allocate segment root node */
130212
130213   assert( iStartLeaf<=iEndLeaf );
130214   if( iStartLeaf==0 ){
130215     nExtra = nRoot + FTS3_NODE_PADDING;
130216   }
130217
130218   pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
130219   if( !pReader ){
130220     return SQLITE_NOMEM;
130221   }
130222   memset(pReader, 0, sizeof(Fts3SegReader));
130223   pReader->iIdx = iAge;
130224   pReader->bLookup = bLookup!=0;
130225   pReader->iStartBlock = iStartLeaf;
130226   pReader->iLeafEndBlock = iEndLeaf;
130227   pReader->iEndBlock = iEndBlock;
130228
130229   if( nExtra ){
130230     /* The entire segment is stored in the root node. */
130231     pReader->aNode = (char *)&pReader[1];
130232     pReader->rootOnly = 1;
130233     pReader->nNode = nRoot;
130234     memcpy(pReader->aNode, zRoot, nRoot);
130235     memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
130236   }else{
130237     pReader->iCurrentBlock = iStartLeaf-1;
130238   }
130239   *ppReader = pReader;
130240   return SQLITE_OK;
130241 }
130242
130243 /*
130244 ** This is a comparison function used as a qsort() callback when sorting
130245 ** an array of pending terms by term. This occurs as part of flushing
130246 ** the contents of the pending-terms hash table to the database.
130247 */
130248 static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
130249   char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
130250   char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
130251   int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
130252   int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
130253
130254   int n = (n1<n2 ? n1 : n2);
130255   int c = memcmp(z1, z2, n);
130256   if( c==0 ){
130257     c = n1 - n2;
130258   }
130259   return c;
130260 }
130261
130262 /*
130263 ** This function is used to allocate an Fts3SegReader that iterates through
130264 ** a subset of the terms stored in the Fts3Table.pendingTerms array.
130265 **
130266 ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
130267 ** through each term in the pending-terms table. Or, if isPrefixIter is
130268 ** non-zero, it iterates through each term and its prefixes. For example, if
130269 ** the pending terms hash table contains the terms "sqlite", "mysql" and
130270 ** "firebird", then the iterator visits the following 'terms' (in the order
130271 ** shown):
130272 **
130273 **   f fi fir fire fireb firebi firebir firebird
130274 **   m my mys mysq mysql
130275 **   s sq sql sqli sqlit sqlite
130276 **
130277 ** Whereas if isPrefixIter is zero, the terms visited are:
130278 **
130279 **   firebird mysql sqlite
130280 */
130281 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
130282   Fts3Table *p,                   /* Virtual table handle */
130283   int iIndex,                     /* Index for p->aIndex */
130284   const char *zTerm,              /* Term to search for */
130285   int nTerm,                      /* Size of buffer zTerm */
130286   int bPrefix,                    /* True for a prefix iterator */
130287   Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
130288 ){
130289   Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
130290   Fts3HashElem *pE;               /* Iterator variable */
130291   Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
130292   int nElem = 0;                  /* Size of array at aElem */
130293   int rc = SQLITE_OK;             /* Return Code */
130294   Fts3Hash *pHash;
130295
130296   pHash = &p->aIndex[iIndex].hPending;
130297   if( bPrefix ){
130298     int nAlloc = 0;               /* Size of allocated array at aElem */
130299
130300     for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
130301       char *zKey = (char *)fts3HashKey(pE);
130302       int nKey = fts3HashKeysize(pE);
130303       if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
130304         if( nElem==nAlloc ){
130305           Fts3HashElem **aElem2;
130306           nAlloc += 16;
130307           aElem2 = (Fts3HashElem **)sqlite3_realloc(
130308               aElem, nAlloc*sizeof(Fts3HashElem *)
130309           );
130310           if( !aElem2 ){
130311             rc = SQLITE_NOMEM;
130312             nElem = 0;
130313             break;
130314           }
130315           aElem = aElem2;
130316         }
130317
130318         aElem[nElem++] = pE;
130319       }
130320     }
130321
130322     /* If more than one term matches the prefix, sort the Fts3HashElem
130323     ** objects in term order using qsort(). This uses the same comparison
130324     ** callback as is used when flushing terms to disk.
130325     */
130326     if( nElem>1 ){
130327       qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
130328     }
130329
130330   }else{
130331     /* The query is a simple term lookup that matches at most one term in
130332     ** the index. All that is required is a straight hash-lookup. 
130333     **
130334     ** Because the stack address of pE may be accessed via the aElem pointer
130335     ** below, the "Fts3HashElem *pE" must be declared so that it is valid
130336     ** within this entire function, not just this "else{...}" block.
130337     */
130338     pE = fts3HashFindElem(pHash, zTerm, nTerm);
130339     if( pE ){
130340       aElem = &pE;
130341       nElem = 1;
130342     }
130343   }
130344
130345   if( nElem>0 ){
130346     int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
130347     pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
130348     if( !pReader ){
130349       rc = SQLITE_NOMEM;
130350     }else{
130351       memset(pReader, 0, nByte);
130352       pReader->iIdx = 0x7FFFFFFF;
130353       pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
130354       memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
130355     }
130356   }
130357
130358   if( bPrefix ){
130359     sqlite3_free(aElem);
130360   }
130361   *ppReader = pReader;
130362   return rc;
130363 }
130364
130365 /*
130366 ** Compare the entries pointed to by two Fts3SegReader structures. 
130367 ** Comparison is as follows:
130368 **
130369 **   1) EOF is greater than not EOF.
130370 **
130371 **   2) The current terms (if any) are compared using memcmp(). If one
130372 **      term is a prefix of another, the longer term is considered the
130373 **      larger.
130374 **
130375 **   3) By segment age. An older segment is considered larger.
130376 */
130377 static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
130378   int rc;
130379   if( pLhs->aNode && pRhs->aNode ){
130380     int rc2 = pLhs->nTerm - pRhs->nTerm;
130381     if( rc2<0 ){
130382       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
130383     }else{
130384       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
130385     }
130386     if( rc==0 ){
130387       rc = rc2;
130388     }
130389   }else{
130390     rc = (pLhs->aNode==0) - (pRhs->aNode==0);
130391   }
130392   if( rc==0 ){
130393     rc = pRhs->iIdx - pLhs->iIdx;
130394   }
130395   assert( rc!=0 );
130396   return rc;
130397 }
130398
130399 /*
130400 ** A different comparison function for SegReader structures. In this
130401 ** version, it is assumed that each SegReader points to an entry in
130402 ** a doclist for identical terms. Comparison is made as follows:
130403 **
130404 **   1) EOF (end of doclist in this case) is greater than not EOF.
130405 **
130406 **   2) By current docid.
130407 **
130408 **   3) By segment age. An older segment is considered larger.
130409 */
130410 static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
130411   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
130412   if( rc==0 ){
130413     if( pLhs->iDocid==pRhs->iDocid ){
130414       rc = pRhs->iIdx - pLhs->iIdx;
130415     }else{
130416       rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
130417     }
130418   }
130419   assert( pLhs->aNode && pRhs->aNode );
130420   return rc;
130421 }
130422 static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
130423   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
130424   if( rc==0 ){
130425     if( pLhs->iDocid==pRhs->iDocid ){
130426       rc = pRhs->iIdx - pLhs->iIdx;
130427     }else{
130428       rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
130429     }
130430   }
130431   assert( pLhs->aNode && pRhs->aNode );
130432   return rc;
130433 }
130434
130435 /*
130436 ** Compare the term that the Fts3SegReader object passed as the first argument
130437 ** points to with the term specified by arguments zTerm and nTerm. 
130438 **
130439 ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
130440 ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
130441 ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
130442 */
130443 static int fts3SegReaderTermCmp(
130444   Fts3SegReader *pSeg,            /* Segment reader object */
130445   const char *zTerm,              /* Term to compare to */
130446   int nTerm                       /* Size of term zTerm in bytes */
130447 ){
130448   int res = 0;
130449   if( pSeg->aNode ){
130450     if( pSeg->nTerm>nTerm ){
130451       res = memcmp(pSeg->zTerm, zTerm, nTerm);
130452     }else{
130453       res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
130454     }
130455     if( res==0 ){
130456       res = pSeg->nTerm-nTerm;
130457     }
130458   }
130459   return res;
130460 }
130461
130462 /*
130463 ** Argument apSegment is an array of nSegment elements. It is known that
130464 ** the final (nSegment-nSuspect) members are already in sorted order
130465 ** (according to the comparison function provided). This function shuffles
130466 ** the array around until all entries are in sorted order.
130467 */
130468 static void fts3SegReaderSort(
130469   Fts3SegReader **apSegment,                     /* Array to sort entries of */
130470   int nSegment,                                  /* Size of apSegment array */
130471   int nSuspect,                                  /* Unsorted entry count */
130472   int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
130473 ){
130474   int i;                          /* Iterator variable */
130475
130476   assert( nSuspect<=nSegment );
130477
130478   if( nSuspect==nSegment ) nSuspect--;
130479   for(i=nSuspect-1; i>=0; i--){
130480     int j;
130481     for(j=i; j<(nSegment-1); j++){
130482       Fts3SegReader *pTmp;
130483       if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
130484       pTmp = apSegment[j+1];
130485       apSegment[j+1] = apSegment[j];
130486       apSegment[j] = pTmp;
130487     }
130488   }
130489
130490 #ifndef NDEBUG
130491   /* Check that the list really is sorted now. */
130492   for(i=0; i<(nSuspect-1); i++){
130493     assert( xCmp(apSegment[i], apSegment[i+1])<0 );
130494   }
130495 #endif
130496 }
130497
130498 /* 
130499 ** Insert a record into the %_segments table.
130500 */
130501 static int fts3WriteSegment(
130502   Fts3Table *p,                   /* Virtual table handle */
130503   sqlite3_int64 iBlock,           /* Block id for new block */
130504   char *z,                        /* Pointer to buffer containing block data */
130505   int n                           /* Size of buffer z in bytes */
130506 ){
130507   sqlite3_stmt *pStmt;
130508   int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
130509   if( rc==SQLITE_OK ){
130510     sqlite3_bind_int64(pStmt, 1, iBlock);
130511     sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
130512     sqlite3_step(pStmt);
130513     rc = sqlite3_reset(pStmt);
130514   }
130515   return rc;
130516 }
130517
130518 /*
130519 ** Find the largest relative level number in the table. If successful, set
130520 ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
130521 ** set *pnMax to zero and return an SQLite error code.
130522 */
130523 SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
130524   int rc;
130525   int mxLevel = 0;
130526   sqlite3_stmt *pStmt = 0;
130527
130528   rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
130529   if( rc==SQLITE_OK ){
130530     if( SQLITE_ROW==sqlite3_step(pStmt) ){
130531       mxLevel = sqlite3_column_int(pStmt, 0);
130532     }
130533     rc = sqlite3_reset(pStmt);
130534   }
130535   *pnMax = mxLevel;
130536   return rc;
130537 }
130538
130539 /* 
130540 ** Insert a record into the %_segdir table.
130541 */
130542 static int fts3WriteSegdir(
130543   Fts3Table *p,                   /* Virtual table handle */
130544   sqlite3_int64 iLevel,           /* Value for "level" field (absolute level) */
130545   int iIdx,                       /* Value for "idx" field */
130546   sqlite3_int64 iStartBlock,      /* Value for "start_block" field */
130547   sqlite3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
130548   sqlite3_int64 iEndBlock,        /* Value for "end_block" field */
130549   char *zRoot,                    /* Blob value for "root" field */
130550   int nRoot                       /* Number of bytes in buffer zRoot */
130551 ){
130552   sqlite3_stmt *pStmt;
130553   int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
130554   if( rc==SQLITE_OK ){
130555     sqlite3_bind_int64(pStmt, 1, iLevel);
130556     sqlite3_bind_int(pStmt, 2, iIdx);
130557     sqlite3_bind_int64(pStmt, 3, iStartBlock);
130558     sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
130559     sqlite3_bind_int64(pStmt, 5, iEndBlock);
130560     sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
130561     sqlite3_step(pStmt);
130562     rc = sqlite3_reset(pStmt);
130563   }
130564   return rc;
130565 }
130566
130567 /*
130568 ** Return the size of the common prefix (if any) shared by zPrev and
130569 ** zNext, in bytes. For example, 
130570 **
130571 **   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
130572 **   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
130573 **   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
130574 */
130575 static int fts3PrefixCompress(
130576   const char *zPrev,              /* Buffer containing previous term */
130577   int nPrev,                      /* Size of buffer zPrev in bytes */
130578   const char *zNext,              /* Buffer containing next term */
130579   int nNext                       /* Size of buffer zNext in bytes */
130580 ){
130581   int n;
130582   UNUSED_PARAMETER(nNext);
130583   for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
130584   return n;
130585 }
130586
130587 /*
130588 ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
130589 ** (according to memcmp) than the previous term.
130590 */
130591 static int fts3NodeAddTerm(
130592   Fts3Table *p,                   /* Virtual table handle */
130593   SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */ 
130594   int isCopyTerm,                 /* True if zTerm/nTerm is transient */
130595   const char *zTerm,              /* Pointer to buffer containing term */
130596   int nTerm                       /* Size of term in bytes */
130597 ){
130598   SegmentNode *pTree = *ppTree;
130599   int rc;
130600   SegmentNode *pNew;
130601
130602   /* First try to append the term to the current node. Return early if 
130603   ** this is possible.
130604   */
130605   if( pTree ){
130606     int nData = pTree->nData;     /* Current size of node in bytes */
130607     int nReq = nData;             /* Required space after adding zTerm */
130608     int nPrefix;                  /* Number of bytes of prefix compression */
130609     int nSuffix;                  /* Suffix length */
130610
130611     nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
130612     nSuffix = nTerm-nPrefix;
130613
130614     nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
130615     if( nReq<=p->nNodeSize || !pTree->zTerm ){
130616
130617       if( nReq>p->nNodeSize ){
130618         /* An unusual case: this is the first term to be added to the node
130619         ** and the static node buffer (p->nNodeSize bytes) is not large
130620         ** enough. Use a separately malloced buffer instead This wastes
130621         ** p->nNodeSize bytes, but since this scenario only comes about when
130622         ** the database contain two terms that share a prefix of almost 2KB, 
130623         ** this is not expected to be a serious problem. 
130624         */
130625         assert( pTree->aData==(char *)&pTree[1] );
130626         pTree->aData = (char *)sqlite3_malloc(nReq);
130627         if( !pTree->aData ){
130628           return SQLITE_NOMEM;
130629         }
130630       }
130631
130632       if( pTree->zTerm ){
130633         /* There is no prefix-length field for first term in a node */
130634         nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
130635       }
130636
130637       nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
130638       memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
130639       pTree->nData = nData + nSuffix;
130640       pTree->nEntry++;
130641
130642       if( isCopyTerm ){
130643         if( pTree->nMalloc<nTerm ){
130644           char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
130645           if( !zNew ){
130646             return SQLITE_NOMEM;
130647           }
130648           pTree->nMalloc = nTerm*2;
130649           pTree->zMalloc = zNew;
130650         }
130651         pTree->zTerm = pTree->zMalloc;
130652         memcpy(pTree->zTerm, zTerm, nTerm);
130653         pTree->nTerm = nTerm;
130654       }else{
130655         pTree->zTerm = (char *)zTerm;
130656         pTree->nTerm = nTerm;
130657       }
130658       return SQLITE_OK;
130659     }
130660   }
130661
130662   /* If control flows to here, it was not possible to append zTerm to the
130663   ** current node. Create a new node (a right-sibling of the current node).
130664   ** If this is the first node in the tree, the term is added to it.
130665   **
130666   ** Otherwise, the term is not added to the new node, it is left empty for
130667   ** now. Instead, the term is inserted into the parent of pTree. If pTree 
130668   ** has no parent, one is created here.
130669   */
130670   pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
130671   if( !pNew ){
130672     return SQLITE_NOMEM;
130673   }
130674   memset(pNew, 0, sizeof(SegmentNode));
130675   pNew->nData = 1 + FTS3_VARINT_MAX;
130676   pNew->aData = (char *)&pNew[1];
130677
130678   if( pTree ){
130679     SegmentNode *pParent = pTree->pParent;
130680     rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
130681     if( pTree->pParent==0 ){
130682       pTree->pParent = pParent;
130683     }
130684     pTree->pRight = pNew;
130685     pNew->pLeftmost = pTree->pLeftmost;
130686     pNew->pParent = pParent;
130687     pNew->zMalloc = pTree->zMalloc;
130688     pNew->nMalloc = pTree->nMalloc;
130689     pTree->zMalloc = 0;
130690   }else{
130691     pNew->pLeftmost = pNew;
130692     rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm); 
130693   }
130694
130695   *ppTree = pNew;
130696   return rc;
130697 }
130698
130699 /*
130700 ** Helper function for fts3NodeWrite().
130701 */
130702 static int fts3TreeFinishNode(
130703   SegmentNode *pTree, 
130704   int iHeight, 
130705   sqlite3_int64 iLeftChild
130706 ){
130707   int nStart;
130708   assert( iHeight>=1 && iHeight<128 );
130709   nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
130710   pTree->aData[nStart] = (char)iHeight;
130711   sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
130712   return nStart;
130713 }
130714
130715 /*
130716 ** Write the buffer for the segment node pTree and all of its peers to the
130717 ** database. Then call this function recursively to write the parent of 
130718 ** pTree and its peers to the database. 
130719 **
130720 ** Except, if pTree is a root node, do not write it to the database. Instead,
130721 ** set output variables *paRoot and *pnRoot to contain the root node.
130722 **
130723 ** If successful, SQLITE_OK is returned and output variable *piLast is
130724 ** set to the largest blockid written to the database (or zero if no
130725 ** blocks were written to the db). Otherwise, an SQLite error code is 
130726 ** returned.
130727 */
130728 static int fts3NodeWrite(
130729   Fts3Table *p,                   /* Virtual table handle */
130730   SegmentNode *pTree,             /* SegmentNode handle */
130731   int iHeight,                    /* Height of this node in tree */
130732   sqlite3_int64 iLeaf,            /* Block id of first leaf node */
130733   sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */
130734   sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */
130735   char **paRoot,                  /* OUT: Data for root node */
130736   int *pnRoot                     /* OUT: Size of root node in bytes */
130737 ){
130738   int rc = SQLITE_OK;
130739
130740   if( !pTree->pParent ){
130741     /* Root node of the tree. */
130742     int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
130743     *piLast = iFree-1;
130744     *pnRoot = pTree->nData - nStart;
130745     *paRoot = &pTree->aData[nStart];
130746   }else{
130747     SegmentNode *pIter;
130748     sqlite3_int64 iNextFree = iFree;
130749     sqlite3_int64 iNextLeaf = iLeaf;
130750     for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
130751       int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
130752       int nWrite = pIter->nData - nStart;
130753   
130754       rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
130755       iNextFree++;
130756       iNextLeaf += (pIter->nEntry+1);
130757     }
130758     if( rc==SQLITE_OK ){
130759       assert( iNextLeaf==iFree );
130760       rc = fts3NodeWrite(
130761           p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
130762       );
130763     }
130764   }
130765
130766   return rc;
130767 }
130768
130769 /*
130770 ** Free all memory allocations associated with the tree pTree.
130771 */
130772 static void fts3NodeFree(SegmentNode *pTree){
130773   if( pTree ){
130774     SegmentNode *p = pTree->pLeftmost;
130775     fts3NodeFree(p->pParent);
130776     while( p ){
130777       SegmentNode *pRight = p->pRight;
130778       if( p->aData!=(char *)&p[1] ){
130779         sqlite3_free(p->aData);
130780       }
130781       assert( pRight==0 || p->zMalloc==0 );
130782       sqlite3_free(p->zMalloc);
130783       sqlite3_free(p);
130784       p = pRight;
130785     }
130786   }
130787 }
130788
130789 /*
130790 ** Add a term to the segment being constructed by the SegmentWriter object
130791 ** *ppWriter. When adding the first term to a segment, *ppWriter should
130792 ** be passed NULL. This function will allocate a new SegmentWriter object
130793 ** and return it via the input/output variable *ppWriter in this case.
130794 **
130795 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
130796 */
130797 static int fts3SegWriterAdd(
130798   Fts3Table *p,                   /* Virtual table handle */
130799   SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */ 
130800   int isCopyTerm,                 /* True if buffer zTerm must be copied */
130801   const char *zTerm,              /* Pointer to buffer containing term */
130802   int nTerm,                      /* Size of term in bytes */
130803   const char *aDoclist,           /* Pointer to buffer containing doclist */
130804   int nDoclist                    /* Size of doclist in bytes */
130805 ){
130806   int nPrefix;                    /* Size of term prefix in bytes */
130807   int nSuffix;                    /* Size of term suffix in bytes */
130808   int nReq;                       /* Number of bytes required on leaf page */
130809   int nData;
130810   SegmentWriter *pWriter = *ppWriter;
130811
130812   if( !pWriter ){
130813     int rc;
130814     sqlite3_stmt *pStmt;
130815
130816     /* Allocate the SegmentWriter structure */
130817     pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
130818     if( !pWriter ) return SQLITE_NOMEM;
130819     memset(pWriter, 0, sizeof(SegmentWriter));
130820     *ppWriter = pWriter;
130821
130822     /* Allocate a buffer in which to accumulate data */
130823     pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
130824     if( !pWriter->aData ) return SQLITE_NOMEM;
130825     pWriter->nSize = p->nNodeSize;
130826
130827     /* Find the next free blockid in the %_segments table */
130828     rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
130829     if( rc!=SQLITE_OK ) return rc;
130830     if( SQLITE_ROW==sqlite3_step(pStmt) ){
130831       pWriter->iFree = sqlite3_column_int64(pStmt, 0);
130832       pWriter->iFirst = pWriter->iFree;
130833     }
130834     rc = sqlite3_reset(pStmt);
130835     if( rc!=SQLITE_OK ) return rc;
130836   }
130837   nData = pWriter->nData;
130838
130839   nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
130840   nSuffix = nTerm-nPrefix;
130841
130842   /* Figure out how many bytes are required by this new entry */
130843   nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
130844     sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
130845     nSuffix +                               /* Term suffix */
130846     sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */
130847     nDoclist;                               /* Doclist data */
130848
130849   if( nData>0 && nData+nReq>p->nNodeSize ){
130850     int rc;
130851
130852     /* The current leaf node is full. Write it out to the database. */
130853     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
130854     if( rc!=SQLITE_OK ) return rc;
130855     p->nLeafAdd++;
130856
130857     /* Add the current term to the interior node tree. The term added to
130858     ** the interior tree must:
130859     **
130860     **   a) be greater than the largest term on the leaf node just written
130861     **      to the database (still available in pWriter->zTerm), and
130862     **
130863     **   b) be less than or equal to the term about to be added to the new
130864     **      leaf node (zTerm/nTerm).
130865     **
130866     ** In other words, it must be the prefix of zTerm 1 byte longer than
130867     ** the common prefix (if any) of zTerm and pWriter->zTerm.
130868     */
130869     assert( nPrefix<nTerm );
130870     rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
130871     if( rc!=SQLITE_OK ) return rc;
130872
130873     nData = 0;
130874     pWriter->nTerm = 0;
130875
130876     nPrefix = 0;
130877     nSuffix = nTerm;
130878     nReq = 1 +                              /* varint containing prefix size */
130879       sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
130880       nTerm +                               /* Term suffix */
130881       sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */
130882       nDoclist;                             /* Doclist data */
130883   }
130884
130885   /* If the buffer currently allocated is too small for this entry, realloc
130886   ** the buffer to make it large enough.
130887   */
130888   if( nReq>pWriter->nSize ){
130889     char *aNew = sqlite3_realloc(pWriter->aData, nReq);
130890     if( !aNew ) return SQLITE_NOMEM;
130891     pWriter->aData = aNew;
130892     pWriter->nSize = nReq;
130893   }
130894   assert( nData+nReq<=pWriter->nSize );
130895
130896   /* Append the prefix-compressed term and doclist to the buffer. */
130897   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
130898   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
130899   memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
130900   nData += nSuffix;
130901   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
130902   memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
130903   pWriter->nData = nData + nDoclist;
130904
130905   /* Save the current term so that it can be used to prefix-compress the next.
130906   ** If the isCopyTerm parameter is true, then the buffer pointed to by
130907   ** zTerm is transient, so take a copy of the term data. Otherwise, just
130908   ** store a copy of the pointer.
130909   */
130910   if( isCopyTerm ){
130911     if( nTerm>pWriter->nMalloc ){
130912       char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
130913       if( !zNew ){
130914         return SQLITE_NOMEM;
130915       }
130916       pWriter->nMalloc = nTerm*2;
130917       pWriter->zMalloc = zNew;
130918       pWriter->zTerm = zNew;
130919     }
130920     assert( pWriter->zTerm==pWriter->zMalloc );
130921     memcpy(pWriter->zTerm, zTerm, nTerm);
130922   }else{
130923     pWriter->zTerm = (char *)zTerm;
130924   }
130925   pWriter->nTerm = nTerm;
130926
130927   return SQLITE_OK;
130928 }
130929
130930 /*
130931 ** Flush all data associated with the SegmentWriter object pWriter to the
130932 ** database. This function must be called after all terms have been added
130933 ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
130934 ** returned. Otherwise, an SQLite error code.
130935 */
130936 static int fts3SegWriterFlush(
130937   Fts3Table *p,                   /* Virtual table handle */
130938   SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
130939   sqlite3_int64 iLevel,           /* Value for 'level' column of %_segdir */
130940   int iIdx                        /* Value for 'idx' column of %_segdir */
130941 ){
130942   int rc;                         /* Return code */
130943   if( pWriter->pTree ){
130944     sqlite3_int64 iLast = 0;      /* Largest block id written to database */
130945     sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */
130946     char *zRoot = NULL;           /* Pointer to buffer containing root node */
130947     int nRoot = 0;                /* Size of buffer zRoot */
130948
130949     iLastLeaf = pWriter->iFree;
130950     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
130951     if( rc==SQLITE_OK ){
130952       rc = fts3NodeWrite(p, pWriter->pTree, 1,
130953           pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
130954     }
130955     if( rc==SQLITE_OK ){
130956       rc = fts3WriteSegdir(
130957           p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, zRoot, nRoot);
130958     }
130959   }else{
130960     /* The entire tree fits on the root node. Write it to the segdir table. */
130961     rc = fts3WriteSegdir(
130962         p, iLevel, iIdx, 0, 0, 0, pWriter->aData, pWriter->nData);
130963   }
130964   p->nLeafAdd++;
130965   return rc;
130966 }
130967
130968 /*
130969 ** Release all memory held by the SegmentWriter object passed as the 
130970 ** first argument.
130971 */
130972 static void fts3SegWriterFree(SegmentWriter *pWriter){
130973   if( pWriter ){
130974     sqlite3_free(pWriter->aData);
130975     sqlite3_free(pWriter->zMalloc);
130976     fts3NodeFree(pWriter->pTree);
130977     sqlite3_free(pWriter);
130978   }
130979 }
130980
130981 /*
130982 ** The first value in the apVal[] array is assumed to contain an integer.
130983 ** This function tests if there exist any documents with docid values that
130984 ** are different from that integer. i.e. if deleting the document with docid
130985 ** pRowid would mean the FTS3 table were empty.
130986 **
130987 ** If successful, *pisEmpty is set to true if the table is empty except for
130988 ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
130989 ** error occurs, an SQLite error code is returned.
130990 */
130991 static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
130992   sqlite3_stmt *pStmt;
130993   int rc;
130994   if( p->zContentTbl ){
130995     /* If using the content=xxx option, assume the table is never empty */
130996     *pisEmpty = 0;
130997     rc = SQLITE_OK;
130998   }else{
130999     rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
131000     if( rc==SQLITE_OK ){
131001       if( SQLITE_ROW==sqlite3_step(pStmt) ){
131002         *pisEmpty = sqlite3_column_int(pStmt, 0);
131003       }
131004       rc = sqlite3_reset(pStmt);
131005     }
131006   }
131007   return rc;
131008 }
131009
131010 /*
131011 ** Set *pnMax to the largest segment level in the database for the index
131012 ** iIndex.
131013 **
131014 ** Segment levels are stored in the 'level' column of the %_segdir table.
131015 **
131016 ** Return SQLITE_OK if successful, or an SQLite error code if not.
131017 */
131018 static int fts3SegmentMaxLevel(
131019   Fts3Table *p, 
131020   int iLangid,
131021   int iIndex, 
131022   sqlite3_int64 *pnMax
131023 ){
131024   sqlite3_stmt *pStmt;
131025   int rc;
131026   assert( iIndex>=0 && iIndex<p->nIndex );
131027
131028   /* Set pStmt to the compiled version of:
131029   **
131030   **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
131031   **
131032   ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
131033   */
131034   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
131035   if( rc!=SQLITE_OK ) return rc;
131036   sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
131037   sqlite3_bind_int64(pStmt, 2, 
131038       getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
131039   );
131040   if( SQLITE_ROW==sqlite3_step(pStmt) ){
131041     *pnMax = sqlite3_column_int64(pStmt, 0);
131042   }
131043   return sqlite3_reset(pStmt);
131044 }
131045
131046 /*
131047 ** Delete all entries in the %_segments table associated with the segment
131048 ** opened with seg-reader pSeg. This function does not affect the contents
131049 ** of the %_segdir table.
131050 */
131051 static int fts3DeleteSegment(
131052   Fts3Table *p,                   /* FTS table handle */
131053   Fts3SegReader *pSeg             /* Segment to delete */
131054 ){
131055   int rc = SQLITE_OK;             /* Return code */
131056   if( pSeg->iStartBlock ){
131057     sqlite3_stmt *pDelete;        /* SQL statement to delete rows */
131058     rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
131059     if( rc==SQLITE_OK ){
131060       sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
131061       sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
131062       sqlite3_step(pDelete);
131063       rc = sqlite3_reset(pDelete);
131064     }
131065   }
131066   return rc;
131067 }
131068
131069 /*
131070 ** This function is used after merging multiple segments into a single large
131071 ** segment to delete the old, now redundant, segment b-trees. Specifically,
131072 ** it:
131073 ** 
131074 **   1) Deletes all %_segments entries for the segments associated with 
131075 **      each of the SegReader objects in the array passed as the third 
131076 **      argument, and
131077 **
131078 **   2) deletes all %_segdir entries with level iLevel, or all %_segdir
131079 **      entries regardless of level if (iLevel<0).
131080 **
131081 ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
131082 */
131083 static int fts3DeleteSegdir(
131084   Fts3Table *p,                   /* Virtual table handle */
131085   int iLangid,                    /* Language id */
131086   int iIndex,                     /* Index for p->aIndex */
131087   int iLevel,                     /* Level of %_segdir entries to delete */
131088   Fts3SegReader **apSegment,      /* Array of SegReader objects */
131089   int nReader                     /* Size of array apSegment */
131090 ){
131091   int rc = SQLITE_OK;             /* Return Code */
131092   int i;                          /* Iterator variable */
131093   sqlite3_stmt *pDelete = 0;      /* SQL statement to delete rows */
131094
131095   for(i=0; rc==SQLITE_OK && i<nReader; i++){
131096     rc = fts3DeleteSegment(p, apSegment[i]);
131097   }
131098   if( rc!=SQLITE_OK ){
131099     return rc;
131100   }
131101
131102   assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
131103   if( iLevel==FTS3_SEGCURSOR_ALL ){
131104     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
131105     if( rc==SQLITE_OK ){
131106       sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
131107       sqlite3_bind_int64(pDelete, 2, 
131108           getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
131109       );
131110     }
131111   }else{
131112     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
131113     if( rc==SQLITE_OK ){
131114       sqlite3_bind_int64(
131115           pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
131116       );
131117     }
131118   }
131119
131120   if( rc==SQLITE_OK ){
131121     sqlite3_step(pDelete);
131122     rc = sqlite3_reset(pDelete);
131123   }
131124
131125   return rc;
131126 }
131127
131128 /*
131129 ** When this function is called, buffer *ppList (size *pnList bytes) contains 
131130 ** a position list that may (or may not) feature multiple columns. This
131131 ** function adjusts the pointer *ppList and the length *pnList so that they
131132 ** identify the subset of the position list that corresponds to column iCol.
131133 **
131134 ** If there are no entries in the input position list for column iCol, then
131135 ** *pnList is set to zero before returning.
131136 **
131137 ** If parameter bZero is non-zero, then any part of the input list following
131138 ** the end of the output list is zeroed before returning.
131139 */
131140 static void fts3ColumnFilter(
131141   int iCol,                       /* Column to filter on */
131142   int bZero,                      /* Zero out anything following *ppList */
131143   char **ppList,                  /* IN/OUT: Pointer to position list */
131144   int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
131145 ){
131146   char *pList = *ppList;
131147   int nList = *pnList;
131148   char *pEnd = &pList[nList];
131149   int iCurrent = 0;
131150   char *p = pList;
131151
131152   assert( iCol>=0 );
131153   while( 1 ){
131154     char c = 0;
131155     while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
131156   
131157     if( iCol==iCurrent ){
131158       nList = (int)(p - pList);
131159       break;
131160     }
131161
131162     nList -= (int)(p - pList);
131163     pList = p;
131164     if( nList==0 ){
131165       break;
131166     }
131167     p = &pList[1];
131168     p += sqlite3Fts3GetVarint32(p, &iCurrent);
131169   }
131170
131171   if( bZero && &pList[nList]!=pEnd ){
131172     memset(&pList[nList], 0, pEnd - &pList[nList]);
131173   }
131174   *ppList = pList;
131175   *pnList = nList;
131176 }
131177
131178 /*
131179 ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
131180 ** existing data). Grow the buffer if required.
131181 **
131182 ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
131183 ** trying to resize the buffer, return SQLITE_NOMEM.
131184 */
131185 static int fts3MsrBufferData(
131186   Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
131187   char *pList,
131188   int nList
131189 ){
131190   if( nList>pMsr->nBuffer ){
131191     char *pNew;
131192     pMsr->nBuffer = nList*2;
131193     pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
131194     if( !pNew ) return SQLITE_NOMEM;
131195     pMsr->aBuffer = pNew;
131196   }
131197
131198   memcpy(pMsr->aBuffer, pList, nList);
131199   return SQLITE_OK;
131200 }
131201
131202 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
131203   Fts3Table *p,                   /* Virtual table handle */
131204   Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
131205   sqlite3_int64 *piDocid,         /* OUT: Docid value */
131206   char **paPoslist,               /* OUT: Pointer to position list */
131207   int *pnPoslist                  /* OUT: Size of position list in bytes */
131208 ){
131209   int nMerge = pMsr->nAdvance;
131210   Fts3SegReader **apSegment = pMsr->apSegment;
131211   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
131212     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
131213   );
131214
131215   if( nMerge==0 ){
131216     *paPoslist = 0;
131217     return SQLITE_OK;
131218   }
131219
131220   while( 1 ){
131221     Fts3SegReader *pSeg;
131222     pSeg = pMsr->apSegment[0];
131223
131224     if( pSeg->pOffsetList==0 ){
131225       *paPoslist = 0;
131226       break;
131227     }else{
131228       int rc;
131229       char *pList;
131230       int nList;
131231       int j;
131232       sqlite3_int64 iDocid = apSegment[0]->iDocid;
131233
131234       rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
131235       j = 1;
131236       while( rc==SQLITE_OK 
131237         && j<nMerge
131238         && apSegment[j]->pOffsetList
131239         && apSegment[j]->iDocid==iDocid
131240       ){
131241         rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
131242         j++;
131243       }
131244       if( rc!=SQLITE_OK ) return rc;
131245       fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
131246
131247       if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
131248         rc = fts3MsrBufferData(pMsr, pList, nList+1);
131249         if( rc!=SQLITE_OK ) return rc;
131250         assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
131251         pList = pMsr->aBuffer;
131252       }
131253
131254       if( pMsr->iColFilter>=0 ){
131255         fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
131256       }
131257
131258       if( nList>0 ){
131259         *paPoslist = pList;
131260         *piDocid = iDocid;
131261         *pnPoslist = nList;
131262         break;
131263       }
131264     }
131265   }
131266
131267   return SQLITE_OK;
131268 }
131269
131270 static int fts3SegReaderStart(
131271   Fts3Table *p,                   /* Virtual table handle */
131272   Fts3MultiSegReader *pCsr,       /* Cursor object */
131273   const char *zTerm,              /* Term searched for (or NULL) */
131274   int nTerm                       /* Length of zTerm in bytes */
131275 ){
131276   int i;
131277   int nSeg = pCsr->nSegment;
131278
131279   /* If the Fts3SegFilter defines a specific term (or term prefix) to search 
131280   ** for, then advance each segment iterator until it points to a term of
131281   ** equal or greater value than the specified term. This prevents many
131282   ** unnecessary merge/sort operations for the case where single segment
131283   ** b-tree leaf nodes contain more than one term.
131284   */
131285   for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
131286     int res = 0;
131287     Fts3SegReader *pSeg = pCsr->apSegment[i];
131288     do {
131289       int rc = fts3SegReaderNext(p, pSeg, 0);
131290       if( rc!=SQLITE_OK ) return rc;
131291     }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
131292
131293     if( pSeg->bLookup && res!=0 ){
131294       fts3SegReaderSetEof(pSeg);
131295     }
131296   }
131297   fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
131298
131299   return SQLITE_OK;
131300 }
131301
131302 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
131303   Fts3Table *p,                   /* Virtual table handle */
131304   Fts3MultiSegReader *pCsr,       /* Cursor object */
131305   Fts3SegFilter *pFilter          /* Restrictions on range of iteration */
131306 ){
131307   pCsr->pFilter = pFilter;
131308   return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
131309 }
131310
131311 SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
131312   Fts3Table *p,                   /* Virtual table handle */
131313   Fts3MultiSegReader *pCsr,       /* Cursor object */
131314   int iCol,                       /* Column to match on. */
131315   const char *zTerm,              /* Term to iterate through a doclist for */
131316   int nTerm                       /* Number of bytes in zTerm */
131317 ){
131318   int i;
131319   int rc;
131320   int nSegment = pCsr->nSegment;
131321   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
131322     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
131323   );
131324
131325   assert( pCsr->pFilter==0 );
131326   assert( zTerm && nTerm>0 );
131327
131328   /* Advance each segment iterator until it points to the term zTerm/nTerm. */
131329   rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
131330   if( rc!=SQLITE_OK ) return rc;
131331
131332   /* Determine how many of the segments actually point to zTerm/nTerm. */
131333   for(i=0; i<nSegment; i++){
131334     Fts3SegReader *pSeg = pCsr->apSegment[i];
131335     if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
131336       break;
131337     }
131338   }
131339   pCsr->nAdvance = i;
131340
131341   /* Advance each of the segments to point to the first docid. */
131342   for(i=0; i<pCsr->nAdvance; i++){
131343     rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
131344     if( rc!=SQLITE_OK ) return rc;
131345   }
131346   fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
131347
131348   assert( iCol<0 || iCol<p->nColumn );
131349   pCsr->iColFilter = iCol;
131350
131351   return SQLITE_OK;
131352 }
131353
131354 /*
131355 ** This function is called on a MultiSegReader that has been started using
131356 ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
131357 ** have been made. Calling this function puts the MultiSegReader in such
131358 ** a state that if the next two calls are:
131359 **
131360 **   sqlite3Fts3SegReaderStart()
131361 **   sqlite3Fts3SegReaderStep()
131362 **
131363 ** then the entire doclist for the term is available in 
131364 ** MultiSegReader.aDoclist/nDoclist.
131365 */
131366 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
131367   int i;                          /* Used to iterate through segment-readers */
131368
131369   assert( pCsr->zTerm==0 );
131370   assert( pCsr->nTerm==0 );
131371   assert( pCsr->aDoclist==0 );
131372   assert( pCsr->nDoclist==0 );
131373
131374   pCsr->nAdvance = 0;
131375   pCsr->bRestart = 1;
131376   for(i=0; i<pCsr->nSegment; i++){
131377     pCsr->apSegment[i]->pOffsetList = 0;
131378     pCsr->apSegment[i]->nOffsetList = 0;
131379     pCsr->apSegment[i]->iDocid = 0;
131380   }
131381
131382   return SQLITE_OK;
131383 }
131384
131385
131386 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
131387   Fts3Table *p,                   /* Virtual table handle */
131388   Fts3MultiSegReader *pCsr        /* Cursor object */
131389 ){
131390   int rc = SQLITE_OK;
131391
131392   int isIgnoreEmpty =  (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
131393   int isRequirePos =   (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
131394   int isColFilter =    (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
131395   int isPrefix =       (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
131396   int isScan =         (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
131397   int isFirst =        (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
131398
131399   Fts3SegReader **apSegment = pCsr->apSegment;
131400   int nSegment = pCsr->nSegment;
131401   Fts3SegFilter *pFilter = pCsr->pFilter;
131402   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
131403     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
131404   );
131405
131406   if( pCsr->nSegment==0 ) return SQLITE_OK;
131407
131408   do {
131409     int nMerge;
131410     int i;
131411   
131412     /* Advance the first pCsr->nAdvance entries in the apSegment[] array
131413     ** forward. Then sort the list in order of current term again.  
131414     */
131415     for(i=0; i<pCsr->nAdvance; i++){
131416       Fts3SegReader *pSeg = apSegment[i];
131417       if( pSeg->bLookup ){
131418         fts3SegReaderSetEof(pSeg);
131419       }else{
131420         rc = fts3SegReaderNext(p, pSeg, 0);
131421       }
131422       if( rc!=SQLITE_OK ) return rc;
131423     }
131424     fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
131425     pCsr->nAdvance = 0;
131426
131427     /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
131428     assert( rc==SQLITE_OK );
131429     if( apSegment[0]->aNode==0 ) break;
131430
131431     pCsr->nTerm = apSegment[0]->nTerm;
131432     pCsr->zTerm = apSegment[0]->zTerm;
131433
131434     /* If this is a prefix-search, and if the term that apSegment[0] points
131435     ** to does not share a suffix with pFilter->zTerm/nTerm, then all 
131436     ** required callbacks have been made. In this case exit early.
131437     **
131438     ** Similarly, if this is a search for an exact match, and the first term
131439     ** of segment apSegment[0] is not a match, exit early.
131440     */
131441     if( pFilter->zTerm && !isScan ){
131442       if( pCsr->nTerm<pFilter->nTerm 
131443        || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
131444        || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm) 
131445       ){
131446         break;
131447       }
131448     }
131449
131450     nMerge = 1;
131451     while( nMerge<nSegment 
131452         && apSegment[nMerge]->aNode
131453         && apSegment[nMerge]->nTerm==pCsr->nTerm 
131454         && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
131455     ){
131456       nMerge++;
131457     }
131458
131459     assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
131460     if( nMerge==1 
131461      && !isIgnoreEmpty 
131462      && !isFirst 
131463      && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
131464     ){
131465       pCsr->nDoclist = apSegment[0]->nDoclist;
131466       if( fts3SegReaderIsPending(apSegment[0]) ){
131467         rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
131468         pCsr->aDoclist = pCsr->aBuffer;
131469       }else{
131470         pCsr->aDoclist = apSegment[0]->aDoclist;
131471       }
131472       if( rc==SQLITE_OK ) rc = SQLITE_ROW;
131473     }else{
131474       int nDoclist = 0;           /* Size of doclist */
131475       sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */
131476
131477       /* The current term of the first nMerge entries in the array
131478       ** of Fts3SegReader objects is the same. The doclists must be merged
131479       ** and a single term returned with the merged doclist.
131480       */
131481       for(i=0; i<nMerge; i++){
131482         fts3SegReaderFirstDocid(p, apSegment[i]);
131483       }
131484       fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
131485       while( apSegment[0]->pOffsetList ){
131486         int j;                    /* Number of segments that share a docid */
131487         char *pList;
131488         int nList;
131489         int nByte;
131490         sqlite3_int64 iDocid = apSegment[0]->iDocid;
131491         fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
131492         j = 1;
131493         while( j<nMerge
131494             && apSegment[j]->pOffsetList
131495             && apSegment[j]->iDocid==iDocid
131496         ){
131497           fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
131498           j++;
131499         }
131500
131501         if( isColFilter ){
131502           fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
131503         }
131504
131505         if( !isIgnoreEmpty || nList>0 ){
131506
131507           /* Calculate the 'docid' delta value to write into the merged 
131508           ** doclist. */
131509           sqlite3_int64 iDelta;
131510           if( p->bDescIdx && nDoclist>0 ){
131511             iDelta = iPrev - iDocid;
131512           }else{
131513             iDelta = iDocid - iPrev;
131514           }
131515           assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
131516           assert( nDoclist>0 || iDelta==iDocid );
131517
131518           nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
131519           if( nDoclist+nByte>pCsr->nBuffer ){
131520             char *aNew;
131521             pCsr->nBuffer = (nDoclist+nByte)*2;
131522             aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
131523             if( !aNew ){
131524               return SQLITE_NOMEM;
131525             }
131526             pCsr->aBuffer = aNew;
131527           }
131528
131529           if( isFirst ){
131530             char *a = &pCsr->aBuffer[nDoclist];
131531             int nWrite;
131532            
131533             nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
131534             if( nWrite ){
131535               iPrev = iDocid;
131536               nDoclist += nWrite;
131537             }
131538           }else{
131539             nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
131540             iPrev = iDocid;
131541             if( isRequirePos ){
131542               memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
131543               nDoclist += nList;
131544               pCsr->aBuffer[nDoclist++] = '\0';
131545             }
131546           }
131547         }
131548
131549         fts3SegReaderSort(apSegment, nMerge, j, xCmp);
131550       }
131551       if( nDoclist>0 ){
131552         pCsr->aDoclist = pCsr->aBuffer;
131553         pCsr->nDoclist = nDoclist;
131554         rc = SQLITE_ROW;
131555       }
131556     }
131557     pCsr->nAdvance = nMerge;
131558   }while( rc==SQLITE_OK );
131559
131560   return rc;
131561 }
131562
131563
131564 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
131565   Fts3MultiSegReader *pCsr       /* Cursor object */
131566 ){
131567   if( pCsr ){
131568     int i;
131569     for(i=0; i<pCsr->nSegment; i++){
131570       sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
131571     }
131572     sqlite3_free(pCsr->apSegment);
131573     sqlite3_free(pCsr->aBuffer);
131574
131575     pCsr->nSegment = 0;
131576     pCsr->apSegment = 0;
131577     pCsr->aBuffer = 0;
131578   }
131579 }
131580
131581 /*
131582 ** Merge all level iLevel segments in the database into a single 
131583 ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
131584 ** single segment with a level equal to the numerically largest level 
131585 ** currently present in the database.
131586 **
131587 ** If this function is called with iLevel<0, but there is only one
131588 ** segment in the database, SQLITE_DONE is returned immediately. 
131589 ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs, 
131590 ** an SQLite error code is returned.
131591 */
131592 static int fts3SegmentMerge(
131593   Fts3Table *p, 
131594   int iLangid,                    /* Language id to merge */
131595   int iIndex,                     /* Index in p->aIndex[] to merge */
131596   int iLevel                      /* Level to merge */
131597 ){
131598   int rc;                         /* Return code */
131599   int iIdx = 0;                   /* Index of new segment */
131600   sqlite3_int64 iNewLevel = 0;    /* Level/index to create new segment at */
131601   SegmentWriter *pWriter = 0;     /* Used to write the new, merged, segment */
131602   Fts3SegFilter filter;           /* Segment term filter condition */
131603   Fts3MultiSegReader csr;         /* Cursor to iterate through level(s) */
131604   int bIgnoreEmpty = 0;           /* True to ignore empty segments */
131605
131606   assert( iLevel==FTS3_SEGCURSOR_ALL
131607        || iLevel==FTS3_SEGCURSOR_PENDING
131608        || iLevel>=0
131609   );
131610   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
131611   assert( iIndex>=0 && iIndex<p->nIndex );
131612
131613   rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
131614   if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
131615
131616   if( iLevel==FTS3_SEGCURSOR_ALL ){
131617     /* This call is to merge all segments in the database to a single
131618     ** segment. The level of the new segment is equal to the numerically
131619     ** greatest segment level currently present in the database for this
131620     ** index. The idx of the new segment is always 0.  */
131621     if( csr.nSegment==1 ){
131622       rc = SQLITE_DONE;
131623       goto finished;
131624     }
131625     rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iNewLevel);
131626     bIgnoreEmpty = 1;
131627
131628   }else if( iLevel==FTS3_SEGCURSOR_PENDING ){
131629     iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, 0);
131630     rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, 0, &iIdx);
131631   }else{
131632     /* This call is to merge all segments at level iLevel. find the next
131633     ** available segment index at level iLevel+1. The call to
131634     ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to 
131635     ** a single iLevel+2 segment if necessary.  */
131636     rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
131637     iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
131638   }
131639   if( rc!=SQLITE_OK ) goto finished;
131640   assert( csr.nSegment>0 );
131641   assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
131642   assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
131643
131644   memset(&filter, 0, sizeof(Fts3SegFilter));
131645   filter.flags = FTS3_SEGMENT_REQUIRE_POS;
131646   filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
131647
131648   rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
131649   while( SQLITE_OK==rc ){
131650     rc = sqlite3Fts3SegReaderStep(p, &csr);
131651     if( rc!=SQLITE_ROW ) break;
131652     rc = fts3SegWriterAdd(p, &pWriter, 1, 
131653         csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
131654   }
131655   if( rc!=SQLITE_OK ) goto finished;
131656   assert( pWriter );
131657
131658   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
131659     rc = fts3DeleteSegdir(
131660         p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
131661     );
131662     if( rc!=SQLITE_OK ) goto finished;
131663   }
131664   rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
131665
131666  finished:
131667   fts3SegWriterFree(pWriter);
131668   sqlite3Fts3SegReaderFinish(&csr);
131669   return rc;
131670 }
131671
131672
131673 /* 
131674 ** Flush the contents of pendingTerms to level 0 segments.
131675 */
131676 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
131677   int rc = SQLITE_OK;
131678   int i;
131679         
131680   for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
131681     rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
131682     if( rc==SQLITE_DONE ) rc = SQLITE_OK;
131683   }
131684   sqlite3Fts3PendingTermsClear(p);
131685
131686   /* Determine the auto-incr-merge setting if unknown.  If enabled,
131687   ** estimate the number of leaf blocks of content to be written
131688   */
131689   if( rc==SQLITE_OK && p->bHasStat
131690    && p->bAutoincrmerge==0xff && p->nLeafAdd>0
131691   ){
131692     sqlite3_stmt *pStmt = 0;
131693     rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
131694     if( rc==SQLITE_OK ){
131695       sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
131696       rc = sqlite3_step(pStmt);
131697       p->bAutoincrmerge = (rc==SQLITE_ROW && sqlite3_column_int(pStmt, 0));
131698       rc = sqlite3_reset(pStmt);
131699     }
131700   }
131701   return rc;
131702 }
131703
131704 /*
131705 ** Encode N integers as varints into a blob.
131706 */
131707 static void fts3EncodeIntArray(
131708   int N,             /* The number of integers to encode */
131709   u32 *a,            /* The integer values */
131710   char *zBuf,        /* Write the BLOB here */
131711   int *pNBuf         /* Write number of bytes if zBuf[] used here */
131712 ){
131713   int i, j;
131714   for(i=j=0; i<N; i++){
131715     j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
131716   }
131717   *pNBuf = j;
131718 }
131719
131720 /*
131721 ** Decode a blob of varints into N integers
131722 */
131723 static void fts3DecodeIntArray(
131724   int N,             /* The number of integers to decode */
131725   u32 *a,            /* Write the integer values */
131726   const char *zBuf,  /* The BLOB containing the varints */
131727   int nBuf           /* size of the BLOB */
131728 ){
131729   int i, j;
131730   UNUSED_PARAMETER(nBuf);
131731   for(i=j=0; i<N; i++){
131732     sqlite3_int64 x;
131733     j += sqlite3Fts3GetVarint(&zBuf[j], &x);
131734     assert(j<=nBuf);
131735     a[i] = (u32)(x & 0xffffffff);
131736   }
131737 }
131738
131739 /*
131740 ** Insert the sizes (in tokens) for each column of the document
131741 ** with docid equal to p->iPrevDocid.  The sizes are encoded as
131742 ** a blob of varints.
131743 */
131744 static void fts3InsertDocsize(
131745   int *pRC,                       /* Result code */
131746   Fts3Table *p,                   /* Table into which to insert */
131747   u32 *aSz                        /* Sizes of each column, in tokens */
131748 ){
131749   char *pBlob;             /* The BLOB encoding of the document size */
131750   int nBlob;               /* Number of bytes in the BLOB */
131751   sqlite3_stmt *pStmt;     /* Statement used to insert the encoding */
131752   int rc;                  /* Result code from subfunctions */
131753
131754   if( *pRC ) return;
131755   pBlob = sqlite3_malloc( 10*p->nColumn );
131756   if( pBlob==0 ){
131757     *pRC = SQLITE_NOMEM;
131758     return;
131759   }
131760   fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
131761   rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
131762   if( rc ){
131763     sqlite3_free(pBlob);
131764     *pRC = rc;
131765     return;
131766   }
131767   sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
131768   sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
131769   sqlite3_step(pStmt);
131770   *pRC = sqlite3_reset(pStmt);
131771 }
131772
131773 /*
131774 ** Record 0 of the %_stat table contains a blob consisting of N varints,
131775 ** where N is the number of user defined columns in the fts3 table plus
131776 ** two. If nCol is the number of user defined columns, then values of the 
131777 ** varints are set as follows:
131778 **
131779 **   Varint 0:       Total number of rows in the table.
131780 **
131781 **   Varint 1..nCol: For each column, the total number of tokens stored in
131782 **                   the column for all rows of the table.
131783 **
131784 **   Varint 1+nCol:  The total size, in bytes, of all text values in all
131785 **                   columns of all rows of the table.
131786 **
131787 */
131788 static void fts3UpdateDocTotals(
131789   int *pRC,                       /* The result code */
131790   Fts3Table *p,                   /* Table being updated */
131791   u32 *aSzIns,                    /* Size increases */
131792   u32 *aSzDel,                    /* Size decreases */
131793   int nChng                       /* Change in the number of documents */
131794 ){
131795   char *pBlob;             /* Storage for BLOB written into %_stat */
131796   int nBlob;               /* Size of BLOB written into %_stat */
131797   u32 *a;                  /* Array of integers that becomes the BLOB */
131798   sqlite3_stmt *pStmt;     /* Statement for reading and writing */
131799   int i;                   /* Loop counter */
131800   int rc;                  /* Result code from subfunctions */
131801
131802   const int nStat = p->nColumn+2;
131803
131804   if( *pRC ) return;
131805   a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
131806   if( a==0 ){
131807     *pRC = SQLITE_NOMEM;
131808     return;
131809   }
131810   pBlob = (char*)&a[nStat];
131811   rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
131812   if( rc ){
131813     sqlite3_free(a);
131814     *pRC = rc;
131815     return;
131816   }
131817   sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
131818   if( sqlite3_step(pStmt)==SQLITE_ROW ){
131819     fts3DecodeIntArray(nStat, a,
131820          sqlite3_column_blob(pStmt, 0),
131821          sqlite3_column_bytes(pStmt, 0));
131822   }else{
131823     memset(a, 0, sizeof(u32)*(nStat) );
131824   }
131825   rc = sqlite3_reset(pStmt);
131826   if( rc!=SQLITE_OK ){
131827     sqlite3_free(a);
131828     *pRC = rc;
131829     return;
131830   }
131831   if( nChng<0 && a[0]<(u32)(-nChng) ){
131832     a[0] = 0;
131833   }else{
131834     a[0] += nChng;
131835   }
131836   for(i=0; i<p->nColumn+1; i++){
131837     u32 x = a[i+1];
131838     if( x+aSzIns[i] < aSzDel[i] ){
131839       x = 0;
131840     }else{
131841       x = x + aSzIns[i] - aSzDel[i];
131842     }
131843     a[i+1] = x;
131844   }
131845   fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
131846   rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
131847   if( rc ){
131848     sqlite3_free(a);
131849     *pRC = rc;
131850     return;
131851   }
131852   sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
131853   sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
131854   sqlite3_step(pStmt);
131855   *pRC = sqlite3_reset(pStmt);
131856   sqlite3_free(a);
131857 }
131858
131859 /*
131860 ** Merge the entire database so that there is one segment for each 
131861 ** iIndex/iLangid combination.
131862 */
131863 static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
131864   int bSeenDone = 0;
131865   int rc;
131866   sqlite3_stmt *pAllLangid = 0;
131867
131868   rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
131869   if( rc==SQLITE_OK ){
131870     int rc2;
131871     sqlite3_bind_int(pAllLangid, 1, p->nIndex);
131872     while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
131873       int i;
131874       int iLangid = sqlite3_column_int(pAllLangid, 0);
131875       for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
131876         rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
131877         if( rc==SQLITE_DONE ){
131878           bSeenDone = 1;
131879           rc = SQLITE_OK;
131880         }
131881       }
131882     }
131883     rc2 = sqlite3_reset(pAllLangid);
131884     if( rc==SQLITE_OK ) rc = rc2;
131885   }
131886
131887   sqlite3Fts3SegmentsClose(p);
131888   sqlite3Fts3PendingTermsClear(p);
131889
131890   return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
131891 }
131892
131893 /*
131894 ** This function is called when the user executes the following statement:
131895 **
131896 **     INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
131897 **
131898 ** The entire FTS index is discarded and rebuilt. If the table is one 
131899 ** created using the content=xxx option, then the new index is based on
131900 ** the current contents of the xxx table. Otherwise, it is rebuilt based
131901 ** on the contents of the %_content table.
131902 */
131903 static int fts3DoRebuild(Fts3Table *p){
131904   int rc;                         /* Return Code */
131905
131906   rc = fts3DeleteAll(p, 0);
131907   if( rc==SQLITE_OK ){
131908     u32 *aSz = 0;
131909     u32 *aSzIns = 0;
131910     u32 *aSzDel = 0;
131911     sqlite3_stmt *pStmt = 0;
131912     int nEntry = 0;
131913
131914     /* Compose and prepare an SQL statement to loop through the content table */
131915     char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
131916     if( !zSql ){
131917       rc = SQLITE_NOMEM;
131918     }else{
131919       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
131920       sqlite3_free(zSql);
131921     }
131922
131923     if( rc==SQLITE_OK ){
131924       int nByte = sizeof(u32) * (p->nColumn+1)*3;
131925       aSz = (u32 *)sqlite3_malloc(nByte);
131926       if( aSz==0 ){
131927         rc = SQLITE_NOMEM;
131928       }else{
131929         memset(aSz, 0, nByte);
131930         aSzIns = &aSz[p->nColumn+1];
131931         aSzDel = &aSzIns[p->nColumn+1];
131932       }
131933     }
131934
131935     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
131936       int iCol;
131937       int iLangid = langidFromSelect(p, pStmt);
131938       rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pStmt, 0));
131939       memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
131940       for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
131941         const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
131942         rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
131943         aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
131944       }
131945       if( p->bHasDocsize ){
131946         fts3InsertDocsize(&rc, p, aSz);
131947       }
131948       if( rc!=SQLITE_OK ){
131949         sqlite3_finalize(pStmt);
131950         pStmt = 0;
131951       }else{
131952         nEntry++;
131953         for(iCol=0; iCol<=p->nColumn; iCol++){
131954           aSzIns[iCol] += aSz[iCol];
131955         }
131956       }
131957     }
131958     if( p->bFts4 ){
131959       fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
131960     }
131961     sqlite3_free(aSz);
131962
131963     if( pStmt ){
131964       int rc2 = sqlite3_finalize(pStmt);
131965       if( rc==SQLITE_OK ){
131966         rc = rc2;
131967       }
131968     }
131969   }
131970
131971   return rc;
131972 }
131973
131974
131975 /*
131976 ** This function opens a cursor used to read the input data for an 
131977 ** incremental merge operation. Specifically, it opens a cursor to scan
131978 ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute 
131979 ** level iAbsLevel.
131980 */
131981 static int fts3IncrmergeCsr(
131982   Fts3Table *p,                   /* FTS3 table handle */
131983   sqlite3_int64 iAbsLevel,        /* Absolute level to open */
131984   int nSeg,                       /* Number of segments to merge */
131985   Fts3MultiSegReader *pCsr        /* Cursor object to populate */
131986 ){
131987   int rc;                         /* Return Code */
131988   sqlite3_stmt *pStmt = 0;        /* Statement used to read %_segdir entry */  
131989   int nByte;                      /* Bytes allocated at pCsr->apSegment[] */
131990
131991   /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
131992   memset(pCsr, 0, sizeof(*pCsr));
131993   nByte = sizeof(Fts3SegReader *) * nSeg;
131994   pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
131995
131996   if( pCsr->apSegment==0 ){
131997     rc = SQLITE_NOMEM;
131998   }else{
131999     memset(pCsr->apSegment, 0, nByte);
132000     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
132001   }
132002   if( rc==SQLITE_OK ){
132003     int i;
132004     int rc2;
132005     sqlite3_bind_int64(pStmt, 1, iAbsLevel);
132006     assert( pCsr->nSegment==0 );
132007     for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
132008       rc = sqlite3Fts3SegReaderNew(i, 0,
132009           sqlite3_column_int64(pStmt, 1),        /* segdir.start_block */
132010           sqlite3_column_int64(pStmt, 2),        /* segdir.leaves_end_block */
132011           sqlite3_column_int64(pStmt, 3),        /* segdir.end_block */
132012           sqlite3_column_blob(pStmt, 4),         /* segdir.root */
132013           sqlite3_column_bytes(pStmt, 4),        /* segdir.root */
132014           &pCsr->apSegment[i]
132015       );
132016       pCsr->nSegment++;
132017     }
132018     rc2 = sqlite3_reset(pStmt);
132019     if( rc==SQLITE_OK ) rc = rc2;
132020   }
132021
132022   return rc;
132023 }
132024
132025 typedef struct IncrmergeWriter IncrmergeWriter;
132026 typedef struct NodeWriter NodeWriter;
132027 typedef struct Blob Blob;
132028 typedef struct NodeReader NodeReader;
132029
132030 /*
132031 ** An instance of the following structure is used as a dynamic buffer
132032 ** to build up nodes or other blobs of data in.
132033 **
132034 ** The function blobGrowBuffer() is used to extend the allocation.
132035 */
132036 struct Blob {
132037   char *a;                        /* Pointer to allocation */
132038   int n;                          /* Number of valid bytes of data in a[] */
132039   int nAlloc;                     /* Allocated size of a[] (nAlloc>=n) */
132040 };
132041
132042 /*
132043 ** This structure is used to build up buffers containing segment b-tree 
132044 ** nodes (blocks).
132045 */
132046 struct NodeWriter {
132047   sqlite3_int64 iBlock;           /* Current block id */
132048   Blob key;                       /* Last key written to the current block */
132049   Blob block;                     /* Current block image */
132050 };
132051
132052 /*
132053 ** An object of this type contains the state required to create or append
132054 ** to an appendable b-tree segment.
132055 */
132056 struct IncrmergeWriter {
132057   int nLeafEst;                   /* Space allocated for leaf blocks */
132058   int nWork;                      /* Number of leaf pages flushed */
132059   sqlite3_int64 iAbsLevel;        /* Absolute level of input segments */
132060   int iIdx;                       /* Index of *output* segment in iAbsLevel+1 */
132061   sqlite3_int64 iStart;           /* Block number of first allocated block */
132062   sqlite3_int64 iEnd;             /* Block number of last allocated block */
132063   NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
132064 };
132065
132066 /*
132067 ** An object of the following type is used to read data from a single
132068 ** FTS segment node. See the following functions:
132069 **
132070 **     nodeReaderInit()
132071 **     nodeReaderNext()
132072 **     nodeReaderRelease()
132073 */
132074 struct NodeReader {
132075   const char *aNode;
132076   int nNode;
132077   int iOff;                       /* Current offset within aNode[] */
132078
132079   /* Output variables. Containing the current node entry. */
132080   sqlite3_int64 iChild;           /* Pointer to child node */
132081   Blob term;                      /* Current term */
132082   const char *aDoclist;           /* Pointer to doclist */
132083   int nDoclist;                   /* Size of doclist in bytes */
132084 };
132085
132086 /*
132087 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
132088 ** Otherwise, if the allocation at pBlob->a is not already at least nMin
132089 ** bytes in size, extend (realloc) it to be so.
132090 **
132091 ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
132092 ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
132093 ** to reflect the new size of the pBlob->a[] buffer.
132094 */
132095 static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
132096   if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
132097     int nAlloc = nMin;
132098     char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
132099     if( a ){
132100       pBlob->nAlloc = nAlloc;
132101       pBlob->a = a;
132102     }else{
132103       *pRc = SQLITE_NOMEM;
132104     }
132105   }
132106 }
132107
132108 /*
132109 ** Attempt to advance the node-reader object passed as the first argument to
132110 ** the next entry on the node. 
132111 **
132112 ** Return an error code if an error occurs (SQLITE_NOMEM is possible). 
132113 ** Otherwise return SQLITE_OK. If there is no next entry on the node
132114 ** (e.g. because the current entry is the last) set NodeReader->aNode to
132115 ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output 
132116 ** variables for the new entry.
132117 */
132118 static int nodeReaderNext(NodeReader *p){
132119   int bFirst = (p->term.n==0);    /* True for first term on the node */
132120   int nPrefix = 0;                /* Bytes to copy from previous term */
132121   int nSuffix = 0;                /* Bytes to append to the prefix */
132122   int rc = SQLITE_OK;             /* Return code */
132123
132124   assert( p->aNode );
132125   if( p->iChild && bFirst==0 ) p->iChild++;
132126   if( p->iOff>=p->nNode ){
132127     /* EOF */
132128     p->aNode = 0;
132129   }else{
132130     if( bFirst==0 ){
132131       p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
132132     }
132133     p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
132134
132135     blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
132136     if( rc==SQLITE_OK ){
132137       memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
132138       p->term.n = nPrefix+nSuffix;
132139       p->iOff += nSuffix;
132140       if( p->iChild==0 ){
132141         p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
132142         p->aDoclist = &p->aNode[p->iOff];
132143         p->iOff += p->nDoclist;
132144       }
132145     }
132146   }
132147
132148   assert( p->iOff<=p->nNode );
132149
132150   return rc;
132151 }
132152
132153 /*
132154 ** Release all dynamic resources held by node-reader object *p.
132155 */
132156 static void nodeReaderRelease(NodeReader *p){
132157   sqlite3_free(p->term.a);
132158 }
132159
132160 /*
132161 ** Initialize a node-reader object to read the node in buffer aNode/nNode.
132162 **
132163 ** If successful, SQLITE_OK is returned and the NodeReader object set to 
132164 ** point to the first entry on the node (if any). Otherwise, an SQLite
132165 ** error code is returned.
132166 */
132167 static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
132168   memset(p, 0, sizeof(NodeReader));
132169   p->aNode = aNode;
132170   p->nNode = nNode;
132171
132172   /* Figure out if this is a leaf or an internal node. */
132173   if( p->aNode[0] ){
132174     /* An internal node. */
132175     p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
132176   }else{
132177     p->iOff = 1;
132178   }
132179
132180   return nodeReaderNext(p);
132181 }
132182
132183 /*
132184 ** This function is called while writing an FTS segment each time a leaf o
132185 ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
132186 ** to be greater than the largest key on the node just written, but smaller
132187 ** than or equal to the first key that will be written to the next leaf
132188 ** node.
132189 **
132190 ** The block id of the leaf node just written to disk may be found in
132191 ** (pWriter->aNodeWriter[0].iBlock) when this function is called.
132192 */
132193 static int fts3IncrmergePush(
132194   Fts3Table *p,                   /* Fts3 table handle */
132195   IncrmergeWriter *pWriter,       /* Writer object */
132196   const char *zTerm,              /* Term to write to internal node */
132197   int nTerm                       /* Bytes at zTerm */
132198 ){
132199   sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
132200   int iLayer;
132201
132202   assert( nTerm>0 );
132203   for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
132204     sqlite3_int64 iNextPtr = 0;
132205     NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
132206     int rc = SQLITE_OK;
132207     int nPrefix;
132208     int nSuffix;
132209     int nSpace;
132210
132211     /* Figure out how much space the key will consume if it is written to
132212     ** the current node of layer iLayer. Due to the prefix compression, 
132213     ** the space required changes depending on which node the key is to
132214     ** be added to.  */
132215     nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
132216     nSuffix = nTerm - nPrefix;
132217     nSpace  = sqlite3Fts3VarintLen(nPrefix);
132218     nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
132219
132220     if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){ 
132221       /* If the current node of layer iLayer contains zero keys, or if adding
132222       ** the key to it will not cause it to grow to larger than nNodeSize 
132223       ** bytes in size, write the key here.  */
132224
132225       Blob *pBlk = &pNode->block;
132226       if( pBlk->n==0 ){
132227         blobGrowBuffer(pBlk, p->nNodeSize, &rc);
132228         if( rc==SQLITE_OK ){
132229           pBlk->a[0] = (char)iLayer;
132230           pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
132231         }
132232       }
132233       blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
132234       blobGrowBuffer(&pNode->key, nTerm, &rc);
132235
132236       if( rc==SQLITE_OK ){
132237         if( pNode->key.n ){
132238           pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
132239         }
132240         pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
132241         memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
132242         pBlk->n += nSuffix;
132243
132244         memcpy(pNode->key.a, zTerm, nTerm);
132245         pNode->key.n = nTerm;
132246       }
132247     }else{
132248       /* Otherwise, flush the current node of layer iLayer to disk.
132249       ** Then allocate a new, empty sibling node. The key will be written
132250       ** into the parent of this node. */
132251       rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
132252
132253       assert( pNode->block.nAlloc>=p->nNodeSize );
132254       pNode->block.a[0] = (char)iLayer;
132255       pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
132256
132257       iNextPtr = pNode->iBlock;
132258       pNode->iBlock++;
132259       pNode->key.n = 0;
132260     }
132261
132262     if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
132263     iPtr = iNextPtr;
132264   }
132265
132266   assert( 0 );
132267   return 0;
132268 }
132269
132270 /*
132271 ** Append a term and (optionally) doclist to the FTS segment node currently
132272 ** stored in blob *pNode. The node need not contain any terms, but the
132273 ** header must be written before this function is called.
132274 **
132275 ** A node header is a single 0x00 byte for a leaf node, or a height varint
132276 ** followed by the left-hand-child varint for an internal node.
132277 **
132278 ** The term to be appended is passed via arguments zTerm/nTerm. For a 
132279 ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
132280 ** node, both aDoclist and nDoclist must be passed 0.
132281 **
132282 ** If the size of the value in blob pPrev is zero, then this is the first
132283 ** term written to the node. Otherwise, pPrev contains a copy of the 
132284 ** previous term. Before this function returns, it is updated to contain a
132285 ** copy of zTerm/nTerm.
132286 **
132287 ** It is assumed that the buffer associated with pNode is already large
132288 ** enough to accommodate the new entry. The buffer associated with pPrev
132289 ** is extended by this function if requrired.
132290 **
132291 ** If an error (i.e. OOM condition) occurs, an SQLite error code is
132292 ** returned. Otherwise, SQLITE_OK.
132293 */
132294 static int fts3AppendToNode(
132295   Blob *pNode,                    /* Current node image to append to */
132296   Blob *pPrev,                    /* Buffer containing previous term written */
132297   const char *zTerm,              /* New term to write */
132298   int nTerm,                      /* Size of zTerm in bytes */
132299   const char *aDoclist,           /* Doclist (or NULL) to write */
132300   int nDoclist                    /* Size of aDoclist in bytes */ 
132301 ){
132302   int rc = SQLITE_OK;             /* Return code */
132303   int bFirst = (pPrev->n==0);     /* True if this is the first term written */
132304   int nPrefix;                    /* Size of term prefix in bytes */
132305   int nSuffix;                    /* Size of term suffix in bytes */
132306
132307   /* Node must have already been started. There must be a doclist for a
132308   ** leaf node, and there must not be a doclist for an internal node.  */
132309   assert( pNode->n>0 );
132310   assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
132311
132312   blobGrowBuffer(pPrev, nTerm, &rc);
132313   if( rc!=SQLITE_OK ) return rc;
132314
132315   nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
132316   nSuffix = nTerm - nPrefix;
132317   memcpy(pPrev->a, zTerm, nTerm);
132318   pPrev->n = nTerm;
132319
132320   if( bFirst==0 ){
132321     pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
132322   }
132323   pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
132324   memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
132325   pNode->n += nSuffix;
132326
132327   if( aDoclist ){
132328     pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
132329     memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
132330     pNode->n += nDoclist;
132331   }
132332
132333   assert( pNode->n<=pNode->nAlloc );
132334
132335   return SQLITE_OK;
132336 }
132337
132338 /*
132339 ** Append the current term and doclist pointed to by cursor pCsr to the
132340 ** appendable b-tree segment opened for writing by pWriter.
132341 **
132342 ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
132343 */
132344 static int fts3IncrmergeAppend(
132345   Fts3Table *p,                   /* Fts3 table handle */
132346   IncrmergeWriter *pWriter,       /* Writer object */
132347   Fts3MultiSegReader *pCsr        /* Cursor containing term and doclist */
132348 ){
132349   const char *zTerm = pCsr->zTerm;
132350   int nTerm = pCsr->nTerm;
132351   const char *aDoclist = pCsr->aDoclist;
132352   int nDoclist = pCsr->nDoclist;
132353   int rc = SQLITE_OK;           /* Return code */
132354   int nSpace;                   /* Total space in bytes required on leaf */
132355   int nPrefix;                  /* Size of prefix shared with previous term */
132356   int nSuffix;                  /* Size of suffix (nTerm - nPrefix) */
132357   NodeWriter *pLeaf;            /* Object used to write leaf nodes */
132358
132359   pLeaf = &pWriter->aNodeWriter[0];
132360   nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
132361   nSuffix = nTerm - nPrefix;
132362
132363   nSpace  = sqlite3Fts3VarintLen(nPrefix);
132364   nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
132365   nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
132366
132367   /* If the current block is not empty, and if adding this term/doclist
132368   ** to the current block would make it larger than Fts3Table.nNodeSize
132369   ** bytes, write this block out to the database. */
132370   if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
132371     rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
132372     pWriter->nWork++;
132373
132374     /* Add the current term to the parent node. The term added to the 
132375     ** parent must:
132376     **
132377     **   a) be greater than the largest term on the leaf node just written
132378     **      to the database (still available in pLeaf->key), and
132379     **
132380     **   b) be less than or equal to the term about to be added to the new
132381     **      leaf node (zTerm/nTerm).
132382     **
132383     ** In other words, it must be the prefix of zTerm 1 byte longer than
132384     ** the common prefix (if any) of zTerm and pWriter->zTerm.
132385     */
132386     if( rc==SQLITE_OK ){
132387       rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
132388     }
132389
132390     /* Advance to the next output block */
132391     pLeaf->iBlock++;
132392     pLeaf->key.n = 0;
132393     pLeaf->block.n = 0;
132394
132395     nSuffix = nTerm;
132396     nSpace  = 1;
132397     nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
132398     nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
132399   }
132400
132401   blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
132402
132403   if( rc==SQLITE_OK ){
132404     if( pLeaf->block.n==0 ){
132405       pLeaf->block.n = 1;
132406       pLeaf->block.a[0] = '\0';
132407     }
132408     rc = fts3AppendToNode(
132409         &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
132410     );
132411   }
132412
132413   return rc;
132414 }
132415
132416 /*
132417 ** This function is called to release all dynamic resources held by the
132418 ** merge-writer object pWriter, and if no error has occurred, to flush
132419 ** all outstanding node buffers held by pWriter to disk.
132420 **
132421 ** If *pRc is not SQLITE_OK when this function is called, then no attempt
132422 ** is made to write any data to disk. Instead, this function serves only
132423 ** to release outstanding resources.
132424 **
132425 ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
132426 ** flushing buffers to disk, *pRc is set to an SQLite error code before
132427 ** returning.
132428 */
132429 static void fts3IncrmergeRelease(
132430   Fts3Table *p,                   /* FTS3 table handle */
132431   IncrmergeWriter *pWriter,       /* Merge-writer object */
132432   int *pRc                        /* IN/OUT: Error code */
132433 ){
132434   int i;                          /* Used to iterate through non-root layers */
132435   int iRoot;                      /* Index of root in pWriter->aNodeWriter */
132436   NodeWriter *pRoot;              /* NodeWriter for root node */
132437   int rc = *pRc;                  /* Error code */
132438
132439   /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment 
132440   ** root node. If the segment fits entirely on a single leaf node, iRoot
132441   ** will be set to 0. If the root node is the parent of the leaves, iRoot
132442   ** will be 1. And so on.  */
132443   for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
132444     NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
132445     if( pNode->block.n>0 ) break;
132446     assert( *pRc || pNode->block.nAlloc==0 );
132447     assert( *pRc || pNode->key.nAlloc==0 );
132448     sqlite3_free(pNode->block.a);
132449     sqlite3_free(pNode->key.a);
132450   }
132451
132452   /* Empty output segment. This is a no-op. */
132453   if( iRoot<0 ) return;
132454
132455   /* The entire output segment fits on a single node. Normally, this means
132456   ** the node would be stored as a blob in the "root" column of the %_segdir
132457   ** table. However, this is not permitted in this case. The problem is that 
132458   ** space has already been reserved in the %_segments table, and so the 
132459   ** start_block and end_block fields of the %_segdir table must be populated. 
132460   ** And, by design or by accident, released versions of FTS cannot handle 
132461   ** segments that fit entirely on the root node with start_block!=0.
132462   **
132463   ** Instead, create a synthetic root node that contains nothing but a 
132464   ** pointer to the single content node. So that the segment consists of a
132465   ** single leaf and a single interior (root) node.
132466   **
132467   ** Todo: Better might be to defer allocating space in the %_segments 
132468   ** table until we are sure it is needed.
132469   */
132470   if( iRoot==0 ){
132471     Blob *pBlock = &pWriter->aNodeWriter[1].block;
132472     blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
132473     if( rc==SQLITE_OK ){
132474       pBlock->a[0] = 0x01;
132475       pBlock->n = 1 + sqlite3Fts3PutVarint(
132476           &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
132477       );
132478     }
132479     iRoot = 1;
132480   }
132481   pRoot = &pWriter->aNodeWriter[iRoot];
132482
132483   /* Flush all currently outstanding nodes to disk. */
132484   for(i=0; i<iRoot; i++){
132485     NodeWriter *pNode = &pWriter->aNodeWriter[i];
132486     if( pNode->block.n>0 && rc==SQLITE_OK ){
132487       rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
132488     }
132489     sqlite3_free(pNode->block.a);
132490     sqlite3_free(pNode->key.a);
132491   }
132492
132493   /* Write the %_segdir record. */
132494   if( rc==SQLITE_OK ){
132495     rc = fts3WriteSegdir(p, 
132496         pWriter->iAbsLevel+1,               /* level */
132497         pWriter->iIdx,                      /* idx */
132498         pWriter->iStart,                    /* start_block */
132499         pWriter->aNodeWriter[0].iBlock,     /* leaves_end_block */
132500         pWriter->iEnd,                      /* end_block */
132501         pRoot->block.a, pRoot->block.n      /* root */
132502     );
132503   }
132504   sqlite3_free(pRoot->block.a);
132505   sqlite3_free(pRoot->key.a);
132506
132507   *pRc = rc;
132508 }
132509
132510 /*
132511 ** Compare the term in buffer zLhs (size in bytes nLhs) with that in
132512 ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
132513 ** the other, it is considered to be smaller than the other.
132514 **
132515 ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
132516 ** if it is greater.
132517 */
132518 static int fts3TermCmp(
132519   const char *zLhs, int nLhs,     /* LHS of comparison */
132520   const char *zRhs, int nRhs      /* RHS of comparison */
132521 ){
132522   int nCmp = MIN(nLhs, nRhs);
132523   int res;
132524
132525   res = memcmp(zLhs, zRhs, nCmp);
132526   if( res==0 ) res = nLhs - nRhs;
132527
132528   return res;
132529 }
132530
132531
132532 /*
132533 ** Query to see if the entry in the %_segments table with blockid iEnd is 
132534 ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
132535 ** returning. Otherwise, set *pbRes to 0. 
132536 **
132537 ** Or, if an error occurs while querying the database, return an SQLite 
132538 ** error code. The final value of *pbRes is undefined in this case.
132539 **
132540 ** This is used to test if a segment is an "appendable" segment. If it
132541 ** is, then a NULL entry has been inserted into the %_segments table
132542 ** with blockid %_segdir.end_block.
132543 */
132544 static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
132545   int bRes = 0;                   /* Result to set *pbRes to */
132546   sqlite3_stmt *pCheck = 0;       /* Statement to query database with */
132547   int rc;                         /* Return code */
132548
132549   rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
132550   if( rc==SQLITE_OK ){
132551     sqlite3_bind_int64(pCheck, 1, iEnd);
132552     if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
132553     rc = sqlite3_reset(pCheck);
132554   }
132555   
132556   *pbRes = bRes;
132557   return rc;
132558 }
132559
132560 /*
132561 ** This function is called when initializing an incremental-merge operation.
132562 ** It checks if the existing segment with index value iIdx at absolute level 
132563 ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
132564 ** merge-writer object *pWriter is initialized to write to it.
132565 **
132566 ** An existing segment can be appended to by an incremental merge if:
132567 **
132568 **   * It was initially created as an appendable segment (with all required
132569 **     space pre-allocated), and
132570 **
132571 **   * The first key read from the input (arguments zKey and nKey) is 
132572 **     greater than the largest key currently stored in the potential
132573 **     output segment.
132574 */
132575 static int fts3IncrmergeLoad(
132576   Fts3Table *p,                   /* Fts3 table handle */
132577   sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
132578   int iIdx,                       /* Index of candidate output segment */
132579   const char *zKey,               /* First key to write */
132580   int nKey,                       /* Number of bytes in nKey */
132581   IncrmergeWriter *pWriter        /* Populate this object */
132582 ){
132583   int rc;                         /* Return code */
132584   sqlite3_stmt *pSelect = 0;      /* SELECT to read %_segdir entry */
132585
132586   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
132587   if( rc==SQLITE_OK ){
132588     sqlite3_int64 iStart = 0;     /* Value of %_segdir.start_block */
132589     sqlite3_int64 iLeafEnd = 0;   /* Value of %_segdir.leaves_end_block */
132590     sqlite3_int64 iEnd = 0;       /* Value of %_segdir.end_block */
132591     const char *aRoot = 0;        /* Pointer to %_segdir.root buffer */
132592     int nRoot = 0;                /* Size of aRoot[] in bytes */
132593     int rc2;                      /* Return code from sqlite3_reset() */
132594     int bAppendable = 0;          /* Set to true if segment is appendable */
132595
132596     /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
132597     sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
132598     sqlite3_bind_int(pSelect, 2, iIdx);
132599     if( sqlite3_step(pSelect)==SQLITE_ROW ){
132600       iStart = sqlite3_column_int64(pSelect, 1);
132601       iLeafEnd = sqlite3_column_int64(pSelect, 2);
132602       iEnd = sqlite3_column_int64(pSelect, 3);
132603       nRoot = sqlite3_column_bytes(pSelect, 4);
132604       aRoot = sqlite3_column_blob(pSelect, 4);
132605     }else{
132606       return sqlite3_reset(pSelect);
132607     }
132608
132609     /* Check for the zero-length marker in the %_segments table */
132610     rc = fts3IsAppendable(p, iEnd, &bAppendable);
132611
132612     /* Check that zKey/nKey is larger than the largest key the candidate */
132613     if( rc==SQLITE_OK && bAppendable ){
132614       char *aLeaf = 0;
132615       int nLeaf = 0;
132616
132617       rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
132618       if( rc==SQLITE_OK ){
132619         NodeReader reader;
132620         for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
132621             rc==SQLITE_OK && reader.aNode;
132622             rc = nodeReaderNext(&reader)
132623         ){
132624           assert( reader.aNode );
132625         }
132626         if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
132627           bAppendable = 0;
132628         }
132629         nodeReaderRelease(&reader);
132630       }
132631       sqlite3_free(aLeaf);
132632     }
132633
132634     if( rc==SQLITE_OK && bAppendable ){
132635       /* It is possible to append to this segment. Set up the IncrmergeWriter
132636       ** object to do so.  */
132637       int i;
132638       int nHeight = (int)aRoot[0];
132639       NodeWriter *pNode;
132640
132641       pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
132642       pWriter->iStart = iStart;
132643       pWriter->iEnd = iEnd;
132644       pWriter->iAbsLevel = iAbsLevel;
132645       pWriter->iIdx = iIdx;
132646
132647       for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
132648         pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
132649       }
132650
132651       pNode = &pWriter->aNodeWriter[nHeight];
132652       pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
132653       blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
132654       if( rc==SQLITE_OK ){
132655         memcpy(pNode->block.a, aRoot, nRoot);
132656         pNode->block.n = nRoot;
132657       }
132658
132659       for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
132660         NodeReader reader;
132661         pNode = &pWriter->aNodeWriter[i];
132662
132663         rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
132664         while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
132665         blobGrowBuffer(&pNode->key, reader.term.n, &rc);
132666         if( rc==SQLITE_OK ){
132667           memcpy(pNode->key.a, reader.term.a, reader.term.n);
132668           pNode->key.n = reader.term.n;
132669           if( i>0 ){
132670             char *aBlock = 0;
132671             int nBlock = 0;
132672             pNode = &pWriter->aNodeWriter[i-1];
132673             pNode->iBlock = reader.iChild;
132674             rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
132675             blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
132676             if( rc==SQLITE_OK ){
132677               memcpy(pNode->block.a, aBlock, nBlock);
132678               pNode->block.n = nBlock;
132679             }
132680             sqlite3_free(aBlock);
132681           }
132682         }
132683         nodeReaderRelease(&reader);
132684       }
132685     }
132686
132687     rc2 = sqlite3_reset(pSelect);
132688     if( rc==SQLITE_OK ) rc = rc2;
132689   }
132690
132691   return rc;
132692 }
132693
132694 /*
132695 ** Determine the largest segment index value that exists within absolute
132696 ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
132697 ** one before returning SQLITE_OK. Or, if there are no segments at all 
132698 ** within level iAbsLevel, set *piIdx to zero.
132699 **
132700 ** If an error occurs, return an SQLite error code. The final value of
132701 ** *piIdx is undefined in this case.
132702 */
132703 static int fts3IncrmergeOutputIdx( 
132704   Fts3Table *p,                   /* FTS Table handle */
132705   sqlite3_int64 iAbsLevel,        /* Absolute index of input segments */
132706   int *piIdx                      /* OUT: Next free index at iAbsLevel+1 */
132707 ){
132708   int rc;
132709   sqlite3_stmt *pOutputIdx = 0;   /* SQL used to find output index */
132710
132711   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
132712   if( rc==SQLITE_OK ){
132713     sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
132714     sqlite3_step(pOutputIdx);
132715     *piIdx = sqlite3_column_int(pOutputIdx, 0);
132716     rc = sqlite3_reset(pOutputIdx);
132717   }
132718
132719   return rc;
132720 }
132721
132722 /* 
132723 ** Allocate an appendable output segment on absolute level iAbsLevel+1
132724 ** with idx value iIdx.
132725 **
132726 ** In the %_segdir table, a segment is defined by the values in three
132727 ** columns:
132728 **
132729 **     start_block
132730 **     leaves_end_block
132731 **     end_block
132732 **
132733 ** When an appendable segment is allocated, it is estimated that the
132734 ** maximum number of leaf blocks that may be required is the sum of the
132735 ** number of leaf blocks consumed by the input segments, plus the number
132736 ** of input segments, multiplied by two. This value is stored in stack 
132737 ** variable nLeafEst.
132738 **
132739 ** A total of 16*nLeafEst blocks are allocated when an appendable segment
132740 ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
132741 ** array of leaf nodes starts at the first block allocated. The array
132742 ** of interior nodes that are parents of the leaf nodes start at block
132743 ** (start_block + (1 + end_block - start_block) / 16). And so on.
132744 **
132745 ** In the actual code below, the value "16" is replaced with the 
132746 ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
132747 */
132748 static int fts3IncrmergeWriter( 
132749   Fts3Table *p,                   /* Fts3 table handle */
132750   sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
132751   int iIdx,                       /* Index of new output segment */
132752   Fts3MultiSegReader *pCsr,       /* Cursor that data will be read from */
132753   IncrmergeWriter *pWriter        /* Populate this object */
132754 ){
132755   int rc;                         /* Return Code */
132756   int i;                          /* Iterator variable */
132757   int nLeafEst = 0;               /* Blocks allocated for leaf nodes */
132758   sqlite3_stmt *pLeafEst = 0;     /* SQL used to determine nLeafEst */
132759   sqlite3_stmt *pFirstBlock = 0;  /* SQL used to determine first block */
132760
132761   /* Calculate nLeafEst. */
132762   rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
132763   if( rc==SQLITE_OK ){
132764     sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
132765     sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
132766     if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
132767       nLeafEst = sqlite3_column_int(pLeafEst, 0);
132768     }
132769     rc = sqlite3_reset(pLeafEst);
132770   }
132771   if( rc!=SQLITE_OK ) return rc;
132772
132773   /* Calculate the first block to use in the output segment */
132774   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
132775   if( rc==SQLITE_OK ){
132776     if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
132777       pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
132778       pWriter->iEnd = pWriter->iStart - 1;
132779       pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
132780     }
132781     rc = sqlite3_reset(pFirstBlock);
132782   }
132783   if( rc!=SQLITE_OK ) return rc;
132784
132785   /* Insert the marker in the %_segments table to make sure nobody tries
132786   ** to steal the space just allocated. This is also used to identify 
132787   ** appendable segments.  */
132788   rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
132789   if( rc!=SQLITE_OK ) return rc;
132790
132791   pWriter->iAbsLevel = iAbsLevel;
132792   pWriter->nLeafEst = nLeafEst;
132793   pWriter->iIdx = iIdx;
132794
132795   /* Set up the array of NodeWriter objects */
132796   for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
132797     pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
132798   }
132799   return SQLITE_OK;
132800 }
132801
132802 /*
132803 ** Remove an entry from the %_segdir table. This involves running the 
132804 ** following two statements:
132805 **
132806 **   DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
132807 **   UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
132808 **
132809 ** The DELETE statement removes the specific %_segdir level. The UPDATE 
132810 ** statement ensures that the remaining segments have contiguously allocated
132811 ** idx values.
132812 */
132813 static int fts3RemoveSegdirEntry(
132814   Fts3Table *p,                   /* FTS3 table handle */
132815   sqlite3_int64 iAbsLevel,        /* Absolute level to delete from */
132816   int iIdx                        /* Index of %_segdir entry to delete */
132817 ){
132818   int rc;                         /* Return code */
132819   sqlite3_stmt *pDelete = 0;      /* DELETE statement */
132820
132821   rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
132822   if( rc==SQLITE_OK ){
132823     sqlite3_bind_int64(pDelete, 1, iAbsLevel);
132824     sqlite3_bind_int(pDelete, 2, iIdx);
132825     sqlite3_step(pDelete);
132826     rc = sqlite3_reset(pDelete);
132827   }
132828
132829   return rc;
132830 }
132831
132832 /*
132833 ** One or more segments have just been removed from absolute level iAbsLevel.
132834 ** Update the 'idx' values of the remaining segments in the level so that
132835 ** the idx values are a contiguous sequence starting from 0.
132836 */
132837 static int fts3RepackSegdirLevel(
132838   Fts3Table *p,                   /* FTS3 table handle */
132839   sqlite3_int64 iAbsLevel         /* Absolute level to repack */
132840 ){
132841   int rc;                         /* Return code */
132842   int *aIdx = 0;                  /* Array of remaining idx values */
132843   int nIdx = 0;                   /* Valid entries in aIdx[] */
132844   int nAlloc = 0;                 /* Allocated size of aIdx[] */
132845   int i;                          /* Iterator variable */
132846   sqlite3_stmt *pSelect = 0;      /* Select statement to read idx values */
132847   sqlite3_stmt *pUpdate = 0;      /* Update statement to modify idx values */
132848
132849   rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
132850   if( rc==SQLITE_OK ){
132851     int rc2;
132852     sqlite3_bind_int64(pSelect, 1, iAbsLevel);
132853     while( SQLITE_ROW==sqlite3_step(pSelect) ){
132854       if( nIdx>=nAlloc ){
132855         int *aNew;
132856         nAlloc += 16;
132857         aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
132858         if( !aNew ){
132859           rc = SQLITE_NOMEM;
132860           break;
132861         }
132862         aIdx = aNew;
132863       }
132864       aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
132865     }
132866     rc2 = sqlite3_reset(pSelect);
132867     if( rc==SQLITE_OK ) rc = rc2;
132868   }
132869
132870   if( rc==SQLITE_OK ){
132871     rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
132872   }
132873   if( rc==SQLITE_OK ){
132874     sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
132875   }
132876
132877   assert( p->bIgnoreSavepoint==0 );
132878   p->bIgnoreSavepoint = 1;
132879   for(i=0; rc==SQLITE_OK && i<nIdx; i++){
132880     if( aIdx[i]!=i ){
132881       sqlite3_bind_int(pUpdate, 3, aIdx[i]);
132882       sqlite3_bind_int(pUpdate, 1, i);
132883       sqlite3_step(pUpdate);
132884       rc = sqlite3_reset(pUpdate);
132885     }
132886   }
132887   p->bIgnoreSavepoint = 0;
132888
132889   sqlite3_free(aIdx);
132890   return rc;
132891 }
132892
132893 static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
132894   pNode->a[0] = (char)iHeight;
132895   if( iChild ){
132896     assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
132897     pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
132898   }else{
132899     assert( pNode->nAlloc>=1 );
132900     pNode->n = 1;
132901   }
132902 }
132903
132904 /*
132905 ** The first two arguments are a pointer to and the size of a segment b-tree
132906 ** node. The node may be a leaf or an internal node.
132907 **
132908 ** This function creates a new node image in blob object *pNew by copying
132909 ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
132910 ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
132911 */
132912 static int fts3TruncateNode(
132913   const char *aNode,              /* Current node image */
132914   int nNode,                      /* Size of aNode in bytes */
132915   Blob *pNew,                     /* OUT: Write new node image here */
132916   const char *zTerm,              /* Omit all terms smaller than this */
132917   int nTerm,                      /* Size of zTerm in bytes */
132918   sqlite3_int64 *piBlock          /* OUT: Block number in next layer down */
132919 ){
132920   NodeReader reader;              /* Reader object */
132921   Blob prev = {0, 0, 0};          /* Previous term written to new node */
132922   int rc = SQLITE_OK;             /* Return code */
132923   int bLeaf = aNode[0]=='\0';     /* True for a leaf node */
132924
132925   /* Allocate required output space */
132926   blobGrowBuffer(pNew, nNode, &rc);
132927   if( rc!=SQLITE_OK ) return rc;
132928   pNew->n = 0;
132929
132930   /* Populate new node buffer */
132931   for(rc = nodeReaderInit(&reader, aNode, nNode); 
132932       rc==SQLITE_OK && reader.aNode; 
132933       rc = nodeReaderNext(&reader)
132934   ){
132935     if( pNew->n==0 ){
132936       int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
132937       if( res<0 || (bLeaf==0 && res==0) ) continue;
132938       fts3StartNode(pNew, (int)aNode[0], reader.iChild);
132939       *piBlock = reader.iChild;
132940     }
132941     rc = fts3AppendToNode(
132942         pNew, &prev, reader.term.a, reader.term.n,
132943         reader.aDoclist, reader.nDoclist
132944     );
132945     if( rc!=SQLITE_OK ) break;
132946   }
132947   if( pNew->n==0 ){
132948     fts3StartNode(pNew, (int)aNode[0], reader.iChild);
132949     *piBlock = reader.iChild;
132950   }
132951   assert( pNew->n<=pNew->nAlloc );
132952
132953   nodeReaderRelease(&reader);
132954   sqlite3_free(prev.a);
132955   return rc;
132956 }
132957
132958 /*
132959 ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute 
132960 ** level iAbsLevel. This may involve deleting entries from the %_segments
132961 ** table, and modifying existing entries in both the %_segments and %_segdir
132962 ** tables.
132963 **
132964 ** SQLITE_OK is returned if the segment is updated successfully. Or an
132965 ** SQLite error code otherwise.
132966 */
132967 static int fts3TruncateSegment(
132968   Fts3Table *p,                   /* FTS3 table handle */
132969   sqlite3_int64 iAbsLevel,        /* Absolute level of segment to modify */
132970   int iIdx,                       /* Index within level of segment to modify */
132971   const char *zTerm,              /* Remove terms smaller than this */
132972   int nTerm                      /* Number of bytes in buffer zTerm */
132973 ){
132974   int rc = SQLITE_OK;             /* Return code */
132975   Blob root = {0,0,0};            /* New root page image */
132976   Blob block = {0,0,0};           /* Buffer used for any other block */
132977   sqlite3_int64 iBlock = 0;       /* Block id */
132978   sqlite3_int64 iNewStart = 0;    /* New value for iStartBlock */
132979   sqlite3_int64 iOldStart = 0;    /* Old value for iStartBlock */
132980   sqlite3_stmt *pFetch = 0;       /* Statement used to fetch segdir */
132981
132982   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
132983   if( rc==SQLITE_OK ){
132984     int rc2;                      /* sqlite3_reset() return code */
132985     sqlite3_bind_int64(pFetch, 1, iAbsLevel);
132986     sqlite3_bind_int(pFetch, 2, iIdx);
132987     if( SQLITE_ROW==sqlite3_step(pFetch) ){
132988       const char *aRoot = sqlite3_column_blob(pFetch, 4);
132989       int nRoot = sqlite3_column_bytes(pFetch, 4);
132990       iOldStart = sqlite3_column_int64(pFetch, 1);
132991       rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
132992     }
132993     rc2 = sqlite3_reset(pFetch);
132994     if( rc==SQLITE_OK ) rc = rc2;
132995   }
132996
132997   while( rc==SQLITE_OK && iBlock ){
132998     char *aBlock = 0;
132999     int nBlock = 0;
133000     iNewStart = iBlock;
133001
133002     rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
133003     if( rc==SQLITE_OK ){
133004       rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
133005     }
133006     if( rc==SQLITE_OK ){
133007       rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
133008     }
133009     sqlite3_free(aBlock);
133010   }
133011
133012   /* Variable iNewStart now contains the first valid leaf node. */
133013   if( rc==SQLITE_OK && iNewStart ){
133014     sqlite3_stmt *pDel = 0;
133015     rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
133016     if( rc==SQLITE_OK ){
133017       sqlite3_bind_int64(pDel, 1, iOldStart);
133018       sqlite3_bind_int64(pDel, 2, iNewStart-1);
133019       sqlite3_step(pDel);
133020       rc = sqlite3_reset(pDel);
133021     }
133022   }
133023
133024   if( rc==SQLITE_OK ){
133025     sqlite3_stmt *pChomp = 0;
133026     rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
133027     if( rc==SQLITE_OK ){
133028       sqlite3_bind_int64(pChomp, 1, iNewStart);
133029       sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
133030       sqlite3_bind_int64(pChomp, 3, iAbsLevel);
133031       sqlite3_bind_int(pChomp, 4, iIdx);
133032       sqlite3_step(pChomp);
133033       rc = sqlite3_reset(pChomp);
133034     }
133035   }
133036
133037   sqlite3_free(root.a);
133038   sqlite3_free(block.a);
133039   return rc;
133040 }
133041
133042 /*
133043 ** This function is called after an incrmental-merge operation has run to
133044 ** merge (or partially merge) two or more segments from absolute level
133045 ** iAbsLevel.
133046 **
133047 ** Each input segment is either removed from the db completely (if all of
133048 ** its data was copied to the output segment by the incrmerge operation)
133049 ** or modified in place so that it no longer contains those entries that
133050 ** have been duplicated in the output segment.
133051 */
133052 static int fts3IncrmergeChomp(
133053   Fts3Table *p,                   /* FTS table handle */
133054   sqlite3_int64 iAbsLevel,        /* Absolute level containing segments */
133055   Fts3MultiSegReader *pCsr,       /* Chomp all segments opened by this cursor */
133056   int *pnRem                      /* Number of segments not deleted */
133057 ){
133058   int i;
133059   int nRem = 0;
133060   int rc = SQLITE_OK;
133061
133062   for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
133063     Fts3SegReader *pSeg = 0;
133064     int j;
133065
133066     /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
133067     ** somewhere in the pCsr->apSegment[] array.  */
133068     for(j=0; ALWAYS(j<pCsr->nSegment); j++){
133069       pSeg = pCsr->apSegment[j];
133070       if( pSeg->iIdx==i ) break;
133071     }
133072     assert( j<pCsr->nSegment && pSeg->iIdx==i );
133073
133074     if( pSeg->aNode==0 ){
133075       /* Seg-reader is at EOF. Remove the entire input segment. */
133076       rc = fts3DeleteSegment(p, pSeg);
133077       if( rc==SQLITE_OK ){
133078         rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
133079       }
133080       *pnRem = 0;
133081     }else{
133082       /* The incremental merge did not copy all the data from this 
133083       ** segment to the upper level. The segment is modified in place
133084       ** so that it contains no keys smaller than zTerm/nTerm. */ 
133085       const char *zTerm = pSeg->zTerm;
133086       int nTerm = pSeg->nTerm;
133087       rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
133088       nRem++;
133089     }
133090   }
133091
133092   if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
133093     rc = fts3RepackSegdirLevel(p, iAbsLevel);
133094   }
133095
133096   *pnRem = nRem;
133097   return rc;
133098 }
133099
133100 /*
133101 ** Store an incr-merge hint in the database.
133102 */
133103 static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
133104   sqlite3_stmt *pReplace = 0;
133105   int rc;                         /* Return code */
133106
133107   rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
133108   if( rc==SQLITE_OK ){
133109     sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
133110     sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
133111     sqlite3_step(pReplace);
133112     rc = sqlite3_reset(pReplace);
133113   }
133114
133115   return rc;
133116 }
133117
133118 /*
133119 ** Load an incr-merge hint from the database. The incr-merge hint, if one 
133120 ** exists, is stored in the rowid==1 row of the %_stat table.
133121 **
133122 ** If successful, populate blob *pHint with the value read from the %_stat
133123 ** table and return SQLITE_OK. Otherwise, if an error occurs, return an
133124 ** SQLite error code.
133125 */
133126 static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
133127   sqlite3_stmt *pSelect = 0;
133128   int rc;
133129
133130   pHint->n = 0;
133131   rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
133132   if( rc==SQLITE_OK ){
133133     int rc2;
133134     sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
133135     if( SQLITE_ROW==sqlite3_step(pSelect) ){
133136       const char *aHint = sqlite3_column_blob(pSelect, 0);
133137       int nHint = sqlite3_column_bytes(pSelect, 0);
133138       if( aHint ){
133139         blobGrowBuffer(pHint, nHint, &rc);
133140         if( rc==SQLITE_OK ){
133141           memcpy(pHint->a, aHint, nHint);
133142           pHint->n = nHint;
133143         }
133144       }
133145     }
133146     rc2 = sqlite3_reset(pSelect);
133147     if( rc==SQLITE_OK ) rc = rc2;
133148   }
133149
133150   return rc;
133151 }
133152
133153 /*
133154 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
133155 ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
133156 ** consists of two varints, the absolute level number of the input segments 
133157 ** and the number of input segments.
133158 **
133159 ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
133160 ** set *pRc to an SQLite error code before returning.
133161 */
133162 static void fts3IncrmergeHintPush(
133163   Blob *pHint,                    /* Hint blob to append to */
133164   i64 iAbsLevel,                  /* First varint to store in hint */
133165   int nInput,                     /* Second varint to store in hint */
133166   int *pRc                        /* IN/OUT: Error code */
133167 ){
133168   blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
133169   if( *pRc==SQLITE_OK ){
133170     pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
133171     pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
133172   }
133173 }
133174
133175 /*
133176 ** Read the last entry (most recently pushed) from the hint blob *pHint
133177 ** and then remove the entry. Write the two values read to *piAbsLevel and 
133178 ** *pnInput before returning.
133179 **
133180 ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
133181 ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
133182 */
133183 static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
133184   const int nHint = pHint->n;
133185   int i;
133186
133187   i = pHint->n-2;
133188   while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
133189   while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
133190
133191   pHint->n = i;
133192   i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
133193   i += sqlite3Fts3GetVarint32(&pHint->a[i], pnInput);
133194   if( i!=nHint ) return SQLITE_CORRUPT_VTAB;
133195
133196   return SQLITE_OK;
133197 }
133198
133199
133200 /*
133201 ** Attempt an incremental merge that writes nMerge leaf blocks.
133202 **
133203 ** Incremental merges happen nMin segments at a time. The two
133204 ** segments to be merged are the nMin oldest segments (the ones with
133205 ** the smallest indexes) in the highest level that contains at least
133206 ** nMin segments. Multiple merges might occur in an attempt to write the 
133207 ** quota of nMerge leaf blocks.
133208 */
133209 SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
133210   int rc;                         /* Return code */
133211   int nRem = nMerge;              /* Number of leaf pages yet to  be written */
133212   Fts3MultiSegReader *pCsr;       /* Cursor used to read input data */
133213   Fts3SegFilter *pFilter;         /* Filter used with cursor pCsr */
133214   IncrmergeWriter *pWriter;       /* Writer object */
133215   int nSeg = 0;                   /* Number of input segments */
133216   sqlite3_int64 iAbsLevel = 0;    /* Absolute level number to work on */
133217   Blob hint = {0, 0, 0};          /* Hint read from %_stat table */
133218   int bDirtyHint = 0;             /* True if blob 'hint' has been modified */
133219
133220   /* Allocate space for the cursor, filter and writer objects */
133221   const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
133222   pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
133223   if( !pWriter ) return SQLITE_NOMEM;
133224   pFilter = (Fts3SegFilter *)&pWriter[1];
133225   pCsr = (Fts3MultiSegReader *)&pFilter[1];
133226
133227   rc = fts3IncrmergeHintLoad(p, &hint);
133228   while( rc==SQLITE_OK && nRem>0 ){
133229     const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
133230     sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
133231     int bUseHint = 0;             /* True if attempting to append */
133232
133233     /* Search the %_segdir table for the absolute level with the smallest
133234     ** relative level number that contains at least nMin segments, if any.
133235     ** If one is found, set iAbsLevel to the absolute level number and
133236     ** nSeg to nMin. If no level with at least nMin segments can be found, 
133237     ** set nSeg to -1.
133238     */
133239     rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
133240     sqlite3_bind_int(pFindLevel, 1, nMin);
133241     if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
133242       iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
133243       nSeg = nMin;
133244     }else{
133245       nSeg = -1;
133246     }
133247     rc = sqlite3_reset(pFindLevel);
133248
133249     /* If the hint read from the %_stat table is not empty, check if the
133250     ** last entry in it specifies a relative level smaller than or equal
133251     ** to the level identified by the block above (if any). If so, this 
133252     ** iteration of the loop will work on merging at the hinted level.
133253     */
133254     if( rc==SQLITE_OK && hint.n ){
133255       int nHint = hint.n;
133256       sqlite3_int64 iHintAbsLevel = 0;      /* Hint level */
133257       int nHintSeg = 0;                     /* Hint number of segments */
133258
133259       rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
133260       if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
133261         iAbsLevel = iHintAbsLevel;
133262         nSeg = nHintSeg;
133263         bUseHint = 1;
133264         bDirtyHint = 1;
133265       }else{
133266         /* This undoes the effect of the HintPop() above - so that no entry
133267         ** is removed from the hint blob.  */
133268         hint.n = nHint;
133269       }
133270     }
133271
133272     /* If nSeg is less that zero, then there is no level with at least
133273     ** nMin segments and no hint in the %_stat table. No work to do.
133274     ** Exit early in this case.  */
133275     if( nSeg<0 ) break;
133276
133277     /* Open a cursor to iterate through the contents of the oldest nSeg 
133278     ** indexes of absolute level iAbsLevel. If this cursor is opened using 
133279     ** the 'hint' parameters, it is possible that there are less than nSeg
133280     ** segments available in level iAbsLevel. In this case, no work is
133281     ** done on iAbsLevel - fall through to the next iteration of the loop 
133282     ** to start work on some other level.  */
133283     memset(pWriter, 0, nAlloc);
133284     pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
133285     if( rc==SQLITE_OK ){
133286       rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
133287     }
133288     if( SQLITE_OK==rc && pCsr->nSegment==nSeg
133289      && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
133290      && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
133291     ){
133292       int iIdx = 0;               /* Largest idx in level (iAbsLevel+1) */
133293       rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
133294       if( rc==SQLITE_OK ){
133295         if( bUseHint && iIdx>0 ){
133296           const char *zKey = pCsr->zTerm;
133297           int nKey = pCsr->nTerm;
133298           rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
133299         }else{
133300           rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
133301         }
133302       }
133303
133304       if( rc==SQLITE_OK && pWriter->nLeafEst ){
133305         fts3LogMerge(nSeg, iAbsLevel);
133306         do {
133307           rc = fts3IncrmergeAppend(p, pWriter, pCsr);
133308           if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
133309           if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
133310         }while( rc==SQLITE_ROW );
133311
133312         /* Update or delete the input segments */
133313         if( rc==SQLITE_OK ){
133314           nRem -= (1 + pWriter->nWork);
133315           rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
133316           if( nSeg!=0 ){
133317             bDirtyHint = 1;
133318             fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
133319           }
133320         }
133321       }
133322
133323       fts3IncrmergeRelease(p, pWriter, &rc);
133324     }
133325
133326     sqlite3Fts3SegReaderFinish(pCsr);
133327   }
133328
133329   /* Write the hint values into the %_stat table for the next incr-merger */
133330   if( bDirtyHint && rc==SQLITE_OK ){
133331     rc = fts3IncrmergeHintStore(p, &hint);
133332   }
133333
133334   sqlite3_free(pWriter);
133335   sqlite3_free(hint.a);
133336   return rc;
133337 }
133338
133339 /*
133340 ** Convert the text beginning at *pz into an integer and return
133341 ** its value.  Advance *pz to point to the first character past
133342 ** the integer.
133343 */
133344 static int fts3Getint(const char **pz){
133345   const char *z = *pz;
133346   int i = 0;
133347   while( (*z)>='0' && (*z)<='9' ) i = 10*i + *(z++) - '0';
133348   *pz = z;
133349   return i;
133350 }
133351
133352 /*
133353 ** Process statements of the form:
133354 **
133355 **    INSERT INTO table(table) VALUES('merge=A,B');
133356 **
133357 ** A and B are integers that decode to be the number of leaf pages
133358 ** written for the merge, and the minimum number of segments on a level
133359 ** before it will be selected for a merge, respectively.
133360 */
133361 static int fts3DoIncrmerge(
133362   Fts3Table *p,                   /* FTS3 table handle */
133363   const char *zParam              /* Nul-terminated string containing "A,B" */
133364 ){
133365   int rc;
133366   int nMin = (FTS3_MERGE_COUNT / 2);
133367   int nMerge = 0;
133368   const char *z = zParam;
133369
133370   /* Read the first integer value */
133371   nMerge = fts3Getint(&z);
133372
133373   /* If the first integer value is followed by a ',',  read the second
133374   ** integer value. */
133375   if( z[0]==',' && z[1]!='\0' ){
133376     z++;
133377     nMin = fts3Getint(&z);
133378   }
133379
133380   if( z[0]!='\0' || nMin<2 ){
133381     rc = SQLITE_ERROR;
133382   }else{
133383     rc = SQLITE_OK;
133384     if( !p->bHasStat ){
133385       assert( p->bFts4==0 );
133386       sqlite3Fts3CreateStatTable(&rc, p);
133387     }
133388     if( rc==SQLITE_OK ){
133389       rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
133390     }
133391     sqlite3Fts3SegmentsClose(p);
133392   }
133393   return rc;
133394 }
133395
133396 /*
133397 ** Process statements of the form:
133398 **
133399 **    INSERT INTO table(table) VALUES('automerge=X');
133400 **
133401 ** where X is an integer.  X==0 means to turn automerge off.  X!=0 means
133402 ** turn it on.  The setting is persistent.
133403 */
133404 static int fts3DoAutoincrmerge(
133405   Fts3Table *p,                   /* FTS3 table handle */
133406   const char *zParam              /* Nul-terminated string containing boolean */
133407 ){
133408   int rc = SQLITE_OK;
133409   sqlite3_stmt *pStmt = 0;
133410   p->bAutoincrmerge = fts3Getint(&zParam)!=0;
133411   if( !p->bHasStat ){
133412     assert( p->bFts4==0 );
133413     sqlite3Fts3CreateStatTable(&rc, p);
133414     if( rc ) return rc;
133415   }
133416   rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
133417   if( rc ) return rc;;
133418   sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
133419   sqlite3_bind_int(pStmt, 2, p->bAutoincrmerge);
133420   sqlite3_step(pStmt);
133421   rc = sqlite3_reset(pStmt);
133422   return rc;
133423 }
133424
133425 /*
133426 ** Return a 64-bit checksum for the FTS index entry specified by the
133427 ** arguments to this function.
133428 */
133429 static u64 fts3ChecksumEntry(
133430   const char *zTerm,              /* Pointer to buffer containing term */
133431   int nTerm,                      /* Size of zTerm in bytes */
133432   int iLangid,                    /* Language id for current row */
133433   int iIndex,                     /* Index (0..Fts3Table.nIndex-1) */
133434   i64 iDocid,                     /* Docid for current row. */
133435   int iCol,                       /* Column number */
133436   int iPos                        /* Position */
133437 ){
133438   int i;
133439   u64 ret = (u64)iDocid;
133440
133441   ret += (ret<<3) + iLangid;
133442   ret += (ret<<3) + iIndex;
133443   ret += (ret<<3) + iCol;
133444   ret += (ret<<3) + iPos;
133445   for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
133446
133447   return ret;
133448 }
133449
133450 /*
133451 ** Return a checksum of all entries in the FTS index that correspond to
133452 ** language id iLangid. The checksum is calculated by XORing the checksums
133453 ** of each individual entry (see fts3ChecksumEntry()) together.
133454 **
133455 ** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
133456 ** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
133457 ** return value is undefined in this case.
133458 */
133459 static u64 fts3ChecksumIndex(
133460   Fts3Table *p,                   /* FTS3 table handle */
133461   int iLangid,                    /* Language id to return cksum for */
133462   int iIndex,                     /* Index to cksum (0..p->nIndex-1) */
133463   int *pRc                        /* OUT: Return code */
133464 ){
133465   Fts3SegFilter filter;
133466   Fts3MultiSegReader csr;
133467   int rc;
133468   u64 cksum = 0;
133469
133470   assert( *pRc==SQLITE_OK );
133471
133472   memset(&filter, 0, sizeof(filter));
133473   memset(&csr, 0, sizeof(csr));
133474   filter.flags =  FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
133475   filter.flags |= FTS3_SEGMENT_SCAN;
133476
133477   rc = sqlite3Fts3SegReaderCursor(
133478       p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
133479   );
133480   if( rc==SQLITE_OK ){
133481     rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
133482   }
133483
133484   if( rc==SQLITE_OK ){
133485     while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
133486       char *pCsr = csr.aDoclist;
133487       char *pEnd = &pCsr[csr.nDoclist];
133488
133489       i64 iDocid = 0;
133490       i64 iCol = 0;
133491       i64 iPos = 0;
133492
133493       pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
133494       while( pCsr<pEnd ){
133495         i64 iVal = 0;
133496         pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
133497         if( pCsr<pEnd ){
133498           if( iVal==0 || iVal==1 ){
133499             iCol = 0;
133500             iPos = 0;
133501             if( iVal ){
133502               pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
133503             }else{
133504               pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
133505               iDocid += iVal;
133506             }
133507           }else{
133508             iPos += (iVal - 2);
133509             cksum = cksum ^ fts3ChecksumEntry(
133510                 csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
133511                 (int)iCol, (int)iPos
133512             );
133513           }
133514         }
133515       }
133516     }
133517   }
133518   sqlite3Fts3SegReaderFinish(&csr);
133519
133520   *pRc = rc;
133521   return cksum;
133522 }
133523
133524 /*
133525 ** Check if the contents of the FTS index match the current contents of the
133526 ** content table. If no error occurs and the contents do match, set *pbOk
133527 ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
133528 ** to false before returning.
133529 **
133530 ** If an error occurs (e.g. an OOM or IO error), return an SQLite error 
133531 ** code. The final value of *pbOk is undefined in this case.
133532 */
133533 static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
133534   int rc = SQLITE_OK;             /* Return code */
133535   u64 cksum1 = 0;                 /* Checksum based on FTS index contents */
133536   u64 cksum2 = 0;                 /* Checksum based on %_content contents */
133537   sqlite3_stmt *pAllLangid = 0;   /* Statement to return all language-ids */
133538
133539   /* This block calculates the checksum according to the FTS index. */
133540   rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
133541   if( rc==SQLITE_OK ){
133542     int rc2;
133543     sqlite3_bind_int(pAllLangid, 1, p->nIndex);
133544     while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
133545       int iLangid = sqlite3_column_int(pAllLangid, 0);
133546       int i;
133547       for(i=0; i<p->nIndex; i++){
133548         cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
133549       }
133550     }
133551     rc2 = sqlite3_reset(pAllLangid);
133552     if( rc==SQLITE_OK ) rc = rc2;
133553   }
133554
133555   /* This block calculates the checksum according to the %_content table */
133556   rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
133557   if( rc==SQLITE_OK ){
133558     sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
133559     sqlite3_stmt *pStmt = 0;
133560     char *zSql;
133561    
133562     zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
133563     if( !zSql ){
133564       rc = SQLITE_NOMEM;
133565     }else{
133566       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
133567       sqlite3_free(zSql);
133568     }
133569
133570     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
133571       i64 iDocid = sqlite3_column_int64(pStmt, 0);
133572       int iLang = langidFromSelect(p, pStmt);
133573       int iCol;
133574
133575       for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
133576         const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
133577         int nText = sqlite3_column_bytes(pStmt, iCol+1);
133578         sqlite3_tokenizer_cursor *pT = 0;
133579
133580         rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText, &pT);
133581         while( rc==SQLITE_OK ){
133582           char const *zToken;       /* Buffer containing token */
133583           int nToken = 0;           /* Number of bytes in token */
133584           int iDum1 = 0, iDum2 = 0; /* Dummy variables */
133585           int iPos = 0;             /* Position of token in zText */
133586
133587           rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
133588           if( rc==SQLITE_OK ){
133589             int i;
133590             cksum2 = cksum2 ^ fts3ChecksumEntry(
133591                 zToken, nToken, iLang, 0, iDocid, iCol, iPos
133592             );
133593             for(i=1; i<p->nIndex; i++){
133594               if( p->aIndex[i].nPrefix<=nToken ){
133595                 cksum2 = cksum2 ^ fts3ChecksumEntry(
133596                   zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
133597                 );
133598               }
133599             }
133600           }
133601         }
133602         if( pT ) pModule->xClose(pT);
133603         if( rc==SQLITE_DONE ) rc = SQLITE_OK;
133604       }
133605     }
133606
133607     sqlite3_finalize(pStmt);
133608   }
133609
133610   *pbOk = (cksum1==cksum2);
133611   return rc;
133612 }
133613
133614 /*
133615 ** Run the integrity-check. If no error occurs and the current contents of
133616 ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
133617 ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
133618 **
133619 ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite 
133620 ** error code.
133621 **
133622 ** The integrity-check works as follows. For each token and indexed token
133623 ** prefix in the document set, a 64-bit checksum is calculated (by code
133624 ** in fts3ChecksumEntry()) based on the following:
133625 **
133626 **     + The index number (0 for the main index, 1 for the first prefix
133627 **       index etc.),
133628 **     + The token (or token prefix) text itself, 
133629 **     + The language-id of the row it appears in,
133630 **     + The docid of the row it appears in,
133631 **     + The column it appears in, and
133632 **     + The tokens position within that column.
133633 **
133634 ** The checksums for all entries in the index are XORed together to create
133635 ** a single checksum for the entire index.
133636 **
133637 ** The integrity-check code calculates the same checksum in two ways:
133638 **
133639 **     1. By scanning the contents of the FTS index, and 
133640 **     2. By scanning and tokenizing the content table.
133641 **
133642 ** If the two checksums are identical, the integrity-check is deemed to have
133643 ** passed.
133644 */
133645 static int fts3DoIntegrityCheck(
133646   Fts3Table *p                    /* FTS3 table handle */
133647 ){
133648   int rc;
133649   int bOk = 0;
133650   rc = fts3IntegrityCheck(p, &bOk);
133651   if( rc==SQLITE_OK && bOk==0 ) rc = SQLITE_CORRUPT_VTAB;
133652   return rc;
133653 }
133654
133655 /*
133656 ** Handle a 'special' INSERT of the form:
133657 **
133658 **   "INSERT INTO tbl(tbl) VALUES(<expr>)"
133659 **
133660 ** Argument pVal contains the result of <expr>. Currently the only 
133661 ** meaningful value to insert is the text 'optimize'.
133662 */
133663 static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
133664   int rc;                         /* Return Code */
133665   const char *zVal = (const char *)sqlite3_value_text(pVal);
133666   int nVal = sqlite3_value_bytes(pVal);
133667
133668   if( !zVal ){
133669     return SQLITE_NOMEM;
133670   }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
133671     rc = fts3DoOptimize(p, 0);
133672   }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
133673     rc = fts3DoRebuild(p);
133674   }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
133675     rc = fts3DoIntegrityCheck(p);
133676   }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
133677     rc = fts3DoIncrmerge(p, &zVal[6]);
133678   }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
133679     rc = fts3DoAutoincrmerge(p, &zVal[10]);
133680 #ifdef SQLITE_TEST
133681   }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
133682     p->nNodeSize = atoi(&zVal[9]);
133683     rc = SQLITE_OK;
133684   }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
133685     p->nMaxPendingData = atoi(&zVal[11]);
133686     rc = SQLITE_OK;
133687 #endif
133688   }else{
133689     rc = SQLITE_ERROR;
133690   }
133691
133692   return rc;
133693 }
133694
133695 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
133696 /*
133697 ** Delete all cached deferred doclists. Deferred doclists are cached
133698 ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
133699 */
133700 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
133701   Fts3DeferredToken *pDef;
133702   for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
133703     fts3PendingListDelete(pDef->pList);
133704     pDef->pList = 0;
133705   }
133706 }
133707
133708 /*
133709 ** Free all entries in the pCsr->pDeffered list. Entries are added to 
133710 ** this list using sqlite3Fts3DeferToken().
133711 */
133712 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
133713   Fts3DeferredToken *pDef;
133714   Fts3DeferredToken *pNext;
133715   for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
133716     pNext = pDef->pNext;
133717     fts3PendingListDelete(pDef->pList);
133718     sqlite3_free(pDef);
133719   }
133720   pCsr->pDeferred = 0;
133721 }
133722
133723 /*
133724 ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
133725 ** based on the row that pCsr currently points to.
133726 **
133727 ** A deferred-doclist is like any other doclist with position information
133728 ** included, except that it only contains entries for a single row of the
133729 ** table, not for all rows.
133730 */
133731 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
133732   int rc = SQLITE_OK;             /* Return code */
133733   if( pCsr->pDeferred ){
133734     int i;                        /* Used to iterate through table columns */
133735     sqlite3_int64 iDocid;         /* Docid of the row pCsr points to */
133736     Fts3DeferredToken *pDef;      /* Used to iterate through deferred tokens */
133737   
133738     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
133739     sqlite3_tokenizer *pT = p->pTokenizer;
133740     sqlite3_tokenizer_module const *pModule = pT->pModule;
133741    
133742     assert( pCsr->isRequireSeek==0 );
133743     iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
133744   
133745     for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
133746       const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
133747       sqlite3_tokenizer_cursor *pTC = 0;
133748   
133749       rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
133750       while( rc==SQLITE_OK ){
133751         char const *zToken;       /* Buffer containing token */
133752         int nToken = 0;           /* Number of bytes in token */
133753         int iDum1 = 0, iDum2 = 0; /* Dummy variables */
133754         int iPos = 0;             /* Position of token in zText */
133755   
133756         rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
133757         for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
133758           Fts3PhraseToken *pPT = pDef->pToken;
133759           if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
133760            && (pPT->bFirst==0 || iPos==0)
133761            && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
133762            && (0==memcmp(zToken, pPT->z, pPT->n))
133763           ){
133764             fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
133765           }
133766         }
133767       }
133768       if( pTC ) pModule->xClose(pTC);
133769       if( rc==SQLITE_DONE ) rc = SQLITE_OK;
133770     }
133771   
133772     for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
133773       if( pDef->pList ){
133774         rc = fts3PendingListAppendVarint(&pDef->pList, 0);
133775       }
133776     }
133777   }
133778
133779   return rc;
133780 }
133781
133782 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
133783   Fts3DeferredToken *p, 
133784   char **ppData, 
133785   int *pnData
133786 ){
133787   char *pRet;
133788   int nSkip;
133789   sqlite3_int64 dummy;
133790
133791   *ppData = 0;
133792   *pnData = 0;
133793
133794   if( p->pList==0 ){
133795     return SQLITE_OK;
133796   }
133797
133798   pRet = (char *)sqlite3_malloc(p->pList->nData);
133799   if( !pRet ) return SQLITE_NOMEM;
133800
133801   nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
133802   *pnData = p->pList->nData - nSkip;
133803   *ppData = pRet;
133804   
133805   memcpy(pRet, &p->pList->aData[nSkip], *pnData);
133806   return SQLITE_OK;
133807 }
133808
133809 /*
133810 ** Add an entry for token pToken to the pCsr->pDeferred list.
133811 */
133812 SQLITE_PRIVATE int sqlite3Fts3DeferToken(
133813   Fts3Cursor *pCsr,               /* Fts3 table cursor */
133814   Fts3PhraseToken *pToken,        /* Token to defer */
133815   int iCol                        /* Column that token must appear in (or -1) */
133816 ){
133817   Fts3DeferredToken *pDeferred;
133818   pDeferred = sqlite3_malloc(sizeof(*pDeferred));
133819   if( !pDeferred ){
133820     return SQLITE_NOMEM;
133821   }
133822   memset(pDeferred, 0, sizeof(*pDeferred));
133823   pDeferred->pToken = pToken;
133824   pDeferred->pNext = pCsr->pDeferred; 
133825   pDeferred->iCol = iCol;
133826   pCsr->pDeferred = pDeferred;
133827
133828   assert( pToken->pDeferred==0 );
133829   pToken->pDeferred = pDeferred;
133830
133831   return SQLITE_OK;
133832 }
133833 #endif
133834
133835 /*
133836 ** SQLite value pRowid contains the rowid of a row that may or may not be
133837 ** present in the FTS3 table. If it is, delete it and adjust the contents
133838 ** of subsiduary data structures accordingly.
133839 */
133840 static int fts3DeleteByRowid(
133841   Fts3Table *p, 
133842   sqlite3_value *pRowid, 
133843   int *pnChng,                    /* IN/OUT: Decrement if row is deleted */
133844   u32 *aSzDel
133845 ){
133846   int rc = SQLITE_OK;             /* Return code */
133847   int bFound = 0;                 /* True if *pRowid really is in the table */
133848
133849   fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
133850   if( bFound && rc==SQLITE_OK ){
133851     int isEmpty = 0;              /* Deleting *pRowid leaves the table empty */
133852     rc = fts3IsEmpty(p, pRowid, &isEmpty);
133853     if( rc==SQLITE_OK ){
133854       if( isEmpty ){
133855         /* Deleting this row means the whole table is empty. In this case
133856         ** delete the contents of all three tables and throw away any
133857         ** data in the pendingTerms hash table.  */
133858         rc = fts3DeleteAll(p, 1);
133859         *pnChng = 0;
133860         memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
133861       }else{
133862         *pnChng = *pnChng - 1;
133863         if( p->zContentTbl==0 ){
133864           fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
133865         }
133866         if( p->bHasDocsize ){
133867           fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
133868         }
133869       }
133870     }
133871   }
133872
133873   return rc;
133874 }
133875
133876 /*
133877 ** This function does the work for the xUpdate method of FTS3 virtual
133878 ** tables. The schema of the virtual table being:
133879 **
133880 **     CREATE TABLE <table name>( 
133881 **       <user columns>,
133882 **       <table name> HIDDEN, 
133883 **       docid HIDDEN, 
133884 **       <langid> HIDDEN
133885 **     );
133886 **
133887 ** 
133888 */
133889 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
133890   sqlite3_vtab *pVtab,            /* FTS3 vtab object */
133891   int nArg,                       /* Size of argument array */
133892   sqlite3_value **apVal,          /* Array of arguments */
133893   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
133894 ){
133895   Fts3Table *p = (Fts3Table *)pVtab;
133896   int rc = SQLITE_OK;             /* Return Code */
133897   int isRemove = 0;               /* True for an UPDATE or DELETE */
133898   u32 *aSzIns = 0;                /* Sizes of inserted documents */
133899   u32 *aSzDel = 0;                /* Sizes of deleted documents */
133900   int nChng = 0;                  /* Net change in number of documents */
133901   int bInsertDone = 0;
133902
133903   assert( p->pSegments==0 );
133904   assert( 
133905       nArg==1                     /* DELETE operations */
133906    || nArg==(2 + p->nColumn + 3)  /* INSERT or UPDATE operations */
133907   );
133908
133909   /* Check for a "special" INSERT operation. One of the form:
133910   **
133911   **   INSERT INTO xyz(xyz) VALUES('command');
133912   */
133913   if( nArg>1 
133914    && sqlite3_value_type(apVal[0])==SQLITE_NULL 
133915    && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL 
133916   ){
133917     rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
133918     goto update_out;
133919   }
133920
133921   if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
133922     rc = SQLITE_CONSTRAINT;
133923     goto update_out;
133924   }
133925
133926   /* Allocate space to hold the change in document sizes */
133927   aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
133928   if( aSzDel==0 ){
133929     rc = SQLITE_NOMEM;
133930     goto update_out;
133931   }
133932   aSzIns = &aSzDel[p->nColumn+1];
133933   memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
133934
133935   /* If this is an INSERT operation, or an UPDATE that modifies the rowid
133936   ** value, then this operation requires constraint handling.
133937   **
133938   ** If the on-conflict mode is REPLACE, this means that the existing row
133939   ** should be deleted from the database before inserting the new row. Or,
133940   ** if the on-conflict mode is other than REPLACE, then this method must
133941   ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
133942   ** modify the database file.
133943   */
133944   if( nArg>1 && p->zContentTbl==0 ){
133945     /* Find the value object that holds the new rowid value. */
133946     sqlite3_value *pNewRowid = apVal[3+p->nColumn];
133947     if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
133948       pNewRowid = apVal[1];
133949     }
133950
133951     if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && ( 
133952         sqlite3_value_type(apVal[0])==SQLITE_NULL
133953      || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
133954     )){
133955       /* The new rowid is not NULL (in this case the rowid will be
133956       ** automatically assigned and there is no chance of a conflict), and 
133957       ** the statement is either an INSERT or an UPDATE that modifies the
133958       ** rowid column. So if the conflict mode is REPLACE, then delete any
133959       ** existing row with rowid=pNewRowid. 
133960       **
133961       ** Or, if the conflict mode is not REPLACE, insert the new record into 
133962       ** the %_content table. If we hit the duplicate rowid constraint (or any
133963       ** other error) while doing so, return immediately.
133964       **
133965       ** This branch may also run if pNewRowid contains a value that cannot
133966       ** be losslessly converted to an integer. In this case, the eventual 
133967       ** call to fts3InsertData() (either just below or further on in this
133968       ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is 
133969       ** invoked, it will delete zero rows (since no row will have
133970       ** docid=$pNewRowid if $pNewRowid is not an integer value).
133971       */
133972       if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
133973         rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
133974       }else{
133975         rc = fts3InsertData(p, apVal, pRowid);
133976         bInsertDone = 1;
133977       }
133978     }
133979   }
133980   if( rc!=SQLITE_OK ){
133981     goto update_out;
133982   }
133983
133984   /* If this is a DELETE or UPDATE operation, remove the old record. */
133985   if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
133986     assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
133987     rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
133988     isRemove = 1;
133989   }
133990   
133991   /* If this is an INSERT or UPDATE operation, insert the new record. */
133992   if( nArg>1 && rc==SQLITE_OK ){
133993     int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
133994     if( bInsertDone==0 ){
133995       rc = fts3InsertData(p, apVal, pRowid);
133996       if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
133997         rc = FTS_CORRUPT_VTAB;
133998       }
133999     }
134000     if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
134001       rc = fts3PendingTermsDocid(p, iLangid, *pRowid);
134002     }
134003     if( rc==SQLITE_OK ){
134004       assert( p->iPrevDocid==*pRowid );
134005       rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
134006     }
134007     if( p->bHasDocsize ){
134008       fts3InsertDocsize(&rc, p, aSzIns);
134009     }
134010     nChng++;
134011   }
134012
134013   if( p->bFts4 ){
134014     fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
134015   }
134016
134017  update_out:
134018   sqlite3_free(aSzDel);
134019   sqlite3Fts3SegmentsClose(p);
134020   return rc;
134021 }
134022
134023 /* 
134024 ** Flush any data in the pending-terms hash table to disk. If successful,
134025 ** merge all segments in the database (including the new segment, if 
134026 ** there was any data to flush) into a single segment. 
134027 */
134028 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
134029   int rc;
134030   rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
134031   if( rc==SQLITE_OK ){
134032     rc = fts3DoOptimize(p, 1);
134033     if( rc==SQLITE_OK || rc==SQLITE_DONE ){
134034       int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
134035       if( rc2!=SQLITE_OK ) rc = rc2;
134036     }else{
134037       sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
134038       sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
134039     }
134040   }
134041   sqlite3Fts3SegmentsClose(p);
134042   return rc;
134043 }
134044
134045 #endif
134046
134047 /************** End of fts3_write.c ******************************************/
134048 /************** Begin file fts3_snippet.c ************************************/
134049 /*
134050 ** 2009 Oct 23
134051 **
134052 ** The author disclaims copyright to this source code.  In place of
134053 ** a legal notice, here is a blessing:
134054 **
134055 **    May you do good and not evil.
134056 **    May you find forgiveness for yourself and forgive others.
134057 **    May you share freely, never taking more than you give.
134058 **
134059 ******************************************************************************
134060 */
134061
134062 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
134063
134064 /* #include <string.h> */
134065 /* #include <assert.h> */
134066
134067 /*
134068 ** Characters that may appear in the second argument to matchinfo().
134069 */
134070 #define FTS3_MATCHINFO_NPHRASE   'p'        /* 1 value */
134071 #define FTS3_MATCHINFO_NCOL      'c'        /* 1 value */
134072 #define FTS3_MATCHINFO_NDOC      'n'        /* 1 value */
134073 #define FTS3_MATCHINFO_AVGLENGTH 'a'        /* nCol values */
134074 #define FTS3_MATCHINFO_LENGTH    'l'        /* nCol values */
134075 #define FTS3_MATCHINFO_LCS       's'        /* nCol values */
134076 #define FTS3_MATCHINFO_HITS      'x'        /* 3*nCol*nPhrase values */
134077
134078 /*
134079 ** The default value for the second argument to matchinfo(). 
134080 */
134081 #define FTS3_MATCHINFO_DEFAULT   "pcx"
134082
134083
134084 /*
134085 ** Used as an fts3ExprIterate() context when loading phrase doclists to
134086 ** Fts3Expr.aDoclist[]/nDoclist.
134087 */
134088 typedef struct LoadDoclistCtx LoadDoclistCtx;
134089 struct LoadDoclistCtx {
134090   Fts3Cursor *pCsr;               /* FTS3 Cursor */
134091   int nPhrase;                    /* Number of phrases seen so far */
134092   int nToken;                     /* Number of tokens seen so far */
134093 };
134094
134095 /*
134096 ** The following types are used as part of the implementation of the 
134097 ** fts3BestSnippet() routine.
134098 */
134099 typedef struct SnippetIter SnippetIter;
134100 typedef struct SnippetPhrase SnippetPhrase;
134101 typedef struct SnippetFragment SnippetFragment;
134102
134103 struct SnippetIter {
134104   Fts3Cursor *pCsr;               /* Cursor snippet is being generated from */
134105   int iCol;                       /* Extract snippet from this column */
134106   int nSnippet;                   /* Requested snippet length (in tokens) */
134107   int nPhrase;                    /* Number of phrases in query */
134108   SnippetPhrase *aPhrase;         /* Array of size nPhrase */
134109   int iCurrent;                   /* First token of current snippet */
134110 };
134111
134112 struct SnippetPhrase {
134113   int nToken;                     /* Number of tokens in phrase */
134114   char *pList;                    /* Pointer to start of phrase position list */
134115   int iHead;                      /* Next value in position list */
134116   char *pHead;                    /* Position list data following iHead */
134117   int iTail;                      /* Next value in trailing position list */
134118   char *pTail;                    /* Position list data following iTail */
134119 };
134120
134121 struct SnippetFragment {
134122   int iCol;                       /* Column snippet is extracted from */
134123   int iPos;                       /* Index of first token in snippet */
134124   u64 covered;                    /* Mask of query phrases covered */
134125   u64 hlmask;                     /* Mask of snippet terms to highlight */
134126 };
134127
134128 /*
134129 ** This type is used as an fts3ExprIterate() context object while 
134130 ** accumulating the data returned by the matchinfo() function.
134131 */
134132 typedef struct MatchInfo MatchInfo;
134133 struct MatchInfo {
134134   Fts3Cursor *pCursor;            /* FTS3 Cursor */
134135   int nCol;                       /* Number of columns in table */
134136   int nPhrase;                    /* Number of matchable phrases in query */
134137   sqlite3_int64 nDoc;             /* Number of docs in database */
134138   u32 *aMatchinfo;                /* Pre-allocated buffer */
134139 };
134140
134141
134142
134143 /*
134144 ** The snippet() and offsets() functions both return text values. An instance
134145 ** of the following structure is used to accumulate those values while the
134146 ** functions are running. See fts3StringAppend() for details.
134147 */
134148 typedef struct StrBuffer StrBuffer;
134149 struct StrBuffer {
134150   char *z;                        /* Pointer to buffer containing string */
134151   int n;                          /* Length of z in bytes (excl. nul-term) */
134152   int nAlloc;                     /* Allocated size of buffer z in bytes */
134153 };
134154
134155
134156 /*
134157 ** This function is used to help iterate through a position-list. A position
134158 ** list is a list of unique integers, sorted from smallest to largest. Each
134159 ** element of the list is represented by an FTS3 varint that takes the value
134160 ** of the difference between the current element and the previous one plus
134161 ** two. For example, to store the position-list:
134162 **
134163 **     4 9 113
134164 **
134165 ** the three varints:
134166 **
134167 **     6 7 106
134168 **
134169 ** are encoded.
134170 **
134171 ** When this function is called, *pp points to the start of an element of
134172 ** the list. *piPos contains the value of the previous entry in the list.
134173 ** After it returns, *piPos contains the value of the next element of the
134174 ** list and *pp is advanced to the following varint.
134175 */
134176 static void fts3GetDeltaPosition(char **pp, int *piPos){
134177   int iVal;
134178   *pp += sqlite3Fts3GetVarint32(*pp, &iVal);
134179   *piPos += (iVal-2);
134180 }
134181
134182 /*
134183 ** Helper function for fts3ExprIterate() (see below).
134184 */
134185 static int fts3ExprIterate2(
134186   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
134187   int *piPhrase,                  /* Pointer to phrase counter */
134188   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
134189   void *pCtx                      /* Second argument to pass to callback */
134190 ){
134191   int rc;                         /* Return code */
134192   int eType = pExpr->eType;       /* Type of expression node pExpr */
134193
134194   if( eType!=FTSQUERY_PHRASE ){
134195     assert( pExpr->pLeft && pExpr->pRight );
134196     rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
134197     if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
134198       rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
134199     }
134200   }else{
134201     rc = x(pExpr, *piPhrase, pCtx);
134202     (*piPhrase)++;
134203   }
134204   return rc;
134205 }
134206
134207 /*
134208 ** Iterate through all phrase nodes in an FTS3 query, except those that
134209 ** are part of a sub-tree that is the right-hand-side of a NOT operator.
134210 ** For each phrase node found, the supplied callback function is invoked.
134211 **
134212 ** If the callback function returns anything other than SQLITE_OK, 
134213 ** the iteration is abandoned and the error code returned immediately.
134214 ** Otherwise, SQLITE_OK is returned after a callback has been made for
134215 ** all eligible phrase nodes.
134216 */
134217 static int fts3ExprIterate(
134218   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
134219   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
134220   void *pCtx                      /* Second argument to pass to callback */
134221 ){
134222   int iPhrase = 0;                /* Variable used as the phrase counter */
134223   return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
134224 }
134225
134226 /*
134227 ** This is an fts3ExprIterate() callback used while loading the doclists
134228 ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
134229 ** fts3ExprLoadDoclists().
134230 */
134231 static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
134232   int rc = SQLITE_OK;
134233   Fts3Phrase *pPhrase = pExpr->pPhrase;
134234   LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
134235
134236   UNUSED_PARAMETER(iPhrase);
134237
134238   p->nPhrase++;
134239   p->nToken += pPhrase->nToken;
134240
134241   return rc;
134242 }
134243
134244 /*
134245 ** Load the doclists for each phrase in the query associated with FTS3 cursor
134246 ** pCsr. 
134247 **
134248 ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable 
134249 ** phrases in the expression (all phrases except those directly or 
134250 ** indirectly descended from the right-hand-side of a NOT operator). If 
134251 ** pnToken is not NULL, then it is set to the number of tokens in all
134252 ** matchable phrases of the expression.
134253 */
134254 static int fts3ExprLoadDoclists(
134255   Fts3Cursor *pCsr,               /* Fts3 cursor for current query */
134256   int *pnPhrase,                  /* OUT: Number of phrases in query */
134257   int *pnToken                    /* OUT: Number of tokens in query */
134258 ){
134259   int rc;                         /* Return Code */
134260   LoadDoclistCtx sCtx = {0,0,0};  /* Context for fts3ExprIterate() */
134261   sCtx.pCsr = pCsr;
134262   rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
134263   if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
134264   if( pnToken ) *pnToken = sCtx.nToken;
134265   return rc;
134266 }
134267
134268 static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
134269   (*(int *)ctx)++;
134270   UNUSED_PARAMETER(pExpr);
134271   UNUSED_PARAMETER(iPhrase);
134272   return SQLITE_OK;
134273 }
134274 static int fts3ExprPhraseCount(Fts3Expr *pExpr){
134275   int nPhrase = 0;
134276   (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
134277   return nPhrase;
134278 }
134279
134280 /*
134281 ** Advance the position list iterator specified by the first two 
134282 ** arguments so that it points to the first element with a value greater
134283 ** than or equal to parameter iNext.
134284 */
134285 static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
134286   char *pIter = *ppIter;
134287   if( pIter ){
134288     int iIter = *piIter;
134289
134290     while( iIter<iNext ){
134291       if( 0==(*pIter & 0xFE) ){
134292         iIter = -1;
134293         pIter = 0;
134294         break;
134295       }
134296       fts3GetDeltaPosition(&pIter, &iIter);
134297     }
134298
134299     *piIter = iIter;
134300     *ppIter = pIter;
134301   }
134302 }
134303
134304 /*
134305 ** Advance the snippet iterator to the next candidate snippet.
134306 */
134307 static int fts3SnippetNextCandidate(SnippetIter *pIter){
134308   int i;                          /* Loop counter */
134309
134310   if( pIter->iCurrent<0 ){
134311     /* The SnippetIter object has just been initialized. The first snippet
134312     ** candidate always starts at offset 0 (even if this candidate has a
134313     ** score of 0.0).
134314     */
134315     pIter->iCurrent = 0;
134316
134317     /* Advance the 'head' iterator of each phrase to the first offset that
134318     ** is greater than or equal to (iNext+nSnippet).
134319     */
134320     for(i=0; i<pIter->nPhrase; i++){
134321       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
134322       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
134323     }
134324   }else{
134325     int iStart;
134326     int iEnd = 0x7FFFFFFF;
134327
134328     for(i=0; i<pIter->nPhrase; i++){
134329       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
134330       if( pPhrase->pHead && pPhrase->iHead<iEnd ){
134331         iEnd = pPhrase->iHead;
134332       }
134333     }
134334     if( iEnd==0x7FFFFFFF ){
134335       return 1;
134336     }
134337
134338     pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
134339     for(i=0; i<pIter->nPhrase; i++){
134340       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
134341       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
134342       fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
134343     }
134344   }
134345
134346   return 0;
134347 }
134348
134349 /*
134350 ** Retrieve information about the current candidate snippet of snippet 
134351 ** iterator pIter.
134352 */
134353 static void fts3SnippetDetails(
134354   SnippetIter *pIter,             /* Snippet iterator */
134355   u64 mCovered,                   /* Bitmask of phrases already covered */
134356   int *piToken,                   /* OUT: First token of proposed snippet */
134357   int *piScore,                   /* OUT: "Score" for this snippet */
134358   u64 *pmCover,                   /* OUT: Bitmask of phrases covered */
134359   u64 *pmHighlight                /* OUT: Bitmask of terms to highlight */
134360 ){
134361   int iStart = pIter->iCurrent;   /* First token of snippet */
134362   int iScore = 0;                 /* Score of this snippet */
134363   int i;                          /* Loop counter */
134364   u64 mCover = 0;                 /* Mask of phrases covered by this snippet */
134365   u64 mHighlight = 0;             /* Mask of tokens to highlight in snippet */
134366
134367   for(i=0; i<pIter->nPhrase; i++){
134368     SnippetPhrase *pPhrase = &pIter->aPhrase[i];
134369     if( pPhrase->pTail ){
134370       char *pCsr = pPhrase->pTail;
134371       int iCsr = pPhrase->iTail;
134372
134373       while( iCsr<(iStart+pIter->nSnippet) ){
134374         int j;
134375         u64 mPhrase = (u64)1 << i;
134376         u64 mPos = (u64)1 << (iCsr - iStart);
134377         assert( iCsr>=iStart );
134378         if( (mCover|mCovered)&mPhrase ){
134379           iScore++;
134380         }else{
134381           iScore += 1000;
134382         }
134383         mCover |= mPhrase;
134384
134385         for(j=0; j<pPhrase->nToken; j++){
134386           mHighlight |= (mPos>>j);
134387         }
134388
134389         if( 0==(*pCsr & 0x0FE) ) break;
134390         fts3GetDeltaPosition(&pCsr, &iCsr);
134391       }
134392     }
134393   }
134394
134395   /* Set the output variables before returning. */
134396   *piToken = iStart;
134397   *piScore = iScore;
134398   *pmCover = mCover;
134399   *pmHighlight = mHighlight;
134400 }
134401
134402 /*
134403 ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
134404 ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
134405 */
134406 static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
134407   SnippetIter *p = (SnippetIter *)ctx;
134408   SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
134409   char *pCsr;
134410   int rc;
134411
134412   pPhrase->nToken = pExpr->pPhrase->nToken;
134413   rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
134414   assert( rc==SQLITE_OK || pCsr==0 );
134415   if( pCsr ){
134416     int iFirst = 0;
134417     pPhrase->pList = pCsr;
134418     fts3GetDeltaPosition(&pCsr, &iFirst);
134419     assert( iFirst>=0 );
134420     pPhrase->pHead = pCsr;
134421     pPhrase->pTail = pCsr;
134422     pPhrase->iHead = iFirst;
134423     pPhrase->iTail = iFirst;
134424   }else{
134425     assert( rc!=SQLITE_OK || (
134426        pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0 
134427     ));
134428   }
134429
134430   return rc;
134431 }
134432
134433 /*
134434 ** Select the fragment of text consisting of nFragment contiguous tokens 
134435 ** from column iCol that represent the "best" snippet. The best snippet
134436 ** is the snippet with the highest score, where scores are calculated
134437 ** by adding:
134438 **
134439 **   (a) +1 point for each occurrence of a matchable phrase in the snippet.
134440 **
134441 **   (b) +1000 points for the first occurrence of each matchable phrase in 
134442 **       the snippet for which the corresponding mCovered bit is not set.
134443 **
134444 ** The selected snippet parameters are stored in structure *pFragment before
134445 ** returning. The score of the selected snippet is stored in *piScore
134446 ** before returning.
134447 */
134448 static int fts3BestSnippet(
134449   int nSnippet,                   /* Desired snippet length */
134450   Fts3Cursor *pCsr,               /* Cursor to create snippet for */
134451   int iCol,                       /* Index of column to create snippet from */
134452   u64 mCovered,                   /* Mask of phrases already covered */
134453   u64 *pmSeen,                    /* IN/OUT: Mask of phrases seen */
134454   SnippetFragment *pFragment,     /* OUT: Best snippet found */
134455   int *piScore                    /* OUT: Score of snippet pFragment */
134456 ){
134457   int rc;                         /* Return Code */
134458   int nList;                      /* Number of phrases in expression */
134459   SnippetIter sIter;              /* Iterates through snippet candidates */
134460   int nByte;                      /* Number of bytes of space to allocate */
134461   int iBestScore = -1;            /* Best snippet score found so far */
134462   int i;                          /* Loop counter */
134463
134464   memset(&sIter, 0, sizeof(sIter));
134465
134466   /* Iterate through the phrases in the expression to count them. The same
134467   ** callback makes sure the doclists are loaded for each phrase.
134468   */
134469   rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
134470   if( rc!=SQLITE_OK ){
134471     return rc;
134472   }
134473
134474   /* Now that it is known how many phrases there are, allocate and zero
134475   ** the required space using malloc().
134476   */
134477   nByte = sizeof(SnippetPhrase) * nList;
134478   sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
134479   if( !sIter.aPhrase ){
134480     return SQLITE_NOMEM;
134481   }
134482   memset(sIter.aPhrase, 0, nByte);
134483
134484   /* Initialize the contents of the SnippetIter object. Then iterate through
134485   ** the set of phrases in the expression to populate the aPhrase[] array.
134486   */
134487   sIter.pCsr = pCsr;
134488   sIter.iCol = iCol;
134489   sIter.nSnippet = nSnippet;
134490   sIter.nPhrase = nList;
134491   sIter.iCurrent = -1;
134492   (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
134493
134494   /* Set the *pmSeen output variable. */
134495   for(i=0; i<nList; i++){
134496     if( sIter.aPhrase[i].pHead ){
134497       *pmSeen |= (u64)1 << i;
134498     }
134499   }
134500
134501   /* Loop through all candidate snippets. Store the best snippet in 
134502   ** *pFragment. Store its associated 'score' in iBestScore.
134503   */
134504   pFragment->iCol = iCol;
134505   while( !fts3SnippetNextCandidate(&sIter) ){
134506     int iPos;
134507     int iScore;
134508     u64 mCover;
134509     u64 mHighlight;
134510     fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight);
134511     assert( iScore>=0 );
134512     if( iScore>iBestScore ){
134513       pFragment->iPos = iPos;
134514       pFragment->hlmask = mHighlight;
134515       pFragment->covered = mCover;
134516       iBestScore = iScore;
134517     }
134518   }
134519
134520   sqlite3_free(sIter.aPhrase);
134521   *piScore = iBestScore;
134522   return SQLITE_OK;
134523 }
134524
134525
134526 /*
134527 ** Append a string to the string-buffer passed as the first argument.
134528 **
134529 ** If nAppend is negative, then the length of the string zAppend is
134530 ** determined using strlen().
134531 */
134532 static int fts3StringAppend(
134533   StrBuffer *pStr,                /* Buffer to append to */
134534   const char *zAppend,            /* Pointer to data to append to buffer */
134535   int nAppend                     /* Size of zAppend in bytes (or -1) */
134536 ){
134537   if( nAppend<0 ){
134538     nAppend = (int)strlen(zAppend);
134539   }
134540
134541   /* If there is insufficient space allocated at StrBuffer.z, use realloc()
134542   ** to grow the buffer until so that it is big enough to accomadate the
134543   ** appended data.
134544   */
134545   if( pStr->n+nAppend+1>=pStr->nAlloc ){
134546     int nAlloc = pStr->nAlloc+nAppend+100;
134547     char *zNew = sqlite3_realloc(pStr->z, nAlloc);
134548     if( !zNew ){
134549       return SQLITE_NOMEM;
134550     }
134551     pStr->z = zNew;
134552     pStr->nAlloc = nAlloc;
134553   }
134554
134555   /* Append the data to the string buffer. */
134556   memcpy(&pStr->z[pStr->n], zAppend, nAppend);
134557   pStr->n += nAppend;
134558   pStr->z[pStr->n] = '\0';
134559
134560   return SQLITE_OK;
134561 }
134562
134563 /*
134564 ** The fts3BestSnippet() function often selects snippets that end with a
134565 ** query term. That is, the final term of the snippet is always a term
134566 ** that requires highlighting. For example, if 'X' is a highlighted term
134567 ** and '.' is a non-highlighted term, BestSnippet() may select:
134568 **
134569 **     ........X.....X
134570 **
134571 ** This function "shifts" the beginning of the snippet forward in the 
134572 ** document so that there are approximately the same number of 
134573 ** non-highlighted terms to the right of the final highlighted term as there
134574 ** are to the left of the first highlighted term. For example, to this:
134575 **
134576 **     ....X.....X....
134577 **
134578 ** This is done as part of extracting the snippet text, not when selecting
134579 ** the snippet. Snippet selection is done based on doclists only, so there
134580 ** is no way for fts3BestSnippet() to know whether or not the document 
134581 ** actually contains terms that follow the final highlighted term. 
134582 */
134583 static int fts3SnippetShift(
134584   Fts3Table *pTab,                /* FTS3 table snippet comes from */
134585   int iLangid,                    /* Language id to use in tokenizing */
134586   int nSnippet,                   /* Number of tokens desired for snippet */
134587   const char *zDoc,               /* Document text to extract snippet from */
134588   int nDoc,                       /* Size of buffer zDoc in bytes */
134589   int *piPos,                     /* IN/OUT: First token of snippet */
134590   u64 *pHlmask                    /* IN/OUT: Mask of tokens to highlight */
134591 ){
134592   u64 hlmask = *pHlmask;          /* Local copy of initial highlight-mask */
134593
134594   if( hlmask ){
134595     int nLeft;                    /* Tokens to the left of first highlight */
134596     int nRight;                   /* Tokens to the right of last highlight */
134597     int nDesired;                 /* Ideal number of tokens to shift forward */
134598
134599     for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
134600     for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
134601     nDesired = (nLeft-nRight)/2;
134602
134603     /* Ideally, the start of the snippet should be pushed forward in the
134604     ** document nDesired tokens. This block checks if there are actually
134605     ** nDesired tokens to the right of the snippet. If so, *piPos and
134606     ** *pHlMask are updated to shift the snippet nDesired tokens to the
134607     ** right. Otherwise, the snippet is shifted by the number of tokens
134608     ** available.
134609     */
134610     if( nDesired>0 ){
134611       int nShift;                 /* Number of tokens to shift snippet by */
134612       int iCurrent = 0;           /* Token counter */
134613       int rc;                     /* Return Code */
134614       sqlite3_tokenizer_module *pMod;
134615       sqlite3_tokenizer_cursor *pC;
134616       pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
134617
134618       /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
134619       ** or more tokens in zDoc/nDoc.
134620       */
134621       rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
134622       if( rc!=SQLITE_OK ){
134623         return rc;
134624       }
134625       while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
134626         const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
134627         rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
134628       }
134629       pMod->xClose(pC);
134630       if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
134631
134632       nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
134633       assert( nShift<=nDesired );
134634       if( nShift>0 ){
134635         *piPos += nShift;
134636         *pHlmask = hlmask >> nShift;
134637       }
134638     }
134639   }
134640   return SQLITE_OK;
134641 }
134642
134643 /*
134644 ** Extract the snippet text for fragment pFragment from cursor pCsr and
134645 ** append it to string buffer pOut.
134646 */
134647 static int fts3SnippetText(
134648   Fts3Cursor *pCsr,               /* FTS3 Cursor */
134649   SnippetFragment *pFragment,     /* Snippet to extract */
134650   int iFragment,                  /* Fragment number */
134651   int isLast,                     /* True for final fragment in snippet */
134652   int nSnippet,                   /* Number of tokens in extracted snippet */
134653   const char *zOpen,              /* String inserted before highlighted term */
134654   const char *zClose,             /* String inserted after highlighted term */
134655   const char *zEllipsis,          /* String inserted between snippets */
134656   StrBuffer *pOut                 /* Write output here */
134657 ){
134658   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
134659   int rc;                         /* Return code */
134660   const char *zDoc;               /* Document text to extract snippet from */
134661   int nDoc;                       /* Size of zDoc in bytes */
134662   int iCurrent = 0;               /* Current token number of document */
134663   int iEnd = 0;                   /* Byte offset of end of current token */
134664   int isShiftDone = 0;            /* True after snippet is shifted */
134665   int iPos = pFragment->iPos;     /* First token of snippet */
134666   u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
134667   int iCol = pFragment->iCol+1;   /* Query column to extract text from */
134668   sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
134669   sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
134670   
134671   zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
134672   if( zDoc==0 ){
134673     if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
134674       return SQLITE_NOMEM;
134675     }
134676     return SQLITE_OK;
134677   }
134678   nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
134679
134680   /* Open a token cursor on the document. */
134681   pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
134682   rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
134683   if( rc!=SQLITE_OK ){
134684     return rc;
134685   }
134686
134687   while( rc==SQLITE_OK ){
134688     const char *ZDUMMY;           /* Dummy argument used with tokenizer */
134689     int DUMMY1 = -1;              /* Dummy argument used with tokenizer */
134690     int iBegin = 0;               /* Offset in zDoc of start of token */
134691     int iFin = 0;                 /* Offset in zDoc of end of token */
134692     int isHighlight = 0;          /* True for highlighted terms */
134693
134694     /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
134695     ** in the FTS code the variable that the third argument to xNext points to
134696     ** is initialized to zero before the first (*but not necessarily
134697     ** subsequent*) call to xNext(). This is done for a particular application
134698     ** that needs to know whether or not the tokenizer is being used for
134699     ** snippet generation or for some other purpose.
134700     **
134701     ** Extreme care is required when writing code to depend on this
134702     ** initialization. It is not a documented part of the tokenizer interface.
134703     ** If a tokenizer is used directly by any code outside of FTS, this
134704     ** convention might not be respected.  */
134705     rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
134706     if( rc!=SQLITE_OK ){
134707       if( rc==SQLITE_DONE ){
134708         /* Special case - the last token of the snippet is also the last token
134709         ** of the column. Append any punctuation that occurred between the end
134710         ** of the previous token and the end of the document to the output. 
134711         ** Then break out of the loop. */
134712         rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
134713       }
134714       break;
134715     }
134716     if( iCurrent<iPos ){ continue; }
134717
134718     if( !isShiftDone ){
134719       int n = nDoc - iBegin;
134720       rc = fts3SnippetShift(
134721           pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
134722       );
134723       isShiftDone = 1;
134724
134725       /* Now that the shift has been done, check if the initial "..." are
134726       ** required. They are required if (a) this is not the first fragment,
134727       ** or (b) this fragment does not begin at position 0 of its column. 
134728       */
134729       if( rc==SQLITE_OK && (iPos>0 || iFragment>0) ){
134730         rc = fts3StringAppend(pOut, zEllipsis, -1);
134731       }
134732       if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
134733     }
134734
134735     if( iCurrent>=(iPos+nSnippet) ){
134736       if( isLast ){
134737         rc = fts3StringAppend(pOut, zEllipsis, -1);
134738       }
134739       break;
134740     }
134741
134742     /* Set isHighlight to true if this term should be highlighted. */
134743     isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
134744
134745     if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
134746     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
134747     if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
134748     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
134749
134750     iEnd = iFin;
134751   }
134752
134753   pMod->xClose(pC);
134754   return rc;
134755 }
134756
134757
134758 /*
134759 ** This function is used to count the entries in a column-list (a 
134760 ** delta-encoded list of term offsets within a single column of a single 
134761 ** row). When this function is called, *ppCollist should point to the
134762 ** beginning of the first varint in the column-list (the varint that
134763 ** contains the position of the first matching term in the column data).
134764 ** Before returning, *ppCollist is set to point to the first byte after
134765 ** the last varint in the column-list (either the 0x00 signifying the end
134766 ** of the position-list, or the 0x01 that precedes the column number of
134767 ** the next column in the position-list).
134768 **
134769 ** The number of elements in the column-list is returned.
134770 */
134771 static int fts3ColumnlistCount(char **ppCollist){
134772   char *pEnd = *ppCollist;
134773   char c = 0;
134774   int nEntry = 0;
134775
134776   /* A column-list is terminated by either a 0x01 or 0x00. */
134777   while( 0xFE & (*pEnd | c) ){
134778     c = *pEnd++ & 0x80;
134779     if( !c ) nEntry++;
134780   }
134781
134782   *ppCollist = pEnd;
134783   return nEntry;
134784 }
134785
134786 /*
134787 ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
134788 ** for a single query. 
134789 **
134790 ** fts3ExprIterate() callback to load the 'global' elements of a
134791 ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements 
134792 ** of the matchinfo array that are constant for all rows returned by the 
134793 ** current query.
134794 **
134795 ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
134796 ** function populates Matchinfo.aMatchinfo[] as follows:
134797 **
134798 **   for(iCol=0; iCol<nCol; iCol++){
134799 **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
134800 **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
134801 **   }
134802 **
134803 ** where X is the number of matches for phrase iPhrase is column iCol of all
134804 ** rows of the table. Y is the number of rows for which column iCol contains
134805 ** at least one instance of phrase iPhrase.
134806 **
134807 ** If the phrase pExpr consists entirely of deferred tokens, then all X and
134808 ** Y values are set to nDoc, where nDoc is the number of documents in the 
134809 ** file system. This is done because the full-text index doclist is required
134810 ** to calculate these values properly, and the full-text index doclist is
134811 ** not available for deferred tokens.
134812 */
134813 static int fts3ExprGlobalHitsCb(
134814   Fts3Expr *pExpr,                /* Phrase expression node */
134815   int iPhrase,                    /* Phrase number (numbered from zero) */
134816   void *pCtx                      /* Pointer to MatchInfo structure */
134817 ){
134818   MatchInfo *p = (MatchInfo *)pCtx;
134819   return sqlite3Fts3EvalPhraseStats(
134820       p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
134821   );
134822 }
134823
134824 /*
134825 ** fts3ExprIterate() callback used to collect the "local" part of the
134826 ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the 
134827 ** array that are different for each row returned by the query.
134828 */
134829 static int fts3ExprLocalHitsCb(
134830   Fts3Expr *pExpr,                /* Phrase expression node */
134831   int iPhrase,                    /* Phrase number */
134832   void *pCtx                      /* Pointer to MatchInfo structure */
134833 ){
134834   int rc = SQLITE_OK;
134835   MatchInfo *p = (MatchInfo *)pCtx;
134836   int iStart = iPhrase * p->nCol * 3;
134837   int i;
134838
134839   for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
134840     char *pCsr;
134841     rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
134842     if( pCsr ){
134843       p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
134844     }else{
134845       p->aMatchinfo[iStart+i*3] = 0;
134846     }
134847   }
134848
134849   return rc;
134850 }
134851
134852 static int fts3MatchinfoCheck(
134853   Fts3Table *pTab, 
134854   char cArg,
134855   char **pzErr
134856 ){
134857   if( (cArg==FTS3_MATCHINFO_NPHRASE)
134858    || (cArg==FTS3_MATCHINFO_NCOL)
134859    || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
134860    || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
134861    || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
134862    || (cArg==FTS3_MATCHINFO_LCS)
134863    || (cArg==FTS3_MATCHINFO_HITS)
134864   ){
134865     return SQLITE_OK;
134866   }
134867   *pzErr = sqlite3_mprintf("unrecognized matchinfo request: %c", cArg);
134868   return SQLITE_ERROR;
134869 }
134870
134871 static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
134872   int nVal;                       /* Number of integers output by cArg */
134873
134874   switch( cArg ){
134875     case FTS3_MATCHINFO_NDOC:
134876     case FTS3_MATCHINFO_NPHRASE: 
134877     case FTS3_MATCHINFO_NCOL: 
134878       nVal = 1;
134879       break;
134880
134881     case FTS3_MATCHINFO_AVGLENGTH:
134882     case FTS3_MATCHINFO_LENGTH:
134883     case FTS3_MATCHINFO_LCS:
134884       nVal = pInfo->nCol;
134885       break;
134886
134887     default:
134888       assert( cArg==FTS3_MATCHINFO_HITS );
134889       nVal = pInfo->nCol * pInfo->nPhrase * 3;
134890       break;
134891   }
134892
134893   return nVal;
134894 }
134895
134896 static int fts3MatchinfoSelectDoctotal(
134897   Fts3Table *pTab,
134898   sqlite3_stmt **ppStmt,
134899   sqlite3_int64 *pnDoc,
134900   const char **paLen
134901 ){
134902   sqlite3_stmt *pStmt;
134903   const char *a;
134904   sqlite3_int64 nDoc;
134905
134906   if( !*ppStmt ){
134907     int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
134908     if( rc!=SQLITE_OK ) return rc;
134909   }
134910   pStmt = *ppStmt;
134911   assert( sqlite3_data_count(pStmt)==1 );
134912
134913   a = sqlite3_column_blob(pStmt, 0);
134914   a += sqlite3Fts3GetVarint(a, &nDoc);
134915   if( nDoc==0 ) return FTS_CORRUPT_VTAB;
134916   *pnDoc = (u32)nDoc;
134917
134918   if( paLen ) *paLen = a;
134919   return SQLITE_OK;
134920 }
134921
134922 /*
134923 ** An instance of the following structure is used to store state while 
134924 ** iterating through a multi-column position-list corresponding to the
134925 ** hits for a single phrase on a single row in order to calculate the
134926 ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
134927 */
134928 typedef struct LcsIterator LcsIterator;
134929 struct LcsIterator {
134930   Fts3Expr *pExpr;                /* Pointer to phrase expression */
134931   int iPosOffset;                 /* Tokens count up to end of this phrase */
134932   char *pRead;                    /* Cursor used to iterate through aDoclist */
134933   int iPos;                       /* Current position */
134934 };
134935
134936 /* 
134937 ** If LcsIterator.iCol is set to the following value, the iterator has
134938 ** finished iterating through all offsets for all columns.
134939 */
134940 #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
134941
134942 static int fts3MatchinfoLcsCb(
134943   Fts3Expr *pExpr,                /* Phrase expression node */
134944   int iPhrase,                    /* Phrase number (numbered from zero) */
134945   void *pCtx                      /* Pointer to MatchInfo structure */
134946 ){
134947   LcsIterator *aIter = (LcsIterator *)pCtx;
134948   aIter[iPhrase].pExpr = pExpr;
134949   return SQLITE_OK;
134950 }
134951
134952 /*
134953 ** Advance the iterator passed as an argument to the next position. Return
134954 ** 1 if the iterator is at EOF or if it now points to the start of the
134955 ** position list for the next column.
134956 */
134957 static int fts3LcsIteratorAdvance(LcsIterator *pIter){
134958   char *pRead = pIter->pRead;
134959   sqlite3_int64 iRead;
134960   int rc = 0;
134961
134962   pRead += sqlite3Fts3GetVarint(pRead, &iRead);
134963   if( iRead==0 || iRead==1 ){
134964     pRead = 0;
134965     rc = 1;
134966   }else{
134967     pIter->iPos += (int)(iRead-2);
134968   }
134969
134970   pIter->pRead = pRead;
134971   return rc;
134972 }
134973   
134974 /*
134975 ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag. 
134976 **
134977 ** If the call is successful, the longest-common-substring lengths for each
134978 ** column are written into the first nCol elements of the pInfo->aMatchinfo[] 
134979 ** array before returning. SQLITE_OK is returned in this case.
134980 **
134981 ** Otherwise, if an error occurs, an SQLite error code is returned and the
134982 ** data written to the first nCol elements of pInfo->aMatchinfo[] is 
134983 ** undefined.
134984 */
134985 static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
134986   LcsIterator *aIter;
134987   int i;
134988   int iCol;
134989   int nToken = 0;
134990
134991   /* Allocate and populate the array of LcsIterator objects. The array
134992   ** contains one element for each matchable phrase in the query.
134993   **/
134994   aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
134995   if( !aIter ) return SQLITE_NOMEM;
134996   memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
134997   (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
134998
134999   for(i=0; i<pInfo->nPhrase; i++){
135000     LcsIterator *pIter = &aIter[i];
135001     nToken -= pIter->pExpr->pPhrase->nToken;
135002     pIter->iPosOffset = nToken;
135003   }
135004
135005   for(iCol=0; iCol<pInfo->nCol; iCol++){
135006     int nLcs = 0;                 /* LCS value for this column */
135007     int nLive = 0;                /* Number of iterators in aIter not at EOF */
135008
135009     for(i=0; i<pInfo->nPhrase; i++){
135010       int rc;
135011       LcsIterator *pIt = &aIter[i];
135012       rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
135013       if( rc!=SQLITE_OK ) return rc;
135014       if( pIt->pRead ){
135015         pIt->iPos = pIt->iPosOffset;
135016         fts3LcsIteratorAdvance(&aIter[i]);
135017         nLive++;
135018       }
135019     }
135020
135021     while( nLive>0 ){
135022       LcsIterator *pAdv = 0;      /* The iterator to advance by one position */
135023       int nThisLcs = 0;           /* LCS for the current iterator positions */
135024
135025       for(i=0; i<pInfo->nPhrase; i++){
135026         LcsIterator *pIter = &aIter[i];
135027         if( pIter->pRead==0 ){
135028           /* This iterator is already at EOF for this column. */
135029           nThisLcs = 0;
135030         }else{
135031           if( pAdv==0 || pIter->iPos<pAdv->iPos ){
135032             pAdv = pIter;
135033           }
135034           if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
135035             nThisLcs++;
135036           }else{
135037             nThisLcs = 1;
135038           }
135039           if( nThisLcs>nLcs ) nLcs = nThisLcs;
135040         }
135041       }
135042       if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
135043     }
135044
135045     pInfo->aMatchinfo[iCol] = nLcs;
135046   }
135047
135048   sqlite3_free(aIter);
135049   return SQLITE_OK;
135050 }
135051
135052 /*
135053 ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
135054 ** be returned by the matchinfo() function. Argument zArg contains the 
135055 ** format string passed as the second argument to matchinfo (or the
135056 ** default value "pcx" if no second argument was specified). The format
135057 ** string has already been validated and the pInfo->aMatchinfo[] array
135058 ** is guaranteed to be large enough for the output.
135059 **
135060 ** If bGlobal is true, then populate all fields of the matchinfo() output.
135061 ** If it is false, then assume that those fields that do not change between
135062 ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
135063 ** have already been populated.
135064 **
135065 ** Return SQLITE_OK if successful, or an SQLite error code if an error 
135066 ** occurs. If a value other than SQLITE_OK is returned, the state the
135067 ** pInfo->aMatchinfo[] buffer is left in is undefined.
135068 */
135069 static int fts3MatchinfoValues(
135070   Fts3Cursor *pCsr,               /* FTS3 cursor object */
135071   int bGlobal,                    /* True to grab the global stats */
135072   MatchInfo *pInfo,               /* Matchinfo context object */
135073   const char *zArg                /* Matchinfo format string */
135074 ){
135075   int rc = SQLITE_OK;
135076   int i;
135077   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
135078   sqlite3_stmt *pSelect = 0;
135079
135080   for(i=0; rc==SQLITE_OK && zArg[i]; i++){
135081
135082     switch( zArg[i] ){
135083       case FTS3_MATCHINFO_NPHRASE:
135084         if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
135085         break;
135086
135087       case FTS3_MATCHINFO_NCOL:
135088         if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
135089         break;
135090         
135091       case FTS3_MATCHINFO_NDOC:
135092         if( bGlobal ){
135093           sqlite3_int64 nDoc = 0;
135094           rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
135095           pInfo->aMatchinfo[0] = (u32)nDoc;
135096         }
135097         break;
135098
135099       case FTS3_MATCHINFO_AVGLENGTH: 
135100         if( bGlobal ){
135101           sqlite3_int64 nDoc;     /* Number of rows in table */
135102           const char *a;          /* Aggregate column length array */
135103
135104           rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
135105           if( rc==SQLITE_OK ){
135106             int iCol;
135107             for(iCol=0; iCol<pInfo->nCol; iCol++){
135108               u32 iVal;
135109               sqlite3_int64 nToken;
135110               a += sqlite3Fts3GetVarint(a, &nToken);
135111               iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
135112               pInfo->aMatchinfo[iCol] = iVal;
135113             }
135114           }
135115         }
135116         break;
135117
135118       case FTS3_MATCHINFO_LENGTH: {
135119         sqlite3_stmt *pSelectDocsize = 0;
135120         rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
135121         if( rc==SQLITE_OK ){
135122           int iCol;
135123           const char *a = sqlite3_column_blob(pSelectDocsize, 0);
135124           for(iCol=0; iCol<pInfo->nCol; iCol++){
135125             sqlite3_int64 nToken;
135126             a += sqlite3Fts3GetVarint(a, &nToken);
135127             pInfo->aMatchinfo[iCol] = (u32)nToken;
135128           }
135129         }
135130         sqlite3_reset(pSelectDocsize);
135131         break;
135132       }
135133
135134       case FTS3_MATCHINFO_LCS:
135135         rc = fts3ExprLoadDoclists(pCsr, 0, 0);
135136         if( rc==SQLITE_OK ){
135137           rc = fts3MatchinfoLcs(pCsr, pInfo);
135138         }
135139         break;
135140
135141       default: {
135142         Fts3Expr *pExpr;
135143         assert( zArg[i]==FTS3_MATCHINFO_HITS );
135144         pExpr = pCsr->pExpr;
135145         rc = fts3ExprLoadDoclists(pCsr, 0, 0);
135146         if( rc!=SQLITE_OK ) break;
135147         if( bGlobal ){
135148           if( pCsr->pDeferred ){
135149             rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
135150             if( rc!=SQLITE_OK ) break;
135151           }
135152           rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
135153           if( rc!=SQLITE_OK ) break;
135154         }
135155         (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
135156         break;
135157       }
135158     }
135159
135160     pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
135161   }
135162
135163   sqlite3_reset(pSelect);
135164   return rc;
135165 }
135166
135167
135168 /*
135169 ** Populate pCsr->aMatchinfo[] with data for the current row. The 
135170 ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
135171 */
135172 static int fts3GetMatchinfo(
135173   Fts3Cursor *pCsr,               /* FTS3 Cursor object */
135174   const char *zArg                /* Second argument to matchinfo() function */
135175 ){
135176   MatchInfo sInfo;
135177   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
135178   int rc = SQLITE_OK;
135179   int bGlobal = 0;                /* Collect 'global' stats as well as local */
135180
135181   memset(&sInfo, 0, sizeof(MatchInfo));
135182   sInfo.pCursor = pCsr;
135183   sInfo.nCol = pTab->nColumn;
135184
135185   /* If there is cached matchinfo() data, but the format string for the 
135186   ** cache does not match the format string for this request, discard 
135187   ** the cached data. */
135188   if( pCsr->zMatchinfo && strcmp(pCsr->zMatchinfo, zArg) ){
135189     assert( pCsr->aMatchinfo );
135190     sqlite3_free(pCsr->aMatchinfo);
135191     pCsr->zMatchinfo = 0;
135192     pCsr->aMatchinfo = 0;
135193   }
135194
135195   /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
135196   ** matchinfo function has been called for this query. In this case 
135197   ** allocate the array used to accumulate the matchinfo data and
135198   ** initialize those elements that are constant for every row.
135199   */
135200   if( pCsr->aMatchinfo==0 ){
135201     int nMatchinfo = 0;           /* Number of u32 elements in match-info */
135202     int nArg;                     /* Bytes in zArg */
135203     int i;                        /* Used to iterate through zArg */
135204
135205     /* Determine the number of phrases in the query */
135206     pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
135207     sInfo.nPhrase = pCsr->nPhrase;
135208
135209     /* Determine the number of integers in the buffer returned by this call. */
135210     for(i=0; zArg[i]; i++){
135211       nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
135212     }
135213
135214     /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
135215     nArg = (int)strlen(zArg);
135216     pCsr->aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo + nArg + 1);
135217     if( !pCsr->aMatchinfo ) return SQLITE_NOMEM;
135218
135219     pCsr->zMatchinfo = (char *)&pCsr->aMatchinfo[nMatchinfo];
135220     pCsr->nMatchinfo = nMatchinfo;
135221     memcpy(pCsr->zMatchinfo, zArg, nArg+1);
135222     memset(pCsr->aMatchinfo, 0, sizeof(u32)*nMatchinfo);
135223     pCsr->isMatchinfoNeeded = 1;
135224     bGlobal = 1;
135225   }
135226
135227   sInfo.aMatchinfo = pCsr->aMatchinfo;
135228   sInfo.nPhrase = pCsr->nPhrase;
135229   if( pCsr->isMatchinfoNeeded ){
135230     rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
135231     pCsr->isMatchinfoNeeded = 0;
135232   }
135233
135234   return rc;
135235 }
135236
135237 /*
135238 ** Implementation of snippet() function.
135239 */
135240 SQLITE_PRIVATE void sqlite3Fts3Snippet(
135241   sqlite3_context *pCtx,          /* SQLite function call context */
135242   Fts3Cursor *pCsr,               /* Cursor object */
135243   const char *zStart,             /* Snippet start text - "<b>" */
135244   const char *zEnd,               /* Snippet end text - "</b>" */
135245   const char *zEllipsis,          /* Snippet ellipsis text - "<b>...</b>" */
135246   int iCol,                       /* Extract snippet from this column */
135247   int nToken                      /* Approximate number of tokens in snippet */
135248 ){
135249   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
135250   int rc = SQLITE_OK;
135251   int i;
135252   StrBuffer res = {0, 0, 0};
135253
135254   /* The returned text includes up to four fragments of text extracted from
135255   ** the data in the current row. The first iteration of the for(...) loop
135256   ** below attempts to locate a single fragment of text nToken tokens in 
135257   ** size that contains at least one instance of all phrases in the query
135258   ** expression that appear in the current row. If such a fragment of text
135259   ** cannot be found, the second iteration of the loop attempts to locate
135260   ** a pair of fragments, and so on.
135261   */
135262   int nSnippet = 0;               /* Number of fragments in this snippet */
135263   SnippetFragment aSnippet[4];    /* Maximum of 4 fragments per snippet */
135264   int nFToken = -1;               /* Number of tokens in each fragment */
135265
135266   if( !pCsr->pExpr ){
135267     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
135268     return;
135269   }
135270
135271   for(nSnippet=1; 1; nSnippet++){
135272
135273     int iSnip;                    /* Loop counter 0..nSnippet-1 */
135274     u64 mCovered = 0;             /* Bitmask of phrases covered by snippet */
135275     u64 mSeen = 0;                /* Bitmask of phrases seen by BestSnippet() */
135276
135277     if( nToken>=0 ){
135278       nFToken = (nToken+nSnippet-1) / nSnippet;
135279     }else{
135280       nFToken = -1 * nToken;
135281     }
135282
135283     for(iSnip=0; iSnip<nSnippet; iSnip++){
135284       int iBestScore = -1;        /* Best score of columns checked so far */
135285       int iRead;                  /* Used to iterate through columns */
135286       SnippetFragment *pFragment = &aSnippet[iSnip];
135287
135288       memset(pFragment, 0, sizeof(*pFragment));
135289
135290       /* Loop through all columns of the table being considered for snippets.
135291       ** If the iCol argument to this function was negative, this means all
135292       ** columns of the FTS3 table. Otherwise, only column iCol is considered.
135293       */
135294       for(iRead=0; iRead<pTab->nColumn; iRead++){
135295         SnippetFragment sF = {0, 0, 0, 0};
135296         int iS;
135297         if( iCol>=0 && iRead!=iCol ) continue;
135298
135299         /* Find the best snippet of nFToken tokens in column iRead. */
135300         rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
135301         if( rc!=SQLITE_OK ){
135302           goto snippet_out;
135303         }
135304         if( iS>iBestScore ){
135305           *pFragment = sF;
135306           iBestScore = iS;
135307         }
135308       }
135309
135310       mCovered |= pFragment->covered;
135311     }
135312
135313     /* If all query phrases seen by fts3BestSnippet() are present in at least
135314     ** one of the nSnippet snippet fragments, break out of the loop.
135315     */
135316     assert( (mCovered&mSeen)==mCovered );
135317     if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
135318   }
135319
135320   assert( nFToken>0 );
135321
135322   for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
135323     rc = fts3SnippetText(pCsr, &aSnippet[i], 
135324         i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
135325     );
135326   }
135327
135328  snippet_out:
135329   sqlite3Fts3SegmentsClose(pTab);
135330   if( rc!=SQLITE_OK ){
135331     sqlite3_result_error_code(pCtx, rc);
135332     sqlite3_free(res.z);
135333   }else{
135334     sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
135335   }
135336 }
135337
135338
135339 typedef struct TermOffset TermOffset;
135340 typedef struct TermOffsetCtx TermOffsetCtx;
135341
135342 struct TermOffset {
135343   char *pList;                    /* Position-list */
135344   int iPos;                       /* Position just read from pList */
135345   int iOff;                       /* Offset of this term from read positions */
135346 };
135347
135348 struct TermOffsetCtx {
135349   Fts3Cursor *pCsr;
135350   int iCol;                       /* Column of table to populate aTerm for */
135351   int iTerm;
135352   sqlite3_int64 iDocid;
135353   TermOffset *aTerm;
135354 };
135355
135356 /*
135357 ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
135358 */
135359 static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
135360   TermOffsetCtx *p = (TermOffsetCtx *)ctx;
135361   int nTerm;                      /* Number of tokens in phrase */
135362   int iTerm;                      /* For looping through nTerm phrase terms */
135363   char *pList;                    /* Pointer to position list for phrase */
135364   int iPos = 0;                   /* First position in position-list */
135365   int rc;
135366
135367   UNUSED_PARAMETER(iPhrase);
135368   rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
135369   nTerm = pExpr->pPhrase->nToken;
135370   if( pList ){
135371     fts3GetDeltaPosition(&pList, &iPos);
135372     assert( iPos>=0 );
135373   }
135374
135375   for(iTerm=0; iTerm<nTerm; iTerm++){
135376     TermOffset *pT = &p->aTerm[p->iTerm++];
135377     pT->iOff = nTerm-iTerm-1;
135378     pT->pList = pList;
135379     pT->iPos = iPos;
135380   }
135381
135382   return rc;
135383 }
135384
135385 /*
135386 ** Implementation of offsets() function.
135387 */
135388 SQLITE_PRIVATE void sqlite3Fts3Offsets(
135389   sqlite3_context *pCtx,          /* SQLite function call context */
135390   Fts3Cursor *pCsr                /* Cursor object */
135391 ){
135392   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
135393   sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
135394   int rc;                         /* Return Code */
135395   int nToken;                     /* Number of tokens in query */
135396   int iCol;                       /* Column currently being processed */
135397   StrBuffer res = {0, 0, 0};      /* Result string */
135398   TermOffsetCtx sCtx;             /* Context for fts3ExprTermOffsetInit() */
135399
135400   if( !pCsr->pExpr ){
135401     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
135402     return;
135403   }
135404
135405   memset(&sCtx, 0, sizeof(sCtx));
135406   assert( pCsr->isRequireSeek==0 );
135407
135408   /* Count the number of terms in the query */
135409   rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
135410   if( rc!=SQLITE_OK ) goto offsets_out;
135411
135412   /* Allocate the array of TermOffset iterators. */
135413   sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
135414   if( 0==sCtx.aTerm ){
135415     rc = SQLITE_NOMEM;
135416     goto offsets_out;
135417   }
135418   sCtx.iDocid = pCsr->iPrevId;
135419   sCtx.pCsr = pCsr;
135420
135421   /* Loop through the table columns, appending offset information to 
135422   ** string-buffer res for each column.
135423   */
135424   for(iCol=0; iCol<pTab->nColumn; iCol++){
135425     sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
135426     const char *ZDUMMY;           /* Dummy argument used with xNext() */
135427     int NDUMMY = 0;               /* Dummy argument used with xNext() */
135428     int iStart = 0;
135429     int iEnd = 0;
135430     int iCurrent = 0;
135431     const char *zDoc;
135432     int nDoc;
135433
135434     /* Initialize the contents of sCtx.aTerm[] for column iCol. There is 
135435     ** no way that this operation can fail, so the return code from
135436     ** fts3ExprIterate() can be discarded.
135437     */
135438     sCtx.iCol = iCol;
135439     sCtx.iTerm = 0;
135440     (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
135441
135442     /* Retreive the text stored in column iCol. If an SQL NULL is stored 
135443     ** in column iCol, jump immediately to the next iteration of the loop.
135444     ** If an OOM occurs while retrieving the data (this can happen if SQLite
135445     ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM 
135446     ** to the caller. 
135447     */
135448     zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
135449     nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
135450     if( zDoc==0 ){
135451       if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
135452         continue;
135453       }
135454       rc = SQLITE_NOMEM;
135455       goto offsets_out;
135456     }
135457
135458     /* Initialize a tokenizer iterator to iterate through column iCol. */
135459     rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
135460         zDoc, nDoc, &pC
135461     );
135462     if( rc!=SQLITE_OK ) goto offsets_out;
135463
135464     rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
135465     while( rc==SQLITE_OK ){
135466       int i;                      /* Used to loop through terms */
135467       int iMinPos = 0x7FFFFFFF;   /* Position of next token */
135468       TermOffset *pTerm = 0;      /* TermOffset associated with next token */
135469
135470       for(i=0; i<nToken; i++){
135471         TermOffset *pT = &sCtx.aTerm[i];
135472         if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
135473           iMinPos = pT->iPos-pT->iOff;
135474           pTerm = pT;
135475         }
135476       }
135477
135478       if( !pTerm ){
135479         /* All offsets for this column have been gathered. */
135480         rc = SQLITE_DONE;
135481       }else{
135482         assert( iCurrent<=iMinPos );
135483         if( 0==(0xFE&*pTerm->pList) ){
135484           pTerm->pList = 0;
135485         }else{
135486           fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
135487         }
135488         while( rc==SQLITE_OK && iCurrent<iMinPos ){
135489           rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
135490         }
135491         if( rc==SQLITE_OK ){
135492           char aBuffer[64];
135493           sqlite3_snprintf(sizeof(aBuffer), aBuffer, 
135494               "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
135495           );
135496           rc = fts3StringAppend(&res, aBuffer, -1);
135497         }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
135498           rc = FTS_CORRUPT_VTAB;
135499         }
135500       }
135501     }
135502     if( rc==SQLITE_DONE ){
135503       rc = SQLITE_OK;
135504     }
135505
135506     pMod->xClose(pC);
135507     if( rc!=SQLITE_OK ) goto offsets_out;
135508   }
135509
135510  offsets_out:
135511   sqlite3_free(sCtx.aTerm);
135512   assert( rc!=SQLITE_DONE );
135513   sqlite3Fts3SegmentsClose(pTab);
135514   if( rc!=SQLITE_OK ){
135515     sqlite3_result_error_code(pCtx,  rc);
135516     sqlite3_free(res.z);
135517   }else{
135518     sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
135519   }
135520   return;
135521 }
135522
135523 /*
135524 ** Implementation of matchinfo() function.
135525 */
135526 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
135527   sqlite3_context *pContext,      /* Function call context */
135528   Fts3Cursor *pCsr,               /* FTS3 table cursor */
135529   const char *zArg                /* Second arg to matchinfo() function */
135530 ){
135531   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
135532   int rc;
135533   int i;
135534   const char *zFormat;
135535
135536   if( zArg ){
135537     for(i=0; zArg[i]; i++){
135538       char *zErr = 0;
135539       if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
135540         sqlite3_result_error(pContext, zErr, -1);
135541         sqlite3_free(zErr);
135542         return;
135543       }
135544     }
135545     zFormat = zArg;
135546   }else{
135547     zFormat = FTS3_MATCHINFO_DEFAULT;
135548   }
135549
135550   if( !pCsr->pExpr ){
135551     sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
135552     return;
135553   }
135554
135555   /* Retrieve matchinfo() data. */
135556   rc = fts3GetMatchinfo(pCsr, zFormat);
135557   sqlite3Fts3SegmentsClose(pTab);
135558
135559   if( rc!=SQLITE_OK ){
135560     sqlite3_result_error_code(pContext, rc);
135561   }else{
135562     int n = pCsr->nMatchinfo * sizeof(u32);
135563     sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
135564   }
135565 }
135566
135567 #endif
135568
135569 /************** End of fts3_snippet.c ****************************************/
135570 /************** Begin file fts3_unicode.c ************************************/
135571 /*
135572 ** 2012 May 24
135573 **
135574 ** The author disclaims copyright to this source code.  In place of
135575 ** a legal notice, here is a blessing:
135576 **
135577 **    May you do good and not evil.
135578 **    May you find forgiveness for yourself and forgive others.
135579 **    May you share freely, never taking more than you give.
135580 **
135581 ******************************************************************************
135582 **
135583 ** Implementation of the "unicode" full-text-search tokenizer.
135584 */
135585
135586 #ifdef SQLITE_ENABLE_FTS4_UNICODE61
135587
135588 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
135589
135590 /* #include <assert.h> */
135591 /* #include <stdlib.h> */
135592 /* #include <stdio.h> */
135593 /* #include <string.h> */
135594
135595
135596 /*
135597 ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
135598 ** from the sqlite3 source file utf.c. If this file is compiled as part
135599 ** of the amalgamation, they are not required.
135600 */
135601 #ifndef SQLITE_AMALGAMATION
135602
135603 static const unsigned char sqlite3Utf8Trans1[] = {
135604   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
135605   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
135606   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
135607   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
135608   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
135609   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
135610   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
135611   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
135612 };
135613
135614 #define READ_UTF8(zIn, zTerm, c)                           \
135615   c = *(zIn++);                                            \
135616   if( c>=0xc0 ){                                           \
135617     c = sqlite3Utf8Trans1[c-0xc0];                         \
135618     while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
135619       c = (c<<6) + (0x3f & *(zIn++));                      \
135620     }                                                      \
135621     if( c<0x80                                             \
135622         || (c&0xFFFFF800)==0xD800                          \
135623         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
135624   }
135625
135626 #define WRITE_UTF8(zOut, c) {                          \
135627   if( c<0x00080 ){                                     \
135628     *zOut++ = (u8)(c&0xFF);                            \
135629   }                                                    \
135630   else if( c<0x00800 ){                                \
135631     *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
135632     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
135633   }                                                    \
135634   else if( c<0x10000 ){                                \
135635     *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
135636     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
135637     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
135638   }else{                                               \
135639     *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
135640     *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
135641     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
135642     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
135643   }                                                    \
135644 }
135645
135646 #endif /* ifndef SQLITE_AMALGAMATION */
135647
135648 typedef struct unicode_tokenizer unicode_tokenizer;
135649 typedef struct unicode_cursor unicode_cursor;
135650
135651 struct unicode_tokenizer {
135652   sqlite3_tokenizer base;
135653   int bRemoveDiacritic;
135654   int nException;
135655   int *aiException;
135656 };
135657
135658 struct unicode_cursor {
135659   sqlite3_tokenizer_cursor base;
135660   const unsigned char *aInput;    /* Input text being tokenized */
135661   int nInput;                     /* Size of aInput[] in bytes */
135662   int iOff;                       /* Current offset within aInput[] */
135663   int iToken;                     /* Index of next token to be returned */
135664   char *zToken;                   /* storage for current token */
135665   int nAlloc;                     /* space allocated at zToken */
135666 };
135667
135668
135669 /*
135670 ** Destroy a tokenizer allocated by unicodeCreate().
135671 */
135672 static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
135673   if( pTokenizer ){
135674     unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
135675     sqlite3_free(p->aiException);
135676     sqlite3_free(p);
135677   }
135678   return SQLITE_OK;
135679 }
135680
135681 /*
135682 ** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
135683 ** statement has specified that the tokenizer for this table shall consider
135684 ** all characters in string zIn/nIn to be separators (if bAlnum==0) or
135685 ** token characters (if bAlnum==1).
135686 **
135687 ** For each codepoint in the zIn/nIn string, this function checks if the
135688 ** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
135689 ** If so, no action is taken. Otherwise, the codepoint is added to the 
135690 ** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
135691 ** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
135692 ** codepoints in the aiException[] array.
135693 **
135694 ** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
135695 ** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
135696 ** It is not possible to change the behavior of the tokenizer with respect
135697 ** to these codepoints.
135698 */
135699 static int unicodeAddExceptions(
135700   unicode_tokenizer *p,           /* Tokenizer to add exceptions to */
135701   int bAlnum,                     /* Replace Isalnum() return value with this */
135702   const char *zIn,                /* Array of characters to make exceptions */
135703   int nIn                         /* Length of z in bytes */
135704 ){
135705   const unsigned char *z = (const unsigned char *)zIn;
135706   const unsigned char *zTerm = &z[nIn];
135707   int iCode;
135708   int nEntry = 0;
135709
135710   assert( bAlnum==0 || bAlnum==1 );
135711
135712   while( z<zTerm ){
135713     READ_UTF8(z, zTerm, iCode);
135714     assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
135715     if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum 
135716      && sqlite3FtsUnicodeIsdiacritic(iCode)==0 
135717     ){
135718       nEntry++;
135719     }
135720   }
135721
135722   if( nEntry ){
135723     int *aNew;                    /* New aiException[] array */
135724     int nNew;                     /* Number of valid entries in array aNew[] */
135725
135726     aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));
135727     if( aNew==0 ) return SQLITE_NOMEM;
135728     nNew = p->nException;
135729
135730     z = (const unsigned char *)zIn;
135731     while( z<zTerm ){
135732       READ_UTF8(z, zTerm, iCode);
135733       if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum 
135734        && sqlite3FtsUnicodeIsdiacritic(iCode)==0
135735       ){
135736         int i, j;
135737         for(i=0; i<nNew && aNew[i]<iCode; i++);
135738         for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
135739         aNew[i] = iCode;
135740         nNew++;
135741       }
135742     }
135743     p->aiException = aNew;
135744     p->nException = nNew;
135745   }
135746
135747   return SQLITE_OK;
135748 }
135749
135750 /*
135751 ** Return true if the p->aiException[] array contains the value iCode.
135752 */
135753 static int unicodeIsException(unicode_tokenizer *p, int iCode){
135754   if( p->nException>0 ){
135755     int *a = p->aiException;
135756     int iLo = 0;
135757     int iHi = p->nException-1;
135758
135759     while( iHi>=iLo ){
135760       int iTest = (iHi + iLo) / 2;
135761       if( iCode==a[iTest] ){
135762         return 1;
135763       }else if( iCode>a[iTest] ){
135764         iLo = iTest+1;
135765       }else{
135766         iHi = iTest-1;
135767       }
135768     }
135769   }
135770
135771   return 0;
135772 }
135773
135774 /*
135775 ** Return true if, for the purposes of tokenization, codepoint iCode is
135776 ** considered a token character (not a separator).
135777 */
135778 static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
135779   assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
135780   return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
135781 }
135782
135783 /*
135784 ** Create a new tokenizer instance.
135785 */
135786 static int unicodeCreate(
135787   int nArg,                       /* Size of array argv[] */
135788   const char * const *azArg,      /* Tokenizer creation arguments */
135789   sqlite3_tokenizer **pp          /* OUT: New tokenizer handle */
135790 ){
135791   unicode_tokenizer *pNew;        /* New tokenizer object */
135792   int i;
135793   int rc = SQLITE_OK;
135794
135795   pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
135796   if( pNew==NULL ) return SQLITE_NOMEM;
135797   memset(pNew, 0, sizeof(unicode_tokenizer));
135798   pNew->bRemoveDiacritic = 1;
135799
135800   for(i=0; rc==SQLITE_OK && i<nArg; i++){
135801     const char *z = azArg[i];
135802     int n = strlen(z);
135803
135804     if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
135805       pNew->bRemoveDiacritic = 1;
135806     }
135807     else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
135808       pNew->bRemoveDiacritic = 0;
135809     }
135810     else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
135811       rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
135812     }
135813     else if( n>=11 && memcmp("separators=", z, 11)==0 ){
135814       rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
135815     }
135816     else{
135817       /* Unrecognized argument */
135818       rc  = SQLITE_ERROR;
135819     }
135820   }
135821
135822   if( rc!=SQLITE_OK ){
135823     unicodeDestroy((sqlite3_tokenizer *)pNew);
135824     pNew = 0;
135825   }
135826   *pp = (sqlite3_tokenizer *)pNew;
135827   return rc;
135828 }
135829
135830 /*
135831 ** Prepare to begin tokenizing a particular string.  The input
135832 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
135833 ** used to incrementally tokenize this string is returned in 
135834 ** *ppCursor.
135835 */
135836 static int unicodeOpen(
135837   sqlite3_tokenizer *p,           /* The tokenizer */
135838   const char *aInput,             /* Input string */
135839   int nInput,                     /* Size of string aInput in bytes */
135840   sqlite3_tokenizer_cursor **pp   /* OUT: New cursor object */
135841 ){
135842   unicode_cursor *pCsr;
135843
135844   pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
135845   if( pCsr==0 ){
135846     return SQLITE_NOMEM;
135847   }
135848   memset(pCsr, 0, sizeof(unicode_cursor));
135849
135850   pCsr->aInput = (const unsigned char *)aInput;
135851   if( aInput==0 ){
135852     pCsr->nInput = 0;
135853   }else if( nInput<0 ){
135854     pCsr->nInput = (int)strlen(aInput);
135855   }else{
135856     pCsr->nInput = nInput;
135857   }
135858
135859   *pp = &pCsr->base;
135860   UNUSED_PARAMETER(p);
135861   return SQLITE_OK;
135862 }
135863
135864 /*
135865 ** Close a tokenization cursor previously opened by a call to
135866 ** simpleOpen() above.
135867 */
135868 static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
135869   unicode_cursor *pCsr = (unicode_cursor *) pCursor;
135870   sqlite3_free(pCsr->zToken);
135871   sqlite3_free(pCsr);
135872   return SQLITE_OK;
135873 }
135874
135875 /*
135876 ** Extract the next token from a tokenization cursor.  The cursor must
135877 ** have been opened by a prior call to simpleOpen().
135878 */
135879 static int unicodeNext(
135880   sqlite3_tokenizer_cursor *pC,   /* Cursor returned by simpleOpen */
135881   const char **paToken,           /* OUT: Token text */
135882   int *pnToken,                   /* OUT: Number of bytes at *paToken */
135883   int *piStart,                   /* OUT: Starting offset of token */
135884   int *piEnd,                     /* OUT: Ending offset of token */
135885   int *piPos                      /* OUT: Position integer of token */
135886 ){
135887   unicode_cursor *pCsr = (unicode_cursor *)pC;
135888   unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
135889   int iCode;
135890   char *zOut;
135891   const unsigned char *z = &pCsr->aInput[pCsr->iOff];
135892   const unsigned char *zStart = z;
135893   const unsigned char *zEnd;
135894   const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
135895
135896   /* Scan past any delimiter characters before the start of the next token.
135897   ** Return SQLITE_DONE early if this takes us all the way to the end of 
135898   ** the input.  */
135899   while( z<zTerm ){
135900     READ_UTF8(z, zTerm, iCode);
135901     if( unicodeIsAlnum(p, iCode) ) break;
135902     zStart = z;
135903   }
135904   if( zStart>=zTerm ) return SQLITE_DONE;
135905
135906   zOut = pCsr->zToken;
135907   do {
135908     int iOut;
135909
135910     /* Grow the output buffer if required. */
135911     if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
135912       char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);
135913       if( !zNew ) return SQLITE_NOMEM;
135914       zOut = &zNew[zOut - pCsr->zToken];
135915       pCsr->zToken = zNew;
135916       pCsr->nAlloc += 64;
135917     }
135918
135919     /* Write the folded case of the last character read to the output */
135920     zEnd = z;
135921     iOut = sqlite3FtsUnicodeFold(iCode, p->bRemoveDiacritic);
135922     if( iOut ){
135923       WRITE_UTF8(zOut, iOut);
135924     }
135925
135926     /* If the cursor is not at EOF, read the next character */
135927     if( z>=zTerm ) break;
135928     READ_UTF8(z, zTerm, iCode);
135929   }while( unicodeIsAlnum(p, iCode) 
135930        || sqlite3FtsUnicodeIsdiacritic(iCode)
135931   );
135932
135933   /* Set the output variables and return. */
135934   pCsr->iOff = (z - pCsr->aInput);
135935   *paToken = pCsr->zToken;
135936   *pnToken = zOut - pCsr->zToken;
135937   *piStart = (zStart - pCsr->aInput);
135938   *piEnd = (zEnd - pCsr->aInput);
135939   *piPos = pCsr->iToken++;
135940   return SQLITE_OK;
135941 }
135942
135943 /*
135944 ** Set *ppModule to a pointer to the sqlite3_tokenizer_module 
135945 ** structure for the unicode tokenizer.
135946 */
135947 SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
135948   static const sqlite3_tokenizer_module module = {
135949     0,
135950     unicodeCreate,
135951     unicodeDestroy,
135952     unicodeOpen,
135953     unicodeClose,
135954     unicodeNext,
135955     0,
135956   };
135957   *ppModule = &module;
135958 }
135959
135960 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
135961 #endif /* ifndef SQLITE_ENABLE_FTS4_UNICODE61 */
135962
135963 /************** End of fts3_unicode.c ****************************************/
135964 /************** Begin file fts3_unicode2.c ***********************************/
135965 /*
135966 ** 2012 May 25
135967 **
135968 ** The author disclaims copyright to this source code.  In place of
135969 ** a legal notice, here is a blessing:
135970 **
135971 **    May you do good and not evil.
135972 **    May you find forgiveness for yourself and forgive others.
135973 **    May you share freely, never taking more than you give.
135974 **
135975 ******************************************************************************
135976 */
135977
135978 /*
135979 ** DO NOT EDIT THIS MACHINE GENERATED FILE.
135980 */
135981
135982 #if defined(SQLITE_ENABLE_FTS4_UNICODE61)
135983 #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
135984
135985 /* #include <assert.h> */
135986
135987 /*
135988 ** Return true if the argument corresponds to a unicode codepoint
135989 ** classified as either a letter or a number. Otherwise false.
135990 **
135991 ** The results are undefined if the value passed to this function
135992 ** is less than zero.
135993 */
135994 SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
135995   /* Each unsigned integer in the following array corresponds to a contiguous
135996   ** range of unicode codepoints that are not either letters or numbers (i.e.
135997   ** codepoints for which this function should return 0).
135998   **
135999   ** The most significant 22 bits in each 32-bit value contain the first 
136000   ** codepoint in the range. The least significant 10 bits are used to store
136001   ** the size of the range (always at least 1). In other words, the value 
136002   ** ((C<<22) + N) represents a range of N codepoints starting with codepoint 
136003   ** C. It is not possible to represent a range larger than 1023 codepoints 
136004   ** using this format.
136005   */
136006   const static unsigned int aEntry[] = {
136007     0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
136008     0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
136009     0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
136010     0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
136011     0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
136012     0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
136013     0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
136014     0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
136015     0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
136016     0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
136017     0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
136018     0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
136019     0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
136020     0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
136021     0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
136022     0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
136023     0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
136024     0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
136025     0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
136026     0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
136027     0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
136028     0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
136029     0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
136030     0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
136031     0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
136032     0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
136033     0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
136034     0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
136035     0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
136036     0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
136037     0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
136038     0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
136039     0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
136040     0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
136041     0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
136042     0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
136043     0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
136044     0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
136045     0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
136046     0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
136047     0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
136048     0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
136049     0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
136050     0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
136051     0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
136052     0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
136053     0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
136054     0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
136055     0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
136056     0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
136057     0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
136058     0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
136059     0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
136060     0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
136061     0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
136062     0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
136063     0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
136064     0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
136065     0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
136066     0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
136067     0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
136068     0x037FFC02, 0x03E3FC01, 0x03EC7801, 0x03ECA401, 0x03EEC810,
136069     0x03F4F802, 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023,
136070     0x03F95013, 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807,
136071     0x03FCEC06, 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405,
136072     0x04040003, 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E,
136073     0x040E7C01, 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01,
136074     0x04280403, 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01,
136075     0x04294009, 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016,
136076     0x04420003, 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004,
136077     0x04460003, 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004,
136078     0x05BD442E, 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5,
136079     0x07480046, 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01,
136080     0x075C5401, 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401,
136081     0x075EA401, 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064,
136082     0x07C2800F, 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F,
136083     0x07C4C03C, 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009,
136084     0x07C94002, 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014,
136085     0x07CE8025, 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001,
136086     0x07D108B6, 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018,
136087     0x07D7EC46, 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401,
136088     0x38008060, 0x380400F0, 0x3C000001, 0x3FFFF401, 0x40000001,
136089     0x43FFF401,
136090   };
136091   static const unsigned int aAscii[4] = {
136092     0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
136093   };
136094
136095   if( c<128 ){
136096     return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
136097   }else if( c<(1<<22) ){
136098     unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
136099     int iRes;
136100     int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
136101     int iLo = 0;
136102     while( iHi>=iLo ){
136103       int iTest = (iHi + iLo) / 2;
136104       if( key >= aEntry[iTest] ){
136105         iRes = iTest;
136106         iLo = iTest+1;
136107       }else{
136108         iHi = iTest-1;
136109       }
136110     }
136111     assert( aEntry[0]<key );
136112     assert( key>=aEntry[iRes] );
136113     return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
136114   }
136115   return 1;
136116 }
136117
136118
136119 /*
136120 ** If the argument is a codepoint corresponding to a lowercase letter
136121 ** in the ASCII range with a diacritic added, return the codepoint
136122 ** of the ASCII letter only. For example, if passed 235 - "LATIN
136123 ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
136124 ** E"). The resuls of passing a codepoint that corresponds to an
136125 ** uppercase letter are undefined.
136126 */
136127 static int remove_diacritic(int c){
136128   unsigned short aDia[] = {
136129         0,  1797,  1848,  1859,  1891,  1928,  1940,  1995, 
136130      2024,  2040,  2060,  2110,  2168,  2206,  2264,  2286, 
136131      2344,  2383,  2472,  2488,  2516,  2596,  2668,  2732, 
136132      2782,  2842,  2894,  2954,  2984,  3000,  3028,  3336, 
136133      3456,  3696,  3712,  3728,  3744,  3896,  3912,  3928, 
136134      3968,  4008,  4040,  4106,  4138,  4170,  4202,  4234, 
136135      4266,  4296,  4312,  4344,  4408,  4424,  4472,  4504, 
136136      6148,  6198,  6264,  6280,  6360,  6429,  6505,  6529, 
136137     61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726, 
136138     61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122, 
136139     62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536, 
136140     62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730, 
136141     62924, 63050, 63082, 63274, 63390, 
136142   };
136143   char aChar[] = {
136144     '\0', 'a',  'c',  'e',  'i',  'n',  'o',  'u',  'y',  'y',  'a',  'c',  
136145     'd',  'e',  'e',  'g',  'h',  'i',  'j',  'k',  'l',  'n',  'o',  'r',  
136146     's',  't',  'u',  'u',  'w',  'y',  'z',  'o',  'u',  'a',  'i',  'o',  
136147     'u',  'g',  'k',  'o',  'j',  'g',  'n',  'a',  'e',  'i',  'o',  'r',  
136148     'u',  's',  't',  'h',  'a',  'e',  'o',  'y',  '\0', '\0', '\0', '\0', 
136149     '\0', '\0', '\0', '\0', 'a',  'b',  'd',  'd',  'e',  'f',  'g',  'h',  
136150     'h',  'i',  'k',  'l',  'l',  'm',  'n',  'p',  'r',  'r',  's',  't',  
136151     'u',  'v',  'w',  'w',  'x',  'y',  'z',  'h',  't',  'w',  'y',  'a',  
136152     'e',  'i',  'o',  'u',  'y',  
136153   };
136154
136155   unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
136156   int iRes = 0;
136157   int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
136158   int iLo = 0;
136159   while( iHi>=iLo ){
136160     int iTest = (iHi + iLo) / 2;
136161     if( key >= aDia[iTest] ){
136162       iRes = iTest;
136163       iLo = iTest+1;
136164     }else{
136165       iHi = iTest-1;
136166     }
136167   }
136168   assert( key>=aDia[iRes] );
136169   return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
136170 };
136171
136172
136173 /*
136174 ** Return true if the argument interpreted as a unicode codepoint
136175 ** is a diacritical modifier character.
136176 */
136177 SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
136178   unsigned int mask0 = 0x08029FDF;
136179   unsigned int mask1 = 0x000361F8;
136180   if( c<768 || c>817 ) return 0;
136181   return (c < 768+32) ?
136182       (mask0 & (1 << (c-768))) :
136183       (mask1 & (1 << (c-768-32)));
136184 }
136185
136186
136187 /*
136188 ** Interpret the argument as a unicode codepoint. If the codepoint
136189 ** is an upper case character that has a lower case equivalent,
136190 ** return the codepoint corresponding to the lower case version.
136191 ** Otherwise, return a copy of the argument.
136192 **
136193 ** The results are undefined if the value passed to this function
136194 ** is less than zero.
136195 */
136196 SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){
136197   /* Each entry in the following array defines a rule for folding a range
136198   ** of codepoints to lower case. The rule applies to a range of nRange
136199   ** codepoints starting at codepoint iCode.
136200   **
136201   ** If the least significant bit in flags is clear, then the rule applies
136202   ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
136203   ** need to be folded). Or, if it is set, then the rule only applies to
136204   ** every second codepoint in the range, starting with codepoint C.
136205   **
136206   ** The 7 most significant bits in flags are an index into the aiOff[]
136207   ** array. If a specific codepoint C does require folding, then its lower
136208   ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
136209   **
136210   ** The contents of this array are generated by parsing the CaseFolding.txt
136211   ** file distributed as part of the "Unicode Character Database". See
136212   ** http://www.unicode.org for details.
136213   */
136214   static const struct TableEntry {
136215     unsigned short iCode;
136216     unsigned char flags;
136217     unsigned char nRange;
136218   } aEntry[] = {
136219     {65, 14, 26},          {181, 64, 1},          {192, 14, 23},
136220     {216, 14, 7},          {256, 1, 48},          {306, 1, 6},
136221     {313, 1, 16},          {330, 1, 46},          {376, 116, 1},
136222     {377, 1, 6},           {383, 104, 1},         {385, 50, 1},
136223     {386, 1, 4},           {390, 44, 1},          {391, 0, 1},
136224     {393, 42, 2},          {395, 0, 1},           {398, 32, 1},
136225     {399, 38, 1},          {400, 40, 1},          {401, 0, 1},
136226     {403, 42, 1},          {404, 46, 1},          {406, 52, 1},
136227     {407, 48, 1},          {408, 0, 1},           {412, 52, 1},
136228     {413, 54, 1},          {415, 56, 1},          {416, 1, 6},
136229     {422, 60, 1},          {423, 0, 1},           {425, 60, 1},
136230     {428, 0, 1},           {430, 60, 1},          {431, 0, 1},
136231     {433, 58, 2},          {435, 1, 4},           {439, 62, 1},
136232     {440, 0, 1},           {444, 0, 1},           {452, 2, 1},
136233     {453, 0, 1},           {455, 2, 1},           {456, 0, 1},
136234     {458, 2, 1},           {459, 1, 18},          {478, 1, 18},
136235     {497, 2, 1},           {498, 1, 4},           {502, 122, 1},
136236     {503, 134, 1},         {504, 1, 40},          {544, 110, 1},
136237     {546, 1, 18},          {570, 70, 1},          {571, 0, 1},
136238     {573, 108, 1},         {574, 68, 1},          {577, 0, 1},
136239     {579, 106, 1},         {580, 28, 1},          {581, 30, 1},
136240     {582, 1, 10},          {837, 36, 1},          {880, 1, 4},
136241     {886, 0, 1},           {902, 18, 1},          {904, 16, 3},
136242     {908, 26, 1},          {910, 24, 2},          {913, 14, 17},
136243     {931, 14, 9},          {962, 0, 1},           {975, 4, 1},
136244     {976, 140, 1},         {977, 142, 1},         {981, 146, 1},
136245     {982, 144, 1},         {984, 1, 24},          {1008, 136, 1},
136246     {1009, 138, 1},        {1012, 130, 1},        {1013, 128, 1},
136247     {1015, 0, 1},          {1017, 152, 1},        {1018, 0, 1},
136248     {1021, 110, 3},        {1024, 34, 16},        {1040, 14, 32},
136249     {1120, 1, 34},         {1162, 1, 54},         {1216, 6, 1},
136250     {1217, 1, 14},         {1232, 1, 88},         {1329, 22, 38},
136251     {4256, 66, 38},        {4295, 66, 1},         {4301, 66, 1},
136252     {7680, 1, 150},        {7835, 132, 1},        {7838, 96, 1},
136253     {7840, 1, 96},         {7944, 150, 8},        {7960, 150, 6},
136254     {7976, 150, 8},        {7992, 150, 8},        {8008, 150, 6},
136255     {8025, 151, 8},        {8040, 150, 8},        {8072, 150, 8},
136256     {8088, 150, 8},        {8104, 150, 8},        {8120, 150, 2},
136257     {8122, 126, 2},        {8124, 148, 1},        {8126, 100, 1},
136258     {8136, 124, 4},        {8140, 148, 1},        {8152, 150, 2},
136259     {8154, 120, 2},        {8168, 150, 2},        {8170, 118, 2},
136260     {8172, 152, 1},        {8184, 112, 2},        {8186, 114, 2},
136261     {8188, 148, 1},        {8486, 98, 1},         {8490, 92, 1},
136262     {8491, 94, 1},         {8498, 12, 1},         {8544, 8, 16},
136263     {8579, 0, 1},          {9398, 10, 26},        {11264, 22, 47},
136264     {11360, 0, 1},         {11362, 88, 1},        {11363, 102, 1},
136265     {11364, 90, 1},        {11367, 1, 6},         {11373, 84, 1},
136266     {11374, 86, 1},        {11375, 80, 1},        {11376, 82, 1},
136267     {11378, 0, 1},         {11381, 0, 1},         {11390, 78, 2},
136268     {11392, 1, 100},       {11499, 1, 4},         {11506, 0, 1},
136269     {42560, 1, 46},        {42624, 1, 24},        {42786, 1, 14},
136270     {42802, 1, 62},        {42873, 1, 4},         {42877, 76, 1},
136271     {42878, 1, 10},        {42891, 0, 1},         {42893, 74, 1},
136272     {42896, 1, 4},         {42912, 1, 10},        {42922, 72, 1},
136273     {65313, 14, 26},       
136274   };
136275   static const unsigned short aiOff[] = {
136276    1,     2,     8,     15,    16,    26,    28,    32,    
136277    37,    38,    40,    48,    63,    64,    69,    71,    
136278    79,    80,    116,   202,   203,   205,   206,   207,   
136279    209,   210,   211,   213,   214,   217,   218,   219,   
136280    775,   7264,  10792, 10795, 23228, 23256, 30204, 54721, 
136281    54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274, 
136282    57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406, 
136283    65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462, 
136284    65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511, 
136285    65514, 65521, 65527, 65528, 65529, 
136286   };
136287
136288   int ret = c;
136289
136290   assert( c>=0 );
136291   assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
136292
136293   if( c<128 ){
136294     if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
136295   }else if( c<65536 ){
136296     int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
136297     int iLo = 0;
136298     int iRes = -1;
136299
136300     while( iHi>=iLo ){
136301       int iTest = (iHi + iLo) / 2;
136302       int cmp = (c - aEntry[iTest].iCode);
136303       if( cmp>=0 ){
136304         iRes = iTest;
136305         iLo = iTest+1;
136306       }else{
136307         iHi = iTest-1;
136308       }
136309     }
136310     assert( iRes<0 || c>=aEntry[iRes].iCode );
136311
136312     if( iRes>=0 ){
136313       const struct TableEntry *p = &aEntry[iRes];
136314       if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
136315         ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
136316         assert( ret>0 );
136317       }
136318     }
136319
136320     if( bRemoveDiacritic ) ret = remove_diacritic(ret);
136321   }
136322   
136323   else if( c>=66560 && c<66600 ){
136324     ret = c + 40;
136325   }
136326
136327   return ret;
136328 }
136329 #endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
136330 #endif /* !defined(SQLITE_ENABLE_FTS4_UNICODE61) */
136331
136332 /************** End of fts3_unicode2.c ***************************************/
136333 /************** Begin file rtree.c *******************************************/
136334 /*
136335 ** 2001 September 15
136336 **
136337 ** The author disclaims copyright to this source code.  In place of
136338 ** a legal notice, here is a blessing:
136339 **
136340 **    May you do good and not evil.
136341 **    May you find forgiveness for yourself and forgive others.
136342 **    May you share freely, never taking more than you give.
136343 **
136344 *************************************************************************
136345 ** This file contains code for implementations of the r-tree and r*-tree
136346 ** algorithms packaged as an SQLite virtual table module.
136347 */
136348
136349 /*
136350 ** Database Format of R-Tree Tables
136351 ** --------------------------------
136352 **
136353 ** The data structure for a single virtual r-tree table is stored in three 
136354 ** native SQLite tables declared as follows. In each case, the '%' character
136355 ** in the table name is replaced with the user-supplied name of the r-tree
136356 ** table.
136357 **
136358 **   CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
136359 **   CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
136360 **   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
136361 **
136362 ** The data for each node of the r-tree structure is stored in the %_node
136363 ** table. For each node that is not the root node of the r-tree, there is
136364 ** an entry in the %_parent table associating the node with its parent.
136365 ** And for each row of data in the table, there is an entry in the %_rowid
136366 ** table that maps from the entries rowid to the id of the node that it
136367 ** is stored on.
136368 **
136369 ** The root node of an r-tree always exists, even if the r-tree table is
136370 ** empty. The nodeno of the root node is always 1. All other nodes in the
136371 ** table must be the same size as the root node. The content of each node
136372 ** is formatted as follows:
136373 **
136374 **   1. If the node is the root node (node 1), then the first 2 bytes
136375 **      of the node contain the tree depth as a big-endian integer.
136376 **      For non-root nodes, the first 2 bytes are left unused.
136377 **
136378 **   2. The next 2 bytes contain the number of entries currently 
136379 **      stored in the node.
136380 **
136381 **   3. The remainder of the node contains the node entries. Each entry
136382 **      consists of a single 8-byte integer followed by an even number
136383 **      of 4-byte coordinates. For leaf nodes the integer is the rowid
136384 **      of a record. For internal nodes it is the node number of a
136385 **      child page.
136386 */
136387
136388 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
136389
136390 /*
136391 ** This file contains an implementation of a couple of different variants
136392 ** of the r-tree algorithm. See the README file for further details. The 
136393 ** same data-structure is used for all, but the algorithms for insert and
136394 ** delete operations vary. The variants used are selected at compile time 
136395 ** by defining the following symbols:
136396 */
136397
136398 /* Either, both or none of the following may be set to activate 
136399 ** r*tree variant algorithms.
136400 */
136401 #define VARIANT_RSTARTREE_CHOOSESUBTREE 0
136402 #define VARIANT_RSTARTREE_REINSERT      1
136403
136404 /* 
136405 ** Exactly one of the following must be set to 1.
136406 */
136407 #define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
136408 #define VARIANT_GUTTMAN_LINEAR_SPLIT    0
136409 #define VARIANT_RSTARTREE_SPLIT         1
136410
136411 #define VARIANT_GUTTMAN_SPLIT \
136412         (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
136413
136414 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
136415   #define PickNext QuadraticPickNext
136416   #define PickSeeds QuadraticPickSeeds
136417   #define AssignCells splitNodeGuttman
136418 #endif
136419 #if VARIANT_GUTTMAN_LINEAR_SPLIT
136420   #define PickNext LinearPickNext
136421   #define PickSeeds LinearPickSeeds
136422   #define AssignCells splitNodeGuttman
136423 #endif
136424 #if VARIANT_RSTARTREE_SPLIT
136425   #define AssignCells splitNodeStartree
136426 #endif
136427
136428 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
136429 # define NDEBUG 1
136430 #endif
136431
136432 #ifndef SQLITE_CORE
136433   SQLITE_EXTENSION_INIT1
136434 #else
136435 #endif
136436
136437 /* #include <string.h> */
136438 /* #include <assert.h> */
136439
136440 #ifndef SQLITE_AMALGAMATION
136441 #include "sqlite3rtree.h"
136442 typedef sqlite3_int64 i64;
136443 typedef unsigned char u8;
136444 typedef unsigned int u32;
136445 #endif
136446
136447 /*  The following macro is used to suppress compiler warnings.
136448 */
136449 #ifndef UNUSED_PARAMETER
136450 # define UNUSED_PARAMETER(x) (void)(x)
136451 #endif
136452
136453 typedef struct Rtree Rtree;
136454 typedef struct RtreeCursor RtreeCursor;
136455 typedef struct RtreeNode RtreeNode;
136456 typedef struct RtreeCell RtreeCell;
136457 typedef struct RtreeConstraint RtreeConstraint;
136458 typedef struct RtreeMatchArg RtreeMatchArg;
136459 typedef struct RtreeGeomCallback RtreeGeomCallback;
136460 typedef union RtreeCoord RtreeCoord;
136461
136462 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
136463 #define RTREE_MAX_DIMENSIONS 5
136464
136465 /* Size of hash table Rtree.aHash. This hash table is not expected to
136466 ** ever contain very many entries, so a fixed number of buckets is 
136467 ** used.
136468 */
136469 #define HASHSIZE 128
136470
136471 /* 
136472 ** An rtree virtual-table object.
136473 */
136474 struct Rtree {
136475   sqlite3_vtab base;
136476   sqlite3 *db;                /* Host database connection */
136477   int iNodeSize;              /* Size in bytes of each node in the node table */
136478   int nDim;                   /* Number of dimensions */
136479   int nBytesPerCell;          /* Bytes consumed per cell */
136480   int iDepth;                 /* Current depth of the r-tree structure */
136481   char *zDb;                  /* Name of database containing r-tree table */
136482   char *zName;                /* Name of r-tree table */ 
136483   RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */ 
136484   int nBusy;                  /* Current number of users of this structure */
136485
136486   /* List of nodes removed during a CondenseTree operation. List is
136487   ** linked together via the pointer normally used for hash chains -
136488   ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree 
136489   ** headed by the node (leaf nodes have RtreeNode.iNode==0).
136490   */
136491   RtreeNode *pDeleted;
136492   int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
136493
136494   /* Statements to read/write/delete a record from xxx_node */
136495   sqlite3_stmt *pReadNode;
136496   sqlite3_stmt *pWriteNode;
136497   sqlite3_stmt *pDeleteNode;
136498
136499   /* Statements to read/write/delete a record from xxx_rowid */
136500   sqlite3_stmt *pReadRowid;
136501   sqlite3_stmt *pWriteRowid;
136502   sqlite3_stmt *pDeleteRowid;
136503
136504   /* Statements to read/write/delete a record from xxx_parent */
136505   sqlite3_stmt *pReadParent;
136506   sqlite3_stmt *pWriteParent;
136507   sqlite3_stmt *pDeleteParent;
136508
136509   int eCoordType;
136510 };
136511
136512 /* Possible values for eCoordType: */
136513 #define RTREE_COORD_REAL32 0
136514 #define RTREE_COORD_INT32  1
136515
136516 /*
136517 ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
136518 ** only deal with integer coordinates.  No floating point operations
136519 ** will be done.
136520 */
136521 #ifdef SQLITE_RTREE_INT_ONLY
136522   typedef sqlite3_int64 RtreeDValue;       /* High accuracy coordinate */
136523   typedef int RtreeValue;                  /* Low accuracy coordinate */
136524 #else
136525   typedef double RtreeDValue;              /* High accuracy coordinate */
136526   typedef float RtreeValue;                /* Low accuracy coordinate */
136527 #endif
136528
136529 /*
136530 ** The minimum number of cells allowed for a node is a third of the 
136531 ** maximum. In Gutman's notation:
136532 **
136533 **     m = M/3
136534 **
136535 ** If an R*-tree "Reinsert" operation is required, the same number of
136536 ** cells are removed from the overfull node and reinserted into the tree.
136537 */
136538 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
136539 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
136540 #define RTREE_MAXCELLS 51
136541
136542 /*
136543 ** The smallest possible node-size is (512-64)==448 bytes. And the largest
136544 ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
136545 ** Therefore all non-root nodes must contain at least 3 entries. Since 
136546 ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
136547 ** 40 or less.
136548 */
136549 #define RTREE_MAX_DEPTH 40
136550
136551 /* 
136552 ** An rtree cursor object.
136553 */
136554 struct RtreeCursor {
136555   sqlite3_vtab_cursor base;
136556   RtreeNode *pNode;                 /* Node cursor is currently pointing at */
136557   int iCell;                        /* Index of current cell in pNode */
136558   int iStrategy;                    /* Copy of idxNum search parameter */
136559   int nConstraint;                  /* Number of entries in aConstraint */
136560   RtreeConstraint *aConstraint;     /* Search constraints. */
136561 };
136562
136563 union RtreeCoord {
136564   RtreeValue f;
136565   int i;
136566 };
136567
136568 /*
136569 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
136570 ** formatted as a RtreeDValue (double or int64). This macro assumes that local
136571 ** variable pRtree points to the Rtree structure associated with the
136572 ** RtreeCoord.
136573 */
136574 #ifdef SQLITE_RTREE_INT_ONLY
136575 # define DCOORD(coord) ((RtreeDValue)coord.i)
136576 #else
136577 # define DCOORD(coord) (                           \
136578     (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
136579       ((double)coord.f) :                           \
136580       ((double)coord.i)                             \
136581   )
136582 #endif
136583
136584 /*
136585 ** A search constraint.
136586 */
136587 struct RtreeConstraint {
136588   int iCoord;                     /* Index of constrained coordinate */
136589   int op;                         /* Constraining operation */
136590   RtreeDValue rValue;             /* Constraint value. */
136591   int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
136592   sqlite3_rtree_geometry *pGeom;  /* Constraint callback argument for a MATCH */
136593 };
136594
136595 /* Possible values for RtreeConstraint.op */
136596 #define RTREE_EQ    0x41
136597 #define RTREE_LE    0x42
136598 #define RTREE_LT    0x43
136599 #define RTREE_GE    0x44
136600 #define RTREE_GT    0x45
136601 #define RTREE_MATCH 0x46
136602
136603 /* 
136604 ** An rtree structure node.
136605 */
136606 struct RtreeNode {
136607   RtreeNode *pParent;               /* Parent node */
136608   i64 iNode;
136609   int nRef;
136610   int isDirty;
136611   u8 *zData;
136612   RtreeNode *pNext;                 /* Next node in this hash chain */
136613 };
136614 #define NCELL(pNode) readInt16(&(pNode)->zData[2])
136615
136616 /* 
136617 ** Structure to store a deserialized rtree record.
136618 */
136619 struct RtreeCell {
136620   i64 iRowid;
136621   RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
136622 };
136623
136624
136625 /*
136626 ** Value for the first field of every RtreeMatchArg object. The MATCH
136627 ** operator tests that the first field of a blob operand matches this
136628 ** value to avoid operating on invalid blobs (which could cause a segfault).
136629 */
136630 #define RTREE_GEOMETRY_MAGIC 0x891245AB
136631
136632 /*
136633 ** An instance of this structure must be supplied as a blob argument to
136634 ** the right-hand-side of an SQL MATCH operator used to constrain an
136635 ** r-tree query.
136636 */
136637 struct RtreeMatchArg {
136638   u32 magic;                      /* Always RTREE_GEOMETRY_MAGIC */
136639   int (*xGeom)(sqlite3_rtree_geometry *, int, RtreeDValue*, int *);
136640   void *pContext;
136641   int nParam;
136642   RtreeDValue aParam[1];
136643 };
136644
136645 /*
136646 ** When a geometry callback is created (see sqlite3_rtree_geometry_callback),
136647 ** a single instance of the following structure is allocated. It is used
136648 ** as the context for the user-function created by by s_r_g_c(). The object
136649 ** is eventually deleted by the destructor mechanism provided by
136650 ** sqlite3_create_function_v2() (which is called by s_r_g_c() to create
136651 ** the geometry callback function).
136652 */
136653 struct RtreeGeomCallback {
136654   int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
136655   void *pContext;
136656 };
136657
136658 #ifndef MAX
136659 # define MAX(x,y) ((x) < (y) ? (y) : (x))
136660 #endif
136661 #ifndef MIN
136662 # define MIN(x,y) ((x) > (y) ? (y) : (x))
136663 #endif
136664
136665 /*
136666 ** Functions to deserialize a 16 bit integer, 32 bit real number and
136667 ** 64 bit integer. The deserialized value is returned.
136668 */
136669 static int readInt16(u8 *p){
136670   return (p[0]<<8) + p[1];
136671 }
136672 static void readCoord(u8 *p, RtreeCoord *pCoord){
136673   u32 i = (
136674     (((u32)p[0]) << 24) + 
136675     (((u32)p[1]) << 16) + 
136676     (((u32)p[2]) <<  8) + 
136677     (((u32)p[3]) <<  0)
136678   );
136679   *(u32 *)pCoord = i;
136680 }
136681 static i64 readInt64(u8 *p){
136682   return (
136683     (((i64)p[0]) << 56) + 
136684     (((i64)p[1]) << 48) + 
136685     (((i64)p[2]) << 40) + 
136686     (((i64)p[3]) << 32) + 
136687     (((i64)p[4]) << 24) + 
136688     (((i64)p[5]) << 16) + 
136689     (((i64)p[6]) <<  8) + 
136690     (((i64)p[7]) <<  0)
136691   );
136692 }
136693
136694 /*
136695 ** Functions to serialize a 16 bit integer, 32 bit real number and
136696 ** 64 bit integer. The value returned is the number of bytes written
136697 ** to the argument buffer (always 2, 4 and 8 respectively).
136698 */
136699 static int writeInt16(u8 *p, int i){
136700   p[0] = (i>> 8)&0xFF;
136701   p[1] = (i>> 0)&0xFF;
136702   return 2;
136703 }
136704 static int writeCoord(u8 *p, RtreeCoord *pCoord){
136705   u32 i;
136706   assert( sizeof(RtreeCoord)==4 );
136707   assert( sizeof(u32)==4 );
136708   i = *(u32 *)pCoord;
136709   p[0] = (i>>24)&0xFF;
136710   p[1] = (i>>16)&0xFF;
136711   p[2] = (i>> 8)&0xFF;
136712   p[3] = (i>> 0)&0xFF;
136713   return 4;
136714 }
136715 static int writeInt64(u8 *p, i64 i){
136716   p[0] = (i>>56)&0xFF;
136717   p[1] = (i>>48)&0xFF;
136718   p[2] = (i>>40)&0xFF;
136719   p[3] = (i>>32)&0xFF;
136720   p[4] = (i>>24)&0xFF;
136721   p[5] = (i>>16)&0xFF;
136722   p[6] = (i>> 8)&0xFF;
136723   p[7] = (i>> 0)&0xFF;
136724   return 8;
136725 }
136726
136727 /*
136728 ** Increment the reference count of node p.
136729 */
136730 static void nodeReference(RtreeNode *p){
136731   if( p ){
136732     p->nRef++;
136733   }
136734 }
136735
136736 /*
136737 ** Clear the content of node p (set all bytes to 0x00).
136738 */
136739 static void nodeZero(Rtree *pRtree, RtreeNode *p){
136740   memset(&p->zData[2], 0, pRtree->iNodeSize-2);
136741   p->isDirty = 1;
136742 }
136743
136744 /*
136745 ** Given a node number iNode, return the corresponding key to use
136746 ** in the Rtree.aHash table.
136747 */
136748 static int nodeHash(i64 iNode){
136749   return (
136750     (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^ 
136751     (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
136752   ) % HASHSIZE;
136753 }
136754
136755 /*
136756 ** Search the node hash table for node iNode. If found, return a pointer
136757 ** to it. Otherwise, return 0.
136758 */
136759 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
136760   RtreeNode *p;
136761   for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
136762   return p;
136763 }
136764
136765 /*
136766 ** Add node pNode to the node hash table.
136767 */
136768 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
136769   int iHash;
136770   assert( pNode->pNext==0 );
136771   iHash = nodeHash(pNode->iNode);
136772   pNode->pNext = pRtree->aHash[iHash];
136773   pRtree->aHash[iHash] = pNode;
136774 }
136775
136776 /*
136777 ** Remove node pNode from the node hash table.
136778 */
136779 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
136780   RtreeNode **pp;
136781   if( pNode->iNode!=0 ){
136782     pp = &pRtree->aHash[nodeHash(pNode->iNode)];
136783     for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
136784     *pp = pNode->pNext;
136785     pNode->pNext = 0;
136786   }
136787 }
136788
136789 /*
136790 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
136791 ** indicating that node has not yet been assigned a node number. It is
136792 ** assigned a node number when nodeWrite() is called to write the
136793 ** node contents out to the database.
136794 */
136795 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
136796   RtreeNode *pNode;
136797   pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
136798   if( pNode ){
136799     memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
136800     pNode->zData = (u8 *)&pNode[1];
136801     pNode->nRef = 1;
136802     pNode->pParent = pParent;
136803     pNode->isDirty = 1;
136804     nodeReference(pParent);
136805   }
136806   return pNode;
136807 }
136808
136809 /*
136810 ** Obtain a reference to an r-tree node.
136811 */
136812 static int
136813 nodeAcquire(
136814   Rtree *pRtree,             /* R-tree structure */
136815   i64 iNode,                 /* Node number to load */
136816   RtreeNode *pParent,        /* Either the parent node or NULL */
136817   RtreeNode **ppNode         /* OUT: Acquired node */
136818 ){
136819   int rc;
136820   int rc2 = SQLITE_OK;
136821   RtreeNode *pNode;
136822
136823   /* Check if the requested node is already in the hash table. If so,
136824   ** increase its reference count and return it.
136825   */
136826   if( (pNode = nodeHashLookup(pRtree, iNode)) ){
136827     assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
136828     if( pParent && !pNode->pParent ){
136829       nodeReference(pParent);
136830       pNode->pParent = pParent;
136831     }
136832     pNode->nRef++;
136833     *ppNode = pNode;
136834     return SQLITE_OK;
136835   }
136836
136837   sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
136838   rc = sqlite3_step(pRtree->pReadNode);
136839   if( rc==SQLITE_ROW ){
136840     const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
136841     if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
136842       pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
136843       if( !pNode ){
136844         rc2 = SQLITE_NOMEM;
136845       }else{
136846         pNode->pParent = pParent;
136847         pNode->zData = (u8 *)&pNode[1];
136848         pNode->nRef = 1;
136849         pNode->iNode = iNode;
136850         pNode->isDirty = 0;
136851         pNode->pNext = 0;
136852         memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
136853         nodeReference(pParent);
136854       }
136855     }
136856   }
136857   rc = sqlite3_reset(pRtree->pReadNode);
136858   if( rc==SQLITE_OK ) rc = rc2;
136859
136860   /* If the root node was just loaded, set pRtree->iDepth to the height
136861   ** of the r-tree structure. A height of zero means all data is stored on
136862   ** the root node. A height of one means the children of the root node
136863   ** are the leaves, and so on. If the depth as specified on the root node
136864   ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
136865   */
136866   if( pNode && iNode==1 ){
136867     pRtree->iDepth = readInt16(pNode->zData);
136868     if( pRtree->iDepth>RTREE_MAX_DEPTH ){
136869       rc = SQLITE_CORRUPT_VTAB;
136870     }
136871   }
136872
136873   /* If no error has occurred so far, check if the "number of entries"
136874   ** field on the node is too large. If so, set the return code to 
136875   ** SQLITE_CORRUPT_VTAB.
136876   */
136877   if( pNode && rc==SQLITE_OK ){
136878     if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
136879       rc = SQLITE_CORRUPT_VTAB;
136880     }
136881   }
136882
136883   if( rc==SQLITE_OK ){
136884     if( pNode!=0 ){
136885       nodeHashInsert(pRtree, pNode);
136886     }else{
136887       rc = SQLITE_CORRUPT_VTAB;
136888     }
136889     *ppNode = pNode;
136890   }else{
136891     sqlite3_free(pNode);
136892     *ppNode = 0;
136893   }
136894
136895   return rc;
136896 }
136897
136898 /*
136899 ** Overwrite cell iCell of node pNode with the contents of pCell.
136900 */
136901 static void nodeOverwriteCell(
136902   Rtree *pRtree, 
136903   RtreeNode *pNode,  
136904   RtreeCell *pCell, 
136905   int iCell
136906 ){
136907   int ii;
136908   u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
136909   p += writeInt64(p, pCell->iRowid);
136910   for(ii=0; ii<(pRtree->nDim*2); ii++){
136911     p += writeCoord(p, &pCell->aCoord[ii]);
136912   }
136913   pNode->isDirty = 1;
136914 }
136915
136916 /*
136917 ** Remove cell the cell with index iCell from node pNode.
136918 */
136919 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
136920   u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
136921   u8 *pSrc = &pDst[pRtree->nBytesPerCell];
136922   int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
136923   memmove(pDst, pSrc, nByte);
136924   writeInt16(&pNode->zData[2], NCELL(pNode)-1);
136925   pNode->isDirty = 1;
136926 }
136927
136928 /*
136929 ** Insert the contents of cell pCell into node pNode. If the insert
136930 ** is successful, return SQLITE_OK.
136931 **
136932 ** If there is not enough free space in pNode, return SQLITE_FULL.
136933 */
136934 static int
136935 nodeInsertCell(
136936   Rtree *pRtree, 
136937   RtreeNode *pNode, 
136938   RtreeCell *pCell 
136939 ){
136940   int nCell;                    /* Current number of cells in pNode */
136941   int nMaxCell;                 /* Maximum number of cells for pNode */
136942
136943   nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
136944   nCell = NCELL(pNode);
136945
136946   assert( nCell<=nMaxCell );
136947   if( nCell<nMaxCell ){
136948     nodeOverwriteCell(pRtree, pNode, pCell, nCell);
136949     writeInt16(&pNode->zData[2], nCell+1);
136950     pNode->isDirty = 1;
136951   }
136952
136953   return (nCell==nMaxCell);
136954 }
136955
136956 /*
136957 ** If the node is dirty, write it out to the database.
136958 */
136959 static int
136960 nodeWrite(Rtree *pRtree, RtreeNode *pNode){
136961   int rc = SQLITE_OK;
136962   if( pNode->isDirty ){
136963     sqlite3_stmt *p = pRtree->pWriteNode;
136964     if( pNode->iNode ){
136965       sqlite3_bind_int64(p, 1, pNode->iNode);
136966     }else{
136967       sqlite3_bind_null(p, 1);
136968     }
136969     sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
136970     sqlite3_step(p);
136971     pNode->isDirty = 0;
136972     rc = sqlite3_reset(p);
136973     if( pNode->iNode==0 && rc==SQLITE_OK ){
136974       pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
136975       nodeHashInsert(pRtree, pNode);
136976     }
136977   }
136978   return rc;
136979 }
136980
136981 /*
136982 ** Release a reference to a node. If the node is dirty and the reference
136983 ** count drops to zero, the node data is written to the database.
136984 */
136985 static int
136986 nodeRelease(Rtree *pRtree, RtreeNode *pNode){
136987   int rc = SQLITE_OK;
136988   if( pNode ){
136989     assert( pNode->nRef>0 );
136990     pNode->nRef--;
136991     if( pNode->nRef==0 ){
136992       if( pNode->iNode==1 ){
136993         pRtree->iDepth = -1;
136994       }
136995       if( pNode->pParent ){
136996         rc = nodeRelease(pRtree, pNode->pParent);
136997       }
136998       if( rc==SQLITE_OK ){
136999         rc = nodeWrite(pRtree, pNode);
137000       }
137001       nodeHashDelete(pRtree, pNode);
137002       sqlite3_free(pNode);
137003     }
137004   }
137005   return rc;
137006 }
137007
137008 /*
137009 ** Return the 64-bit integer value associated with cell iCell of
137010 ** node pNode. If pNode is a leaf node, this is a rowid. If it is
137011 ** an internal node, then the 64-bit integer is a child page number.
137012 */
137013 static i64 nodeGetRowid(
137014   Rtree *pRtree, 
137015   RtreeNode *pNode, 
137016   int iCell
137017 ){
137018   assert( iCell<NCELL(pNode) );
137019   return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
137020 }
137021
137022 /*
137023 ** Return coordinate iCoord from cell iCell in node pNode.
137024 */
137025 static void nodeGetCoord(
137026   Rtree *pRtree, 
137027   RtreeNode *pNode, 
137028   int iCell,
137029   int iCoord,
137030   RtreeCoord *pCoord           /* Space to write result to */
137031 ){
137032   readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
137033 }
137034
137035 /*
137036 ** Deserialize cell iCell of node pNode. Populate the structure pointed
137037 ** to by pCell with the results.
137038 */
137039 static void nodeGetCell(
137040   Rtree *pRtree, 
137041   RtreeNode *pNode, 
137042   int iCell,
137043   RtreeCell *pCell
137044 ){
137045   int ii;
137046   pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
137047   for(ii=0; ii<pRtree->nDim*2; ii++){
137048     nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
137049   }
137050 }
137051
137052
137053 /* Forward declaration for the function that does the work of
137054 ** the virtual table module xCreate() and xConnect() methods.
137055 */
137056 static int rtreeInit(
137057   sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
137058 );
137059
137060 /* 
137061 ** Rtree virtual table module xCreate method.
137062 */
137063 static int rtreeCreate(
137064   sqlite3 *db,
137065   void *pAux,
137066   int argc, const char *const*argv,
137067   sqlite3_vtab **ppVtab,
137068   char **pzErr
137069 ){
137070   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
137071 }
137072
137073 /* 
137074 ** Rtree virtual table module xConnect method.
137075 */
137076 static int rtreeConnect(
137077   sqlite3 *db,
137078   void *pAux,
137079   int argc, const char *const*argv,
137080   sqlite3_vtab **ppVtab,
137081   char **pzErr
137082 ){
137083   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
137084 }
137085
137086 /*
137087 ** Increment the r-tree reference count.
137088 */
137089 static void rtreeReference(Rtree *pRtree){
137090   pRtree->nBusy++;
137091 }
137092
137093 /*
137094 ** Decrement the r-tree reference count. When the reference count reaches
137095 ** zero the structure is deleted.
137096 */
137097 static void rtreeRelease(Rtree *pRtree){
137098   pRtree->nBusy--;
137099   if( pRtree->nBusy==0 ){
137100     sqlite3_finalize(pRtree->pReadNode);
137101     sqlite3_finalize(pRtree->pWriteNode);
137102     sqlite3_finalize(pRtree->pDeleteNode);
137103     sqlite3_finalize(pRtree->pReadRowid);
137104     sqlite3_finalize(pRtree->pWriteRowid);
137105     sqlite3_finalize(pRtree->pDeleteRowid);
137106     sqlite3_finalize(pRtree->pReadParent);
137107     sqlite3_finalize(pRtree->pWriteParent);
137108     sqlite3_finalize(pRtree->pDeleteParent);
137109     sqlite3_free(pRtree);
137110   }
137111 }
137112
137113 /* 
137114 ** Rtree virtual table module xDisconnect method.
137115 */
137116 static int rtreeDisconnect(sqlite3_vtab *pVtab){
137117   rtreeRelease((Rtree *)pVtab);
137118   return SQLITE_OK;
137119 }
137120
137121 /* 
137122 ** Rtree virtual table module xDestroy method.
137123 */
137124 static int rtreeDestroy(sqlite3_vtab *pVtab){
137125   Rtree *pRtree = (Rtree *)pVtab;
137126   int rc;
137127   char *zCreate = sqlite3_mprintf(
137128     "DROP TABLE '%q'.'%q_node';"
137129     "DROP TABLE '%q'.'%q_rowid';"
137130     "DROP TABLE '%q'.'%q_parent';",
137131     pRtree->zDb, pRtree->zName, 
137132     pRtree->zDb, pRtree->zName,
137133     pRtree->zDb, pRtree->zName
137134   );
137135   if( !zCreate ){
137136     rc = SQLITE_NOMEM;
137137   }else{
137138     rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
137139     sqlite3_free(zCreate);
137140   }
137141   if( rc==SQLITE_OK ){
137142     rtreeRelease(pRtree);
137143   }
137144
137145   return rc;
137146 }
137147
137148 /* 
137149 ** Rtree virtual table module xOpen method.
137150 */
137151 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
137152   int rc = SQLITE_NOMEM;
137153   RtreeCursor *pCsr;
137154
137155   pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
137156   if( pCsr ){
137157     memset(pCsr, 0, sizeof(RtreeCursor));
137158     pCsr->base.pVtab = pVTab;
137159     rc = SQLITE_OK;
137160   }
137161   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
137162
137163   return rc;
137164 }
137165
137166
137167 /*
137168 ** Free the RtreeCursor.aConstraint[] array and its contents.
137169 */
137170 static void freeCursorConstraints(RtreeCursor *pCsr){
137171   if( pCsr->aConstraint ){
137172     int i;                        /* Used to iterate through constraint array */
137173     for(i=0; i<pCsr->nConstraint; i++){
137174       sqlite3_rtree_geometry *pGeom = pCsr->aConstraint[i].pGeom;
137175       if( pGeom ){
137176         if( pGeom->xDelUser ) pGeom->xDelUser(pGeom->pUser);
137177         sqlite3_free(pGeom);
137178       }
137179     }
137180     sqlite3_free(pCsr->aConstraint);
137181     pCsr->aConstraint = 0;
137182   }
137183 }
137184
137185 /* 
137186 ** Rtree virtual table module xClose method.
137187 */
137188 static int rtreeClose(sqlite3_vtab_cursor *cur){
137189   Rtree *pRtree = (Rtree *)(cur->pVtab);
137190   int rc;
137191   RtreeCursor *pCsr = (RtreeCursor *)cur;
137192   freeCursorConstraints(pCsr);
137193   rc = nodeRelease(pRtree, pCsr->pNode);
137194   sqlite3_free(pCsr);
137195   return rc;
137196 }
137197
137198 /*
137199 ** Rtree virtual table module xEof method.
137200 **
137201 ** Return non-zero if the cursor does not currently point to a valid 
137202 ** record (i.e if the scan has finished), or zero otherwise.
137203 */
137204 static int rtreeEof(sqlite3_vtab_cursor *cur){
137205   RtreeCursor *pCsr = (RtreeCursor *)cur;
137206   return (pCsr->pNode==0);
137207 }
137208
137209 /*
137210 ** The r-tree constraint passed as the second argument to this function is
137211 ** guaranteed to be a MATCH constraint.
137212 */
137213 static int testRtreeGeom(
137214   Rtree *pRtree,                  /* R-Tree object */
137215   RtreeConstraint *pConstraint,   /* MATCH constraint to test */
137216   RtreeCell *pCell,               /* Cell to test */
137217   int *pbRes                      /* OUT: Test result */
137218 ){
137219   int i;
137220   RtreeDValue aCoord[RTREE_MAX_DIMENSIONS*2];
137221   int nCoord = pRtree->nDim*2;
137222
137223   assert( pConstraint->op==RTREE_MATCH );
137224   assert( pConstraint->pGeom );
137225
137226   for(i=0; i<nCoord; i++){
137227     aCoord[i] = DCOORD(pCell->aCoord[i]);
137228   }
137229   return pConstraint->xGeom(pConstraint->pGeom, nCoord, aCoord, pbRes);
137230 }
137231
137232 /* 
137233 ** Cursor pCursor currently points to a cell in a non-leaf page.
137234 ** Set *pbEof to true if the sub-tree headed by the cell is filtered
137235 ** (excluded) by the constraints in the pCursor->aConstraint[] 
137236 ** array, or false otherwise.
137237 **
137238 ** Return SQLITE_OK if successful or an SQLite error code if an error
137239 ** occurs within a geometry callback.
137240 */
137241 static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
137242   RtreeCell cell;
137243   int ii;
137244   int bRes = 0;
137245   int rc = SQLITE_OK;
137246
137247   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
137248   for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
137249     RtreeConstraint *p = &pCursor->aConstraint[ii];
137250     RtreeDValue cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
137251     RtreeDValue cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
137252
137253     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
137254         || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
137255     );
137256
137257     switch( p->op ){
137258       case RTREE_LE: case RTREE_LT: 
137259         bRes = p->rValue<cell_min; 
137260         break;
137261
137262       case RTREE_GE: case RTREE_GT: 
137263         bRes = p->rValue>cell_max; 
137264         break;
137265
137266       case RTREE_EQ:
137267         bRes = (p->rValue>cell_max || p->rValue<cell_min);
137268         break;
137269
137270       default: {
137271         assert( p->op==RTREE_MATCH );
137272         rc = testRtreeGeom(pRtree, p, &cell, &bRes);
137273         bRes = !bRes;
137274         break;
137275       }
137276     }
137277   }
137278
137279   *pbEof = bRes;
137280   return rc;
137281 }
137282
137283 /* 
137284 ** Test if the cell that cursor pCursor currently points to
137285 ** would be filtered (excluded) by the constraints in the 
137286 ** pCursor->aConstraint[] array. If so, set *pbEof to true before
137287 ** returning. If the cell is not filtered (excluded) by the constraints,
137288 ** set pbEof to zero.
137289 **
137290 ** Return SQLITE_OK if successful or an SQLite error code if an error
137291 ** occurs within a geometry callback.
137292 **
137293 ** This function assumes that the cell is part of a leaf node.
137294 */
137295 static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
137296   RtreeCell cell;
137297   int ii;
137298   *pbEof = 0;
137299
137300   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
137301   for(ii=0; ii<pCursor->nConstraint; ii++){
137302     RtreeConstraint *p = &pCursor->aConstraint[ii];
137303     RtreeDValue coord = DCOORD(cell.aCoord[p->iCoord]);
137304     int res;
137305     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
137306         || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
137307     );
137308     switch( p->op ){
137309       case RTREE_LE: res = (coord<=p->rValue); break;
137310       case RTREE_LT: res = (coord<p->rValue);  break;
137311       case RTREE_GE: res = (coord>=p->rValue); break;
137312       case RTREE_GT: res = (coord>p->rValue);  break;
137313       case RTREE_EQ: res = (coord==p->rValue); break;
137314       default: {
137315         int rc;
137316         assert( p->op==RTREE_MATCH );
137317         rc = testRtreeGeom(pRtree, p, &cell, &res);
137318         if( rc!=SQLITE_OK ){
137319           return rc;
137320         }
137321         break;
137322       }
137323     }
137324
137325     if( !res ){
137326       *pbEof = 1;
137327       return SQLITE_OK;
137328     }
137329   }
137330
137331   return SQLITE_OK;
137332 }
137333
137334 /*
137335 ** Cursor pCursor currently points at a node that heads a sub-tree of
137336 ** height iHeight (if iHeight==0, then the node is a leaf). Descend
137337 ** to point to the left-most cell of the sub-tree that matches the 
137338 ** configured constraints.
137339 */
137340 static int descendToCell(
137341   Rtree *pRtree, 
137342   RtreeCursor *pCursor, 
137343   int iHeight,
137344   int *pEof                 /* OUT: Set to true if cannot descend */
137345 ){
137346   int isEof;
137347   int rc;
137348   int ii;
137349   RtreeNode *pChild;
137350   sqlite3_int64 iRowid;
137351
137352   RtreeNode *pSavedNode = pCursor->pNode;
137353   int iSavedCell = pCursor->iCell;
137354
137355   assert( iHeight>=0 );
137356
137357   if( iHeight==0 ){
137358     rc = testRtreeEntry(pRtree, pCursor, &isEof);
137359   }else{
137360     rc = testRtreeCell(pRtree, pCursor, &isEof);
137361   }
137362   if( rc!=SQLITE_OK || isEof || iHeight==0 ){
137363     goto descend_to_cell_out;
137364   }
137365
137366   iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
137367   rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
137368   if( rc!=SQLITE_OK ){
137369     goto descend_to_cell_out;
137370   }
137371
137372   nodeRelease(pRtree, pCursor->pNode);
137373   pCursor->pNode = pChild;
137374   isEof = 1;
137375   for(ii=0; isEof && ii<NCELL(pChild); ii++){
137376     pCursor->iCell = ii;
137377     rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
137378     if( rc!=SQLITE_OK ){
137379       goto descend_to_cell_out;
137380     }
137381   }
137382
137383   if( isEof ){
137384     assert( pCursor->pNode==pChild );
137385     nodeReference(pSavedNode);
137386     nodeRelease(pRtree, pChild);
137387     pCursor->pNode = pSavedNode;
137388     pCursor->iCell = iSavedCell;
137389   }
137390
137391 descend_to_cell_out:
137392   *pEof = isEof;
137393   return rc;
137394 }
137395
137396 /*
137397 ** One of the cells in node pNode is guaranteed to have a 64-bit 
137398 ** integer value equal to iRowid. Return the index of this cell.
137399 */
137400 static int nodeRowidIndex(
137401   Rtree *pRtree, 
137402   RtreeNode *pNode, 
137403   i64 iRowid,
137404   int *piIndex
137405 ){
137406   int ii;
137407   int nCell = NCELL(pNode);
137408   for(ii=0; ii<nCell; ii++){
137409     if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
137410       *piIndex = ii;
137411       return SQLITE_OK;
137412     }
137413   }
137414   return SQLITE_CORRUPT_VTAB;
137415 }
137416
137417 /*
137418 ** Return the index of the cell containing a pointer to node pNode
137419 ** in its parent. If pNode is the root node, return -1.
137420 */
137421 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
137422   RtreeNode *pParent = pNode->pParent;
137423   if( pParent ){
137424     return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
137425   }
137426   *piIndex = -1;
137427   return SQLITE_OK;
137428 }
137429
137430 /* 
137431 ** Rtree virtual table module xNext method.
137432 */
137433 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
137434   Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
137435   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
137436   int rc = SQLITE_OK;
137437
137438   /* RtreeCursor.pNode must not be NULL. If is is NULL, then this cursor is
137439   ** already at EOF. It is against the rules to call the xNext() method of
137440   ** a cursor that has already reached EOF.
137441   */
137442   assert( pCsr->pNode );
137443
137444   if( pCsr->iStrategy==1 ){
137445     /* This "scan" is a direct lookup by rowid. There is no next entry. */
137446     nodeRelease(pRtree, pCsr->pNode);
137447     pCsr->pNode = 0;
137448   }else{
137449     /* Move to the next entry that matches the configured constraints. */
137450     int iHeight = 0;
137451     while( pCsr->pNode ){
137452       RtreeNode *pNode = pCsr->pNode;
137453       int nCell = NCELL(pNode);
137454       for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
137455         int isEof;
137456         rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
137457         if( rc!=SQLITE_OK || !isEof ){
137458           return rc;
137459         }
137460       }
137461       pCsr->pNode = pNode->pParent;
137462       rc = nodeParentIndex(pRtree, pNode, &pCsr->iCell);
137463       if( rc!=SQLITE_OK ){
137464         return rc;
137465       }
137466       nodeReference(pCsr->pNode);
137467       nodeRelease(pRtree, pNode);
137468       iHeight++;
137469     }
137470   }
137471
137472   return rc;
137473 }
137474
137475 /* 
137476 ** Rtree virtual table module xRowid method.
137477 */
137478 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
137479   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
137480   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
137481
137482   assert(pCsr->pNode);
137483   *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
137484
137485   return SQLITE_OK;
137486 }
137487
137488 /* 
137489 ** Rtree virtual table module xColumn method.
137490 */
137491 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
137492   Rtree *pRtree = (Rtree *)cur->pVtab;
137493   RtreeCursor *pCsr = (RtreeCursor *)cur;
137494
137495   if( i==0 ){
137496     i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
137497     sqlite3_result_int64(ctx, iRowid);
137498   }else{
137499     RtreeCoord c;
137500     nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
137501 #ifndef SQLITE_RTREE_INT_ONLY
137502     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
137503       sqlite3_result_double(ctx, c.f);
137504     }else
137505 #endif
137506     {
137507       assert( pRtree->eCoordType==RTREE_COORD_INT32 );
137508       sqlite3_result_int(ctx, c.i);
137509     }
137510   }
137511
137512   return SQLITE_OK;
137513 }
137514
137515 /* 
137516 ** Use nodeAcquire() to obtain the leaf node containing the record with 
137517 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
137518 ** return SQLITE_OK. If there is no such record in the table, set
137519 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
137520 ** to zero and return an SQLite error code.
137521 */
137522 static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
137523   int rc;
137524   *ppLeaf = 0;
137525   sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
137526   if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
137527     i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
137528     rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
137529     sqlite3_reset(pRtree->pReadRowid);
137530   }else{
137531     rc = sqlite3_reset(pRtree->pReadRowid);
137532   }
137533   return rc;
137534 }
137535
137536 /*
137537 ** This function is called to configure the RtreeConstraint object passed
137538 ** as the second argument for a MATCH constraint. The value passed as the
137539 ** first argument to this function is the right-hand operand to the MATCH
137540 ** operator.
137541 */
137542 static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
137543   RtreeMatchArg *p;
137544   sqlite3_rtree_geometry *pGeom;
137545   int nBlob;
137546
137547   /* Check that value is actually a blob. */
137548   if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR;
137549
137550   /* Check that the blob is roughly the right size. */
137551   nBlob = sqlite3_value_bytes(pValue);
137552   if( nBlob<(int)sizeof(RtreeMatchArg) 
137553    || ((nBlob-sizeof(RtreeMatchArg))%sizeof(RtreeDValue))!=0
137554   ){
137555     return SQLITE_ERROR;
137556   }
137557
137558   pGeom = (sqlite3_rtree_geometry *)sqlite3_malloc(
137559       sizeof(sqlite3_rtree_geometry) + nBlob
137560   );
137561   if( !pGeom ) return SQLITE_NOMEM;
137562   memset(pGeom, 0, sizeof(sqlite3_rtree_geometry));
137563   p = (RtreeMatchArg *)&pGeom[1];
137564
137565   memcpy(p, sqlite3_value_blob(pValue), nBlob);
137566   if( p->magic!=RTREE_GEOMETRY_MAGIC 
137567    || nBlob!=(int)(sizeof(RtreeMatchArg) + (p->nParam-1)*sizeof(RtreeDValue))
137568   ){
137569     sqlite3_free(pGeom);
137570     return SQLITE_ERROR;
137571   }
137572
137573   pGeom->pContext = p->pContext;
137574   pGeom->nParam = p->nParam;
137575   pGeom->aParam = p->aParam;
137576
137577   pCons->xGeom = p->xGeom;
137578   pCons->pGeom = pGeom;
137579   return SQLITE_OK;
137580 }
137581
137582 /* 
137583 ** Rtree virtual table module xFilter method.
137584 */
137585 static int rtreeFilter(
137586   sqlite3_vtab_cursor *pVtabCursor, 
137587   int idxNum, const char *idxStr,
137588   int argc, sqlite3_value **argv
137589 ){
137590   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
137591   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
137592
137593   RtreeNode *pRoot = 0;
137594   int ii;
137595   int rc = SQLITE_OK;
137596
137597   rtreeReference(pRtree);
137598
137599   freeCursorConstraints(pCsr);
137600   pCsr->iStrategy = idxNum;
137601
137602   if( idxNum==1 ){
137603     /* Special case - lookup by rowid. */
137604     RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
137605     i64 iRowid = sqlite3_value_int64(argv[0]);
137606     rc = findLeafNode(pRtree, iRowid, &pLeaf);
137607     pCsr->pNode = pLeaf; 
137608     if( pLeaf ){
137609       assert( rc==SQLITE_OK );
137610       rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &pCsr->iCell);
137611     }
137612   }else{
137613     /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array 
137614     ** with the configured constraints. 
137615     */
137616     if( argc>0 ){
137617       pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
137618       pCsr->nConstraint = argc;
137619       if( !pCsr->aConstraint ){
137620         rc = SQLITE_NOMEM;
137621       }else{
137622         memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
137623         assert( (idxStr==0 && argc==0)
137624                 || (idxStr && (int)strlen(idxStr)==argc*2) );
137625         for(ii=0; ii<argc; ii++){
137626           RtreeConstraint *p = &pCsr->aConstraint[ii];
137627           p->op = idxStr[ii*2];
137628           p->iCoord = idxStr[ii*2+1]-'a';
137629           if( p->op==RTREE_MATCH ){
137630             /* A MATCH operator. The right-hand-side must be a blob that
137631             ** can be cast into an RtreeMatchArg object. One created using
137632             ** an sqlite3_rtree_geometry_callback() SQL user function.
137633             */
137634             rc = deserializeGeometry(argv[ii], p);
137635             if( rc!=SQLITE_OK ){
137636               break;
137637             }
137638           }else{
137639 #ifdef SQLITE_RTREE_INT_ONLY
137640             p->rValue = sqlite3_value_int64(argv[ii]);
137641 #else
137642             p->rValue = sqlite3_value_double(argv[ii]);
137643 #endif
137644           }
137645         }
137646       }
137647     }
137648   
137649     if( rc==SQLITE_OK ){
137650       pCsr->pNode = 0;
137651       rc = nodeAcquire(pRtree, 1, 0, &pRoot);
137652     }
137653     if( rc==SQLITE_OK ){
137654       int isEof = 1;
137655       int nCell = NCELL(pRoot);
137656       pCsr->pNode = pRoot;
137657       for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
137658         assert( pCsr->pNode==pRoot );
137659         rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
137660         if( !isEof ){
137661           break;
137662         }
137663       }
137664       if( rc==SQLITE_OK && isEof ){
137665         assert( pCsr->pNode==pRoot );
137666         nodeRelease(pRtree, pRoot);
137667         pCsr->pNode = 0;
137668       }
137669       assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
137670     }
137671   }
137672
137673   rtreeRelease(pRtree);
137674   return rc;
137675 }
137676
137677 /*
137678 ** Rtree virtual table module xBestIndex method. There are three
137679 ** table scan strategies to choose from (in order from most to 
137680 ** least desirable):
137681 **
137682 **   idxNum     idxStr        Strategy
137683 **   ------------------------------------------------
137684 **     1        Unused        Direct lookup by rowid.
137685 **     2        See below     R-tree query or full-table scan.
137686 **   ------------------------------------------------
137687 **
137688 ** If strategy 1 is used, then idxStr is not meaningful. If strategy
137689 ** 2 is used, idxStr is formatted to contain 2 bytes for each 
137690 ** constraint used. The first two bytes of idxStr correspond to 
137691 ** the constraint in sqlite3_index_info.aConstraintUsage[] with
137692 ** (argvIndex==1) etc.
137693 **
137694 ** The first of each pair of bytes in idxStr identifies the constraint
137695 ** operator as follows:
137696 **
137697 **   Operator    Byte Value
137698 **   ----------------------
137699 **      =        0x41 ('A')
137700 **     <=        0x42 ('B')
137701 **      <        0x43 ('C')
137702 **     >=        0x44 ('D')
137703 **      >        0x45 ('E')
137704 **   MATCH       0x46 ('F')
137705 **   ----------------------
137706 **
137707 ** The second of each pair of bytes identifies the coordinate column
137708 ** to which the constraint applies. The leftmost coordinate column
137709 ** is 'a', the second from the left 'b' etc.
137710 */
137711 static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
137712   int rc = SQLITE_OK;
137713   int ii;
137714
137715   int iIdx = 0;
137716   char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
137717   memset(zIdxStr, 0, sizeof(zIdxStr));
137718   UNUSED_PARAMETER(tab);
137719
137720   assert( pIdxInfo->idxStr==0 );
137721   for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
137722     struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
137723
137724     if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
137725       /* We have an equality constraint on the rowid. Use strategy 1. */
137726       int jj;
137727       for(jj=0; jj<ii; jj++){
137728         pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
137729         pIdxInfo->aConstraintUsage[jj].omit = 0;
137730       }
137731       pIdxInfo->idxNum = 1;
137732       pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
137733       pIdxInfo->aConstraintUsage[jj].omit = 1;
137734
137735       /* This strategy involves a two rowid lookups on an B-Tree structures
137736       ** and then a linear search of an R-Tree node. This should be 
137737       ** considered almost as quick as a direct rowid lookup (for which 
137738       ** sqlite uses an internal cost of 0.0).
137739       */ 
137740       pIdxInfo->estimatedCost = 10.0;
137741       return SQLITE_OK;
137742     }
137743
137744     if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
137745       u8 op;
137746       switch( p->op ){
137747         case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
137748         case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
137749         case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
137750         case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
137751         case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
137752         default:
137753           assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
137754           op = RTREE_MATCH; 
137755           break;
137756       }
137757       zIdxStr[iIdx++] = op;
137758       zIdxStr[iIdx++] = p->iColumn - 1 + 'a';
137759       pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
137760       pIdxInfo->aConstraintUsage[ii].omit = 1;
137761     }
137762   }
137763
137764   pIdxInfo->idxNum = 2;
137765   pIdxInfo->needToFreeIdxStr = 1;
137766   if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
137767     return SQLITE_NOMEM;
137768   }
137769   assert( iIdx>=0 );
137770   pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
137771   return rc;
137772 }
137773
137774 /*
137775 ** Return the N-dimensional volumn of the cell stored in *p.
137776 */
137777 static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
137778   RtreeDValue area = (RtreeDValue)1;
137779   int ii;
137780   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
137781     area = (area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));
137782   }
137783   return area;
137784 }
137785
137786 /*
137787 ** Return the margin length of cell p. The margin length is the sum
137788 ** of the objects size in each dimension.
137789 */
137790 static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
137791   RtreeDValue margin = (RtreeDValue)0;
137792   int ii;
137793   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
137794     margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
137795   }
137796   return margin;
137797 }
137798
137799 /*
137800 ** Store the union of cells p1 and p2 in p1.
137801 */
137802 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
137803   int ii;
137804   if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
137805     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
137806       p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
137807       p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
137808     }
137809   }else{
137810     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
137811       p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
137812       p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
137813     }
137814   }
137815 }
137816
137817 /*
137818 ** Return true if the area covered by p2 is a subset of the area covered
137819 ** by p1. False otherwise.
137820 */
137821 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
137822   int ii;
137823   int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
137824   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
137825     RtreeCoord *a1 = &p1->aCoord[ii];
137826     RtreeCoord *a2 = &p2->aCoord[ii];
137827     if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f)) 
137828      || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i)) 
137829     ){
137830       return 0;
137831     }
137832   }
137833   return 1;
137834 }
137835
137836 /*
137837 ** Return the amount cell p would grow by if it were unioned with pCell.
137838 */
137839 static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
137840   RtreeDValue area;
137841   RtreeCell cell;
137842   memcpy(&cell, p, sizeof(RtreeCell));
137843   area = cellArea(pRtree, &cell);
137844   cellUnion(pRtree, &cell, pCell);
137845   return (cellArea(pRtree, &cell)-area);
137846 }
137847
137848 #if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
137849 static RtreeDValue cellOverlap(
137850   Rtree *pRtree, 
137851   RtreeCell *p, 
137852   RtreeCell *aCell, 
137853   int nCell, 
137854   int iExclude
137855 ){
137856   int ii;
137857   RtreeDValue overlap = 0.0;
137858   for(ii=0; ii<nCell; ii++){
137859 #if VARIANT_RSTARTREE_CHOOSESUBTREE
137860     if( ii!=iExclude )
137861 #else
137862     assert( iExclude==-1 );
137863     UNUSED_PARAMETER(iExclude);
137864 #endif
137865     {
137866       int jj;
137867       RtreeDValue o = (RtreeDValue)1;
137868       for(jj=0; jj<(pRtree->nDim*2); jj+=2){
137869         RtreeDValue x1, x2;
137870
137871         x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
137872         x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
137873
137874         if( x2<x1 ){
137875           o = 0.0;
137876           break;
137877         }else{
137878           o = o * (x2-x1);
137879         }
137880       }
137881       overlap += o;
137882     }
137883   }
137884   return overlap;
137885 }
137886 #endif
137887
137888 #if VARIANT_RSTARTREE_CHOOSESUBTREE
137889 static RtreeDValue cellOverlapEnlargement(
137890   Rtree *pRtree, 
137891   RtreeCell *p, 
137892   RtreeCell *pInsert, 
137893   RtreeCell *aCell, 
137894   int nCell, 
137895   int iExclude
137896 ){
137897   RtreeDValue before, after;
137898   before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
137899   cellUnion(pRtree, p, pInsert);
137900   after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
137901   return (after-before);
137902 }
137903 #endif
137904
137905
137906 /*
137907 ** This function implements the ChooseLeaf algorithm from Gutman[84].
137908 ** ChooseSubTree in r*tree terminology.
137909 */
137910 static int ChooseLeaf(
137911   Rtree *pRtree,               /* Rtree table */
137912   RtreeCell *pCell,            /* Cell to insert into rtree */
137913   int iHeight,                 /* Height of sub-tree rooted at pCell */
137914   RtreeNode **ppLeaf           /* OUT: Selected leaf page */
137915 ){
137916   int rc;
137917   int ii;
137918   RtreeNode *pNode;
137919   rc = nodeAcquire(pRtree, 1, 0, &pNode);
137920
137921   for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
137922     int iCell;
137923     sqlite3_int64 iBest = 0;
137924
137925     RtreeDValue fMinGrowth = 0.0;
137926     RtreeDValue fMinArea = 0.0;
137927 #if VARIANT_RSTARTREE_CHOOSESUBTREE
137928     RtreeDValue fMinOverlap = 0.0;
137929     RtreeDValue overlap;
137930 #endif
137931
137932     int nCell = NCELL(pNode);
137933     RtreeCell cell;
137934     RtreeNode *pChild;
137935
137936     RtreeCell *aCell = 0;
137937
137938 #if VARIANT_RSTARTREE_CHOOSESUBTREE
137939     if( ii==(pRtree->iDepth-1) ){
137940       int jj;
137941       aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
137942       if( !aCell ){
137943         rc = SQLITE_NOMEM;
137944         nodeRelease(pRtree, pNode);
137945         pNode = 0;
137946         continue;
137947       }
137948       for(jj=0; jj<nCell; jj++){
137949         nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
137950       }
137951     }
137952 #endif
137953
137954     /* Select the child node which will be enlarged the least if pCell
137955     ** is inserted into it. Resolve ties by choosing the entry with
137956     ** the smallest area.
137957     */
137958     for(iCell=0; iCell<nCell; iCell++){
137959       int bBest = 0;
137960       RtreeDValue growth;
137961       RtreeDValue area;
137962       nodeGetCell(pRtree, pNode, iCell, &cell);
137963       growth = cellGrowth(pRtree, &cell, pCell);
137964       area = cellArea(pRtree, &cell);
137965
137966 #if VARIANT_RSTARTREE_CHOOSESUBTREE
137967       if( ii==(pRtree->iDepth-1) ){
137968         overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
137969       }else{
137970         overlap = 0.0;
137971       }
137972       if( (iCell==0) 
137973        || (overlap<fMinOverlap) 
137974        || (overlap==fMinOverlap && growth<fMinGrowth)
137975        || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
137976       ){
137977         bBest = 1;
137978         fMinOverlap = overlap;
137979       }
137980 #else
137981       if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
137982         bBest = 1;
137983       }
137984 #endif
137985       if( bBest ){
137986         fMinGrowth = growth;
137987         fMinArea = area;
137988         iBest = cell.iRowid;
137989       }
137990     }
137991
137992     sqlite3_free(aCell);
137993     rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
137994     nodeRelease(pRtree, pNode);
137995     pNode = pChild;
137996   }
137997
137998   *ppLeaf = pNode;
137999   return rc;
138000 }
138001
138002 /*
138003 ** A cell with the same content as pCell has just been inserted into
138004 ** the node pNode. This function updates the bounding box cells in
138005 ** all ancestor elements.
138006 */
138007 static int AdjustTree(
138008   Rtree *pRtree,                    /* Rtree table */
138009   RtreeNode *pNode,                 /* Adjust ancestry of this node. */
138010   RtreeCell *pCell                  /* This cell was just inserted */
138011 ){
138012   RtreeNode *p = pNode;
138013   while( p->pParent ){
138014     RtreeNode *pParent = p->pParent;
138015     RtreeCell cell;
138016     int iCell;
138017
138018     if( nodeParentIndex(pRtree, p, &iCell) ){
138019       return SQLITE_CORRUPT_VTAB;
138020     }
138021
138022     nodeGetCell(pRtree, pParent, iCell, &cell);
138023     if( !cellContains(pRtree, &cell, pCell) ){
138024       cellUnion(pRtree, &cell, pCell);
138025       nodeOverwriteCell(pRtree, pParent, &cell, iCell);
138026     }
138027  
138028     p = pParent;
138029   }
138030   return SQLITE_OK;
138031 }
138032
138033 /*
138034 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
138035 */
138036 static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
138037   sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
138038   sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
138039   sqlite3_step(pRtree->pWriteRowid);
138040   return sqlite3_reset(pRtree->pWriteRowid);
138041 }
138042
138043 /*
138044 ** Write mapping (iNode->iPar) to the <rtree>_parent table.
138045 */
138046 static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
138047   sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
138048   sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
138049   sqlite3_step(pRtree->pWriteParent);
138050   return sqlite3_reset(pRtree->pWriteParent);
138051 }
138052
138053 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
138054
138055 #if VARIANT_GUTTMAN_LINEAR_SPLIT
138056 /*
138057 ** Implementation of the linear variant of the PickNext() function from
138058 ** Guttman[84].
138059 */
138060 static RtreeCell *LinearPickNext(
138061   Rtree *pRtree,
138062   RtreeCell *aCell, 
138063   int nCell, 
138064   RtreeCell *pLeftBox, 
138065   RtreeCell *pRightBox,
138066   int *aiUsed
138067 ){
138068   int ii;
138069   for(ii=0; aiUsed[ii]; ii++);
138070   aiUsed[ii] = 1;
138071   return &aCell[ii];
138072 }
138073
138074 /*
138075 ** Implementation of the linear variant of the PickSeeds() function from
138076 ** Guttman[84].
138077 */
138078 static void LinearPickSeeds(
138079   Rtree *pRtree,
138080   RtreeCell *aCell, 
138081   int nCell, 
138082   int *piLeftSeed, 
138083   int *piRightSeed
138084 ){
138085   int i;
138086   int iLeftSeed = 0;
138087   int iRightSeed = 1;
138088   RtreeDValue maxNormalInnerWidth = (RtreeDValue)0;
138089
138090   /* Pick two "seed" cells from the array of cells. The algorithm used
138091   ** here is the LinearPickSeeds algorithm from Gutman[1984]. The 
138092   ** indices of the two seed cells in the array are stored in local
138093   ** variables iLeftSeek and iRightSeed.
138094   */
138095   for(i=0; i<pRtree->nDim; i++){
138096     RtreeDValue x1 = DCOORD(aCell[0].aCoord[i*2]);
138097     RtreeDValue x2 = DCOORD(aCell[0].aCoord[i*2+1]);
138098     RtreeDValue x3 = x1;
138099     RtreeDValue x4 = x2;
138100     int jj;
138101
138102     int iCellLeft = 0;
138103     int iCellRight = 0;
138104
138105     for(jj=1; jj<nCell; jj++){
138106       RtreeDValue left = DCOORD(aCell[jj].aCoord[i*2]);
138107       RtreeDValue right = DCOORD(aCell[jj].aCoord[i*2+1]);
138108
138109       if( left<x1 ) x1 = left;
138110       if( right>x4 ) x4 = right;
138111       if( left>x3 ){
138112         x3 = left;
138113         iCellRight = jj;
138114       }
138115       if( right<x2 ){
138116         x2 = right;
138117         iCellLeft = jj;
138118       }
138119     }
138120
138121     if( x4!=x1 ){
138122       RtreeDValue normalwidth = (x3 - x2) / (x4 - x1);
138123       if( normalwidth>maxNormalInnerWidth ){
138124         iLeftSeed = iCellLeft;
138125         iRightSeed = iCellRight;
138126       }
138127     }
138128   }
138129
138130   *piLeftSeed = iLeftSeed;
138131   *piRightSeed = iRightSeed;
138132 }
138133 #endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
138134
138135 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
138136 /*
138137 ** Implementation of the quadratic variant of the PickNext() function from
138138 ** Guttman[84].
138139 */
138140 static RtreeCell *QuadraticPickNext(
138141   Rtree *pRtree,
138142   RtreeCell *aCell, 
138143   int nCell, 
138144   RtreeCell *pLeftBox, 
138145   RtreeCell *pRightBox,
138146   int *aiUsed
138147 ){
138148   #define FABS(a) ((a)<0.0?-1.0*(a):(a))
138149
138150   int iSelect = -1;
138151   RtreeDValue fDiff;
138152   int ii;
138153   for(ii=0; ii<nCell; ii++){
138154     if( aiUsed[ii]==0 ){
138155       RtreeDValue left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
138156       RtreeDValue right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
138157       RtreeDValue diff = FABS(right-left);
138158       if( iSelect<0 || diff>fDiff ){
138159         fDiff = diff;
138160         iSelect = ii;
138161       }
138162     }
138163   }
138164   aiUsed[iSelect] = 1;
138165   return &aCell[iSelect];
138166 }
138167
138168 /*
138169 ** Implementation of the quadratic variant of the PickSeeds() function from
138170 ** Guttman[84].
138171 */
138172 static void QuadraticPickSeeds(
138173   Rtree *pRtree,
138174   RtreeCell *aCell, 
138175   int nCell, 
138176   int *piLeftSeed, 
138177   int *piRightSeed
138178 ){
138179   int ii;
138180   int jj;
138181
138182   int iLeftSeed = 0;
138183   int iRightSeed = 1;
138184   RtreeDValue fWaste = 0.0;
138185
138186   for(ii=0; ii<nCell; ii++){
138187     for(jj=ii+1; jj<nCell; jj++){
138188       RtreeDValue right = cellArea(pRtree, &aCell[jj]);
138189       RtreeDValue growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
138190       RtreeDValue waste = growth - right;
138191
138192       if( waste>fWaste ){
138193         iLeftSeed = ii;
138194         iRightSeed = jj;
138195         fWaste = waste;
138196       }
138197     }
138198   }
138199
138200   *piLeftSeed = iLeftSeed;
138201   *piRightSeed = iRightSeed;
138202 }
138203 #endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
138204
138205 /*
138206 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
138207 ** nIdx. The aIdx array contains the set of integers from 0 to 
138208 ** (nIdx-1) in no particular order. This function sorts the values
138209 ** in aIdx according to the indexed values in aDistance. For
138210 ** example, assuming the inputs:
138211 **
138212 **   aIdx      = { 0,   1,   2,   3 }
138213 **   aDistance = { 5.0, 2.0, 7.0, 6.0 }
138214 **
138215 ** this function sets the aIdx array to contain:
138216 **
138217 **   aIdx      = { 0,   1,   2,   3 }
138218 **
138219 ** The aSpare array is used as temporary working space by the
138220 ** sorting algorithm.
138221 */
138222 static void SortByDistance(
138223   int *aIdx, 
138224   int nIdx, 
138225   RtreeDValue *aDistance, 
138226   int *aSpare
138227 ){
138228   if( nIdx>1 ){
138229     int iLeft = 0;
138230     int iRight = 0;
138231
138232     int nLeft = nIdx/2;
138233     int nRight = nIdx-nLeft;
138234     int *aLeft = aIdx;
138235     int *aRight = &aIdx[nLeft];
138236
138237     SortByDistance(aLeft, nLeft, aDistance, aSpare);
138238     SortByDistance(aRight, nRight, aDistance, aSpare);
138239
138240     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
138241     aLeft = aSpare;
138242
138243     while( iLeft<nLeft || iRight<nRight ){
138244       if( iLeft==nLeft ){
138245         aIdx[iLeft+iRight] = aRight[iRight];
138246         iRight++;
138247       }else if( iRight==nRight ){
138248         aIdx[iLeft+iRight] = aLeft[iLeft];
138249         iLeft++;
138250       }else{
138251         RtreeDValue fLeft = aDistance[aLeft[iLeft]];
138252         RtreeDValue fRight = aDistance[aRight[iRight]];
138253         if( fLeft<fRight ){
138254           aIdx[iLeft+iRight] = aLeft[iLeft];
138255           iLeft++;
138256         }else{
138257           aIdx[iLeft+iRight] = aRight[iRight];
138258           iRight++;
138259         }
138260       }
138261     }
138262
138263 #if 0
138264     /* Check that the sort worked */
138265     {
138266       int jj;
138267       for(jj=1; jj<nIdx; jj++){
138268         RtreeDValue left = aDistance[aIdx[jj-1]];
138269         RtreeDValue right = aDistance[aIdx[jj]];
138270         assert( left<=right );
138271       }
138272     }
138273 #endif
138274   }
138275 }
138276
138277 /*
138278 ** Arguments aIdx, aCell and aSpare all point to arrays of size
138279 ** nIdx. The aIdx array contains the set of integers from 0 to 
138280 ** (nIdx-1) in no particular order. This function sorts the values
138281 ** in aIdx according to dimension iDim of the cells in aCell. The
138282 ** minimum value of dimension iDim is considered first, the
138283 ** maximum used to break ties.
138284 **
138285 ** The aSpare array is used as temporary working space by the
138286 ** sorting algorithm.
138287 */
138288 static void SortByDimension(
138289   Rtree *pRtree,
138290   int *aIdx, 
138291   int nIdx, 
138292   int iDim, 
138293   RtreeCell *aCell, 
138294   int *aSpare
138295 ){
138296   if( nIdx>1 ){
138297
138298     int iLeft = 0;
138299     int iRight = 0;
138300
138301     int nLeft = nIdx/2;
138302     int nRight = nIdx-nLeft;
138303     int *aLeft = aIdx;
138304     int *aRight = &aIdx[nLeft];
138305
138306     SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
138307     SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
138308
138309     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
138310     aLeft = aSpare;
138311     while( iLeft<nLeft || iRight<nRight ){
138312       RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
138313       RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
138314       RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
138315       RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
138316       if( (iLeft!=nLeft) && ((iRight==nRight)
138317        || (xleft1<xright1)
138318        || (xleft1==xright1 && xleft2<xright2)
138319       )){
138320         aIdx[iLeft+iRight] = aLeft[iLeft];
138321         iLeft++;
138322       }else{
138323         aIdx[iLeft+iRight] = aRight[iRight];
138324         iRight++;
138325       }
138326     }
138327
138328 #if 0
138329     /* Check that the sort worked */
138330     {
138331       int jj;
138332       for(jj=1; jj<nIdx; jj++){
138333         RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
138334         RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
138335         RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
138336         RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
138337         assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
138338       }
138339     }
138340 #endif
138341   }
138342 }
138343
138344 #if VARIANT_RSTARTREE_SPLIT
138345 /*
138346 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
138347 */
138348 static int splitNodeStartree(
138349   Rtree *pRtree,
138350   RtreeCell *aCell,
138351   int nCell,
138352   RtreeNode *pLeft,
138353   RtreeNode *pRight,
138354   RtreeCell *pBboxLeft,
138355   RtreeCell *pBboxRight
138356 ){
138357   int **aaSorted;
138358   int *aSpare;
138359   int ii;
138360
138361   int iBestDim = 0;
138362   int iBestSplit = 0;
138363   RtreeDValue fBestMargin = 0.0;
138364
138365   int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
138366
138367   aaSorted = (int **)sqlite3_malloc(nByte);
138368   if( !aaSorted ){
138369     return SQLITE_NOMEM;
138370   }
138371
138372   aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
138373   memset(aaSorted, 0, nByte);
138374   for(ii=0; ii<pRtree->nDim; ii++){
138375     int jj;
138376     aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
138377     for(jj=0; jj<nCell; jj++){
138378       aaSorted[ii][jj] = jj;
138379     }
138380     SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
138381   }
138382
138383   for(ii=0; ii<pRtree->nDim; ii++){
138384     RtreeDValue margin = 0.0;
138385     RtreeDValue fBestOverlap = 0.0;
138386     RtreeDValue fBestArea = 0.0;
138387     int iBestLeft = 0;
138388     int nLeft;
138389
138390     for(
138391       nLeft=RTREE_MINCELLS(pRtree); 
138392       nLeft<=(nCell-RTREE_MINCELLS(pRtree)); 
138393       nLeft++
138394     ){
138395       RtreeCell left;
138396       RtreeCell right;
138397       int kk;
138398       RtreeDValue overlap;
138399       RtreeDValue area;
138400
138401       memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
138402       memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
138403       for(kk=1; kk<(nCell-1); kk++){
138404         if( kk<nLeft ){
138405           cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
138406         }else{
138407           cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
138408         }
138409       }
138410       margin += cellMargin(pRtree, &left);
138411       margin += cellMargin(pRtree, &right);
138412       overlap = cellOverlap(pRtree, &left, &right, 1, -1);
138413       area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
138414       if( (nLeft==RTREE_MINCELLS(pRtree))
138415        || (overlap<fBestOverlap)
138416        || (overlap==fBestOverlap && area<fBestArea)
138417       ){
138418         iBestLeft = nLeft;
138419         fBestOverlap = overlap;
138420         fBestArea = area;
138421       }
138422     }
138423
138424     if( ii==0 || margin<fBestMargin ){
138425       iBestDim = ii;
138426       fBestMargin = margin;
138427       iBestSplit = iBestLeft;
138428     }
138429   }
138430
138431   memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
138432   memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
138433   for(ii=0; ii<nCell; ii++){
138434     RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
138435     RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
138436     RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
138437     nodeInsertCell(pRtree, pTarget, pCell);
138438     cellUnion(pRtree, pBbox, pCell);
138439   }
138440
138441   sqlite3_free(aaSorted);
138442   return SQLITE_OK;
138443 }
138444 #endif
138445
138446 #if VARIANT_GUTTMAN_SPLIT
138447 /*
138448 ** Implementation of the regular R-tree SplitNode from Guttman[1984].
138449 */
138450 static int splitNodeGuttman(
138451   Rtree *pRtree,
138452   RtreeCell *aCell,
138453   int nCell,
138454   RtreeNode *pLeft,
138455   RtreeNode *pRight,
138456   RtreeCell *pBboxLeft,
138457   RtreeCell *pBboxRight
138458 ){
138459   int iLeftSeed = 0;
138460   int iRightSeed = 1;
138461   int *aiUsed;
138462   int i;
138463
138464   aiUsed = sqlite3_malloc(sizeof(int)*nCell);
138465   if( !aiUsed ){
138466     return SQLITE_NOMEM;
138467   }
138468   memset(aiUsed, 0, sizeof(int)*nCell);
138469
138470   PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
138471
138472   memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
138473   memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
138474   nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
138475   nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
138476   aiUsed[iLeftSeed] = 1;
138477   aiUsed[iRightSeed] = 1;
138478
138479   for(i=nCell-2; i>0; i--){
138480     RtreeCell *pNext;
138481     pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
138482     RtreeDValue diff =  
138483       cellGrowth(pRtree, pBboxLeft, pNext) - 
138484       cellGrowth(pRtree, pBboxRight, pNext)
138485     ;
138486     if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
138487      || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
138488     ){
138489       nodeInsertCell(pRtree, pRight, pNext);
138490       cellUnion(pRtree, pBboxRight, pNext);
138491     }else{
138492       nodeInsertCell(pRtree, pLeft, pNext);
138493       cellUnion(pRtree, pBboxLeft, pNext);
138494     }
138495   }
138496
138497   sqlite3_free(aiUsed);
138498   return SQLITE_OK;
138499 }
138500 #endif
138501
138502 static int updateMapping(
138503   Rtree *pRtree, 
138504   i64 iRowid, 
138505   RtreeNode *pNode, 
138506   int iHeight
138507 ){
138508   int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
138509   xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
138510   if( iHeight>0 ){
138511     RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
138512     if( pChild ){
138513       nodeRelease(pRtree, pChild->pParent);
138514       nodeReference(pNode);
138515       pChild->pParent = pNode;
138516     }
138517   }
138518   return xSetMapping(pRtree, iRowid, pNode->iNode);
138519 }
138520
138521 static int SplitNode(
138522   Rtree *pRtree,
138523   RtreeNode *pNode,
138524   RtreeCell *pCell,
138525   int iHeight
138526 ){
138527   int i;
138528   int newCellIsRight = 0;
138529
138530   int rc = SQLITE_OK;
138531   int nCell = NCELL(pNode);
138532   RtreeCell *aCell;
138533   int *aiUsed;
138534
138535   RtreeNode *pLeft = 0;
138536   RtreeNode *pRight = 0;
138537
138538   RtreeCell leftbbox;
138539   RtreeCell rightbbox;
138540
138541   /* Allocate an array and populate it with a copy of pCell and 
138542   ** all cells from node pLeft. Then zero the original node.
138543   */
138544   aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
138545   if( !aCell ){
138546     rc = SQLITE_NOMEM;
138547     goto splitnode_out;
138548   }
138549   aiUsed = (int *)&aCell[nCell+1];
138550   memset(aiUsed, 0, sizeof(int)*(nCell+1));
138551   for(i=0; i<nCell; i++){
138552     nodeGetCell(pRtree, pNode, i, &aCell[i]);
138553   }
138554   nodeZero(pRtree, pNode);
138555   memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
138556   nCell++;
138557
138558   if( pNode->iNode==1 ){
138559     pRight = nodeNew(pRtree, pNode);
138560     pLeft = nodeNew(pRtree, pNode);
138561     pRtree->iDepth++;
138562     pNode->isDirty = 1;
138563     writeInt16(pNode->zData, pRtree->iDepth);
138564   }else{
138565     pLeft = pNode;
138566     pRight = nodeNew(pRtree, pLeft->pParent);
138567     nodeReference(pLeft);
138568   }
138569
138570   if( !pLeft || !pRight ){
138571     rc = SQLITE_NOMEM;
138572     goto splitnode_out;
138573   }
138574
138575   memset(pLeft->zData, 0, pRtree->iNodeSize);
138576   memset(pRight->zData, 0, pRtree->iNodeSize);
138577
138578   rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
138579   if( rc!=SQLITE_OK ){
138580     goto splitnode_out;
138581   }
138582
138583   /* Ensure both child nodes have node numbers assigned to them by calling
138584   ** nodeWrite(). Node pRight always needs a node number, as it was created
138585   ** by nodeNew() above. But node pLeft sometimes already has a node number.
138586   ** In this case avoid the all to nodeWrite().
138587   */
138588   if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
138589    || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
138590   ){
138591     goto splitnode_out;
138592   }
138593
138594   rightbbox.iRowid = pRight->iNode;
138595   leftbbox.iRowid = pLeft->iNode;
138596
138597   if( pNode->iNode==1 ){
138598     rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
138599     if( rc!=SQLITE_OK ){
138600       goto splitnode_out;
138601     }
138602   }else{
138603     RtreeNode *pParent = pLeft->pParent;
138604     int iCell;
138605     rc = nodeParentIndex(pRtree, pLeft, &iCell);
138606     if( rc==SQLITE_OK ){
138607       nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
138608       rc = AdjustTree(pRtree, pParent, &leftbbox);
138609     }
138610     if( rc!=SQLITE_OK ){
138611       goto splitnode_out;
138612     }
138613   }
138614   if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
138615     goto splitnode_out;
138616   }
138617
138618   for(i=0; i<NCELL(pRight); i++){
138619     i64 iRowid = nodeGetRowid(pRtree, pRight, i);
138620     rc = updateMapping(pRtree, iRowid, pRight, iHeight);
138621     if( iRowid==pCell->iRowid ){
138622       newCellIsRight = 1;
138623     }
138624     if( rc!=SQLITE_OK ){
138625       goto splitnode_out;
138626     }
138627   }
138628   if( pNode->iNode==1 ){
138629     for(i=0; i<NCELL(pLeft); i++){
138630       i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
138631       rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
138632       if( rc!=SQLITE_OK ){
138633         goto splitnode_out;
138634       }
138635     }
138636   }else if( newCellIsRight==0 ){
138637     rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
138638   }
138639
138640   if( rc==SQLITE_OK ){
138641     rc = nodeRelease(pRtree, pRight);
138642     pRight = 0;
138643   }
138644   if( rc==SQLITE_OK ){
138645     rc = nodeRelease(pRtree, pLeft);
138646     pLeft = 0;
138647   }
138648
138649 splitnode_out:
138650   nodeRelease(pRtree, pRight);
138651   nodeRelease(pRtree, pLeft);
138652   sqlite3_free(aCell);
138653   return rc;
138654 }
138655
138656 /*
138657 ** If node pLeaf is not the root of the r-tree and its pParent pointer is 
138658 ** still NULL, load all ancestor nodes of pLeaf into memory and populate
138659 ** the pLeaf->pParent chain all the way up to the root node.
138660 **
138661 ** This operation is required when a row is deleted (or updated - an update
138662 ** is implemented as a delete followed by an insert). SQLite provides the
138663 ** rowid of the row to delete, which can be used to find the leaf on which
138664 ** the entry resides (argument pLeaf). Once the leaf is located, this 
138665 ** function is called to determine its ancestry.
138666 */
138667 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
138668   int rc = SQLITE_OK;
138669   RtreeNode *pChild = pLeaf;
138670   while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
138671     int rc2 = SQLITE_OK;          /* sqlite3_reset() return code */
138672     sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
138673     rc = sqlite3_step(pRtree->pReadParent);
138674     if( rc==SQLITE_ROW ){
138675       RtreeNode *pTest;           /* Used to test for reference loops */
138676       i64 iNode;                  /* Node number of parent node */
138677
138678       /* Before setting pChild->pParent, test that we are not creating a
138679       ** loop of references (as we would if, say, pChild==pParent). We don't
138680       ** want to do this as it leads to a memory leak when trying to delete
138681       ** the referenced counted node structures.
138682       */
138683       iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
138684       for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
138685       if( !pTest ){
138686         rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
138687       }
138688     }
138689     rc = sqlite3_reset(pRtree->pReadParent);
138690     if( rc==SQLITE_OK ) rc = rc2;
138691     if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
138692     pChild = pChild->pParent;
138693   }
138694   return rc;
138695 }
138696
138697 static int deleteCell(Rtree *, RtreeNode *, int, int);
138698
138699 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
138700   int rc;
138701   int rc2;
138702   RtreeNode *pParent = 0;
138703   int iCell;
138704
138705   assert( pNode->nRef==1 );
138706
138707   /* Remove the entry in the parent cell. */
138708   rc = nodeParentIndex(pRtree, pNode, &iCell);
138709   if( rc==SQLITE_OK ){
138710     pParent = pNode->pParent;
138711     pNode->pParent = 0;
138712     rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
138713   }
138714   rc2 = nodeRelease(pRtree, pParent);
138715   if( rc==SQLITE_OK ){
138716     rc = rc2;
138717   }
138718   if( rc!=SQLITE_OK ){
138719     return rc;
138720   }
138721
138722   /* Remove the xxx_node entry. */
138723   sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
138724   sqlite3_step(pRtree->pDeleteNode);
138725   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
138726     return rc;
138727   }
138728
138729   /* Remove the xxx_parent entry. */
138730   sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
138731   sqlite3_step(pRtree->pDeleteParent);
138732   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
138733     return rc;
138734   }
138735   
138736   /* Remove the node from the in-memory hash table and link it into
138737   ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
138738   */
138739   nodeHashDelete(pRtree, pNode);
138740   pNode->iNode = iHeight;
138741   pNode->pNext = pRtree->pDeleted;
138742   pNode->nRef++;
138743   pRtree->pDeleted = pNode;
138744
138745   return SQLITE_OK;
138746 }
138747
138748 static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
138749   RtreeNode *pParent = pNode->pParent;
138750   int rc = SQLITE_OK; 
138751   if( pParent ){
138752     int ii; 
138753     int nCell = NCELL(pNode);
138754     RtreeCell box;                            /* Bounding box for pNode */
138755     nodeGetCell(pRtree, pNode, 0, &box);
138756     for(ii=1; ii<nCell; ii++){
138757       RtreeCell cell;
138758       nodeGetCell(pRtree, pNode, ii, &cell);
138759       cellUnion(pRtree, &box, &cell);
138760     }
138761     box.iRowid = pNode->iNode;
138762     rc = nodeParentIndex(pRtree, pNode, &ii);
138763     if( rc==SQLITE_OK ){
138764       nodeOverwriteCell(pRtree, pParent, &box, ii);
138765       rc = fixBoundingBox(pRtree, pParent);
138766     }
138767   }
138768   return rc;
138769 }
138770
138771 /*
138772 ** Delete the cell at index iCell of node pNode. After removing the
138773 ** cell, adjust the r-tree data structure if required.
138774 */
138775 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
138776   RtreeNode *pParent;
138777   int rc;
138778
138779   if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
138780     return rc;
138781   }
138782
138783   /* Remove the cell from the node. This call just moves bytes around
138784   ** the in-memory node image, so it cannot fail.
138785   */
138786   nodeDeleteCell(pRtree, pNode, iCell);
138787
138788   /* If the node is not the tree root and now has less than the minimum
138789   ** number of cells, remove it from the tree. Otherwise, update the
138790   ** cell in the parent node so that it tightly contains the updated
138791   ** node.
138792   */
138793   pParent = pNode->pParent;
138794   assert( pParent || pNode->iNode==1 );
138795   if( pParent ){
138796     if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
138797       rc = removeNode(pRtree, pNode, iHeight);
138798     }else{
138799       rc = fixBoundingBox(pRtree, pNode);
138800     }
138801   }
138802
138803   return rc;
138804 }
138805
138806 static int Reinsert(
138807   Rtree *pRtree, 
138808   RtreeNode *pNode, 
138809   RtreeCell *pCell, 
138810   int iHeight
138811 ){
138812   int *aOrder;
138813   int *aSpare;
138814   RtreeCell *aCell;
138815   RtreeDValue *aDistance;
138816   int nCell;
138817   RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
138818   int iDim;
138819   int ii;
138820   int rc = SQLITE_OK;
138821   int n;
138822
138823   memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
138824
138825   nCell = NCELL(pNode)+1;
138826   n = (nCell+1)&(~1);
138827
138828   /* Allocate the buffers used by this operation. The allocation is
138829   ** relinquished before this function returns.
138830   */
138831   aCell = (RtreeCell *)sqlite3_malloc(n * (
138832     sizeof(RtreeCell)     +         /* aCell array */
138833     sizeof(int)           +         /* aOrder array */
138834     sizeof(int)           +         /* aSpare array */
138835     sizeof(RtreeDValue)             /* aDistance array */
138836   ));
138837   if( !aCell ){
138838     return SQLITE_NOMEM;
138839   }
138840   aOrder    = (int *)&aCell[n];
138841   aSpare    = (int *)&aOrder[n];
138842   aDistance = (RtreeDValue *)&aSpare[n];
138843
138844   for(ii=0; ii<nCell; ii++){
138845     if( ii==(nCell-1) ){
138846       memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
138847     }else{
138848       nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
138849     }
138850     aOrder[ii] = ii;
138851     for(iDim=0; iDim<pRtree->nDim; iDim++){
138852       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
138853       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
138854     }
138855   }
138856   for(iDim=0; iDim<pRtree->nDim; iDim++){
138857     aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
138858   }
138859
138860   for(ii=0; ii<nCell; ii++){
138861     aDistance[ii] = 0.0;
138862     for(iDim=0; iDim<pRtree->nDim; iDim++){
138863       RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) - 
138864                                DCOORD(aCell[ii].aCoord[iDim*2]));
138865       aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
138866     }
138867   }
138868
138869   SortByDistance(aOrder, nCell, aDistance, aSpare);
138870   nodeZero(pRtree, pNode);
138871
138872   for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
138873     RtreeCell *p = &aCell[aOrder[ii]];
138874     nodeInsertCell(pRtree, pNode, p);
138875     if( p->iRowid==pCell->iRowid ){
138876       if( iHeight==0 ){
138877         rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
138878       }else{
138879         rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
138880       }
138881     }
138882   }
138883   if( rc==SQLITE_OK ){
138884     rc = fixBoundingBox(pRtree, pNode);
138885   }
138886   for(; rc==SQLITE_OK && ii<nCell; ii++){
138887     /* Find a node to store this cell in. pNode->iNode currently contains
138888     ** the height of the sub-tree headed by the cell.
138889     */
138890     RtreeNode *pInsert;
138891     RtreeCell *p = &aCell[aOrder[ii]];
138892     rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
138893     if( rc==SQLITE_OK ){
138894       int rc2;
138895       rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
138896       rc2 = nodeRelease(pRtree, pInsert);
138897       if( rc==SQLITE_OK ){
138898         rc = rc2;
138899       }
138900     }
138901   }
138902
138903   sqlite3_free(aCell);
138904   return rc;
138905 }
138906
138907 /*
138908 ** Insert cell pCell into node pNode. Node pNode is the head of a 
138909 ** subtree iHeight high (leaf nodes have iHeight==0).
138910 */
138911 static int rtreeInsertCell(
138912   Rtree *pRtree,
138913   RtreeNode *pNode,
138914   RtreeCell *pCell,
138915   int iHeight
138916 ){
138917   int rc = SQLITE_OK;
138918   if( iHeight>0 ){
138919     RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
138920     if( pChild ){
138921       nodeRelease(pRtree, pChild->pParent);
138922       nodeReference(pNode);
138923       pChild->pParent = pNode;
138924     }
138925   }
138926   if( nodeInsertCell(pRtree, pNode, pCell) ){
138927 #if VARIANT_RSTARTREE_REINSERT
138928     if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
138929       rc = SplitNode(pRtree, pNode, pCell, iHeight);
138930     }else{
138931       pRtree->iReinsertHeight = iHeight;
138932       rc = Reinsert(pRtree, pNode, pCell, iHeight);
138933     }
138934 #else
138935     rc = SplitNode(pRtree, pNode, pCell, iHeight);
138936 #endif
138937   }else{
138938     rc = AdjustTree(pRtree, pNode, pCell);
138939     if( rc==SQLITE_OK ){
138940       if( iHeight==0 ){
138941         rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
138942       }else{
138943         rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
138944       }
138945     }
138946   }
138947   return rc;
138948 }
138949
138950 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
138951   int ii;
138952   int rc = SQLITE_OK;
138953   int nCell = NCELL(pNode);
138954
138955   for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
138956     RtreeNode *pInsert;
138957     RtreeCell cell;
138958     nodeGetCell(pRtree, pNode, ii, &cell);
138959
138960     /* Find a node to store this cell in. pNode->iNode currently contains
138961     ** the height of the sub-tree headed by the cell.
138962     */
138963     rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
138964     if( rc==SQLITE_OK ){
138965       int rc2;
138966       rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
138967       rc2 = nodeRelease(pRtree, pInsert);
138968       if( rc==SQLITE_OK ){
138969         rc = rc2;
138970       }
138971     }
138972   }
138973   return rc;
138974 }
138975
138976 /*
138977 ** Select a currently unused rowid for a new r-tree record.
138978 */
138979 static int newRowid(Rtree *pRtree, i64 *piRowid){
138980   int rc;
138981   sqlite3_bind_null(pRtree->pWriteRowid, 1);
138982   sqlite3_bind_null(pRtree->pWriteRowid, 2);
138983   sqlite3_step(pRtree->pWriteRowid);
138984   rc = sqlite3_reset(pRtree->pWriteRowid);
138985   *piRowid = sqlite3_last_insert_rowid(pRtree->db);
138986   return rc;
138987 }
138988
138989 /*
138990 ** Remove the entry with rowid=iDelete from the r-tree structure.
138991 */
138992 static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
138993   int rc;                         /* Return code */
138994   RtreeNode *pLeaf = 0;           /* Leaf node containing record iDelete */
138995   int iCell;                      /* Index of iDelete cell in pLeaf */
138996   RtreeNode *pRoot;               /* Root node of rtree structure */
138997
138998
138999   /* Obtain a reference to the root node to initialize Rtree.iDepth */
139000   rc = nodeAcquire(pRtree, 1, 0, &pRoot);
139001
139002   /* Obtain a reference to the leaf node that contains the entry 
139003   ** about to be deleted. 
139004   */
139005   if( rc==SQLITE_OK ){
139006     rc = findLeafNode(pRtree, iDelete, &pLeaf);
139007   }
139008
139009   /* Delete the cell in question from the leaf node. */
139010   if( rc==SQLITE_OK ){
139011     int rc2;
139012     rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
139013     if( rc==SQLITE_OK ){
139014       rc = deleteCell(pRtree, pLeaf, iCell, 0);
139015     }
139016     rc2 = nodeRelease(pRtree, pLeaf);
139017     if( rc==SQLITE_OK ){
139018       rc = rc2;
139019     }
139020   }
139021
139022   /* Delete the corresponding entry in the <rtree>_rowid table. */
139023   if( rc==SQLITE_OK ){
139024     sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
139025     sqlite3_step(pRtree->pDeleteRowid);
139026     rc = sqlite3_reset(pRtree->pDeleteRowid);
139027   }
139028
139029   /* Check if the root node now has exactly one child. If so, remove
139030   ** it, schedule the contents of the child for reinsertion and 
139031   ** reduce the tree height by one.
139032   **
139033   ** This is equivalent to copying the contents of the child into
139034   ** the root node (the operation that Gutman's paper says to perform 
139035   ** in this scenario).
139036   */
139037   if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
139038     int rc2;
139039     RtreeNode *pChild;
139040     i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
139041     rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
139042     if( rc==SQLITE_OK ){
139043       rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
139044     }
139045     rc2 = nodeRelease(pRtree, pChild);
139046     if( rc==SQLITE_OK ) rc = rc2;
139047     if( rc==SQLITE_OK ){
139048       pRtree->iDepth--;
139049       writeInt16(pRoot->zData, pRtree->iDepth);
139050       pRoot->isDirty = 1;
139051     }
139052   }
139053
139054   /* Re-insert the contents of any underfull nodes removed from the tree. */
139055   for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
139056     if( rc==SQLITE_OK ){
139057       rc = reinsertNodeContent(pRtree, pLeaf);
139058     }
139059     pRtree->pDeleted = pLeaf->pNext;
139060     sqlite3_free(pLeaf);
139061   }
139062
139063   /* Release the reference to the root node. */
139064   if( rc==SQLITE_OK ){
139065     rc = nodeRelease(pRtree, pRoot);
139066   }else{
139067     nodeRelease(pRtree, pRoot);
139068   }
139069
139070   return rc;
139071 }
139072
139073 /*
139074 ** Rounding constants for float->double conversion.
139075 */
139076 #define RNDTOWARDS  (1.0 - 1.0/8388608.0)  /* Round towards zero */
139077 #define RNDAWAY     (1.0 + 1.0/8388608.0)  /* Round away from zero */
139078
139079 #if !defined(SQLITE_RTREE_INT_ONLY)
139080 /*
139081 ** Convert an sqlite3_value into an RtreeValue (presumably a float)
139082 ** while taking care to round toward negative or positive, respectively.
139083 */
139084 static RtreeValue rtreeValueDown(sqlite3_value *v){
139085   double d = sqlite3_value_double(v);
139086   float f = (float)d;
139087   if( f>d ){
139088     f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
139089   }
139090   return f;
139091 }
139092 static RtreeValue rtreeValueUp(sqlite3_value *v){
139093   double d = sqlite3_value_double(v);
139094   float f = (float)d;
139095   if( f<d ){
139096     f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
139097   }
139098   return f;
139099 }
139100 #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
139101
139102
139103 /*
139104 ** The xUpdate method for rtree module virtual tables.
139105 */
139106 static int rtreeUpdate(
139107   sqlite3_vtab *pVtab, 
139108   int nData, 
139109   sqlite3_value **azData, 
139110   sqlite_int64 *pRowid
139111 ){
139112   Rtree *pRtree = (Rtree *)pVtab;
139113   int rc = SQLITE_OK;
139114   RtreeCell cell;                 /* New cell to insert if nData>1 */
139115   int bHaveRowid = 0;             /* Set to 1 after new rowid is determined */
139116
139117   rtreeReference(pRtree);
139118   assert(nData>=1);
139119
139120   /* Constraint handling. A write operation on an r-tree table may return
139121   ** SQLITE_CONSTRAINT for two reasons:
139122   **
139123   **   1. A duplicate rowid value, or
139124   **   2. The supplied data violates the "x2>=x1" constraint.
139125   **
139126   ** In the first case, if the conflict-handling mode is REPLACE, then
139127   ** the conflicting row can be removed before proceeding. In the second
139128   ** case, SQLITE_CONSTRAINT must be returned regardless of the
139129   ** conflict-handling mode specified by the user.
139130   */
139131   if( nData>1 ){
139132     int ii;
139133
139134     /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
139135     assert( nData==(pRtree->nDim*2 + 3) );
139136 #ifndef SQLITE_RTREE_INT_ONLY
139137     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
139138       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
139139         cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);
139140         cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);
139141         if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
139142           rc = SQLITE_CONSTRAINT;
139143           goto constraint;
139144         }
139145       }
139146     }else
139147 #endif
139148     {
139149       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
139150         cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
139151         cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
139152         if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
139153           rc = SQLITE_CONSTRAINT;
139154           goto constraint;
139155         }
139156       }
139157     }
139158
139159     /* If a rowid value was supplied, check if it is already present in 
139160     ** the table. If so, the constraint has failed. */
139161     if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
139162       cell.iRowid = sqlite3_value_int64(azData[2]);
139163       if( sqlite3_value_type(azData[0])==SQLITE_NULL
139164        || sqlite3_value_int64(azData[0])!=cell.iRowid
139165       ){
139166         int steprc;
139167         sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
139168         steprc = sqlite3_step(pRtree->pReadRowid);
139169         rc = sqlite3_reset(pRtree->pReadRowid);
139170         if( SQLITE_ROW==steprc ){
139171           if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
139172             rc = rtreeDeleteRowid(pRtree, cell.iRowid);
139173           }else{
139174             rc = SQLITE_CONSTRAINT;
139175             goto constraint;
139176           }
139177         }
139178       }
139179       bHaveRowid = 1;
139180     }
139181   }
139182
139183   /* If azData[0] is not an SQL NULL value, it is the rowid of a
139184   ** record to delete from the r-tree table. The following block does
139185   ** just that.
139186   */
139187   if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
139188     rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
139189   }
139190
139191   /* If the azData[] array contains more than one element, elements
139192   ** (azData[2]..azData[argc-1]) contain a new record to insert into
139193   ** the r-tree structure.
139194   */
139195   if( rc==SQLITE_OK && nData>1 ){
139196     /* Insert the new record into the r-tree */
139197     RtreeNode *pLeaf = 0;
139198
139199     /* Figure out the rowid of the new row. */
139200     if( bHaveRowid==0 ){
139201       rc = newRowid(pRtree, &cell.iRowid);
139202     }
139203     *pRowid = cell.iRowid;
139204
139205     if( rc==SQLITE_OK ){
139206       rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
139207     }
139208     if( rc==SQLITE_OK ){
139209       int rc2;
139210       pRtree->iReinsertHeight = -1;
139211       rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
139212       rc2 = nodeRelease(pRtree, pLeaf);
139213       if( rc==SQLITE_OK ){
139214         rc = rc2;
139215       }
139216     }
139217   }
139218
139219 constraint:
139220   rtreeRelease(pRtree);
139221   return rc;
139222 }
139223
139224 /*
139225 ** The xRename method for rtree module virtual tables.
139226 */
139227 static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
139228   Rtree *pRtree = (Rtree *)pVtab;
139229   int rc = SQLITE_NOMEM;
139230   char *zSql = sqlite3_mprintf(
139231     "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
139232     "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
139233     "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
139234     , pRtree->zDb, pRtree->zName, zNewName 
139235     , pRtree->zDb, pRtree->zName, zNewName 
139236     , pRtree->zDb, pRtree->zName, zNewName
139237   );
139238   if( zSql ){
139239     rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
139240     sqlite3_free(zSql);
139241   }
139242   return rc;
139243 }
139244
139245 static sqlite3_module rtreeModule = {
139246   0,                          /* iVersion */
139247   rtreeCreate,                /* xCreate - create a table */
139248   rtreeConnect,               /* xConnect - connect to an existing table */
139249   rtreeBestIndex,             /* xBestIndex - Determine search strategy */
139250   rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
139251   rtreeDestroy,               /* xDestroy - Drop a table */
139252   rtreeOpen,                  /* xOpen - open a cursor */
139253   rtreeClose,                 /* xClose - close a cursor */
139254   rtreeFilter,                /* xFilter - configure scan constraints */
139255   rtreeNext,                  /* xNext - advance a cursor */
139256   rtreeEof,                   /* xEof */
139257   rtreeColumn,                /* xColumn - read data */
139258   rtreeRowid,                 /* xRowid - read data */
139259   rtreeUpdate,                /* xUpdate - write data */
139260   0,                          /* xBegin - begin transaction */
139261   0,                          /* xSync - sync transaction */
139262   0,                          /* xCommit - commit transaction */
139263   0,                          /* xRollback - rollback transaction */
139264   0,                          /* xFindFunction - function overloading */
139265   rtreeRename,                /* xRename - rename the table */
139266   0,                          /* xSavepoint */
139267   0,                          /* xRelease */
139268   0                           /* xRollbackTo */
139269 };
139270
139271 static int rtreeSqlInit(
139272   Rtree *pRtree, 
139273   sqlite3 *db, 
139274   const char *zDb, 
139275   const char *zPrefix, 
139276   int isCreate
139277 ){
139278   int rc = SQLITE_OK;
139279
139280   #define N_STATEMENT 9
139281   static const char *azSql[N_STATEMENT] = {
139282     /* Read and write the xxx_node table */
139283     "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
139284     "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
139285     "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
139286
139287     /* Read and write the xxx_rowid table */
139288     "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
139289     "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
139290     "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
139291
139292     /* Read and write the xxx_parent table */
139293     "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
139294     "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
139295     "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
139296   };
139297   sqlite3_stmt **appStmt[N_STATEMENT];
139298   int i;
139299
139300   pRtree->db = db;
139301
139302   if( isCreate ){
139303     char *zCreate = sqlite3_mprintf(
139304 "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
139305 "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
139306 "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
139307 "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
139308       zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
139309     );
139310     if( !zCreate ){
139311       return SQLITE_NOMEM;
139312     }
139313     rc = sqlite3_exec(db, zCreate, 0, 0, 0);
139314     sqlite3_free(zCreate);
139315     if( rc!=SQLITE_OK ){
139316       return rc;
139317     }
139318   }
139319
139320   appStmt[0] = &pRtree->pReadNode;
139321   appStmt[1] = &pRtree->pWriteNode;
139322   appStmt[2] = &pRtree->pDeleteNode;
139323   appStmt[3] = &pRtree->pReadRowid;
139324   appStmt[4] = &pRtree->pWriteRowid;
139325   appStmt[5] = &pRtree->pDeleteRowid;
139326   appStmt[6] = &pRtree->pReadParent;
139327   appStmt[7] = &pRtree->pWriteParent;
139328   appStmt[8] = &pRtree->pDeleteParent;
139329
139330   for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
139331     char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
139332     if( zSql ){
139333       rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0); 
139334     }else{
139335       rc = SQLITE_NOMEM;
139336     }
139337     sqlite3_free(zSql);
139338   }
139339
139340   return rc;
139341 }
139342
139343 /*
139344 ** The second argument to this function contains the text of an SQL statement
139345 ** that returns a single integer value. The statement is compiled and executed
139346 ** using database connection db. If successful, the integer value returned
139347 ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
139348 ** code is returned and the value of *piVal after returning is not defined.
139349 */
139350 static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
139351   int rc = SQLITE_NOMEM;
139352   if( zSql ){
139353     sqlite3_stmt *pStmt = 0;
139354     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
139355     if( rc==SQLITE_OK ){
139356       if( SQLITE_ROW==sqlite3_step(pStmt) ){
139357         *piVal = sqlite3_column_int(pStmt, 0);
139358       }
139359       rc = sqlite3_finalize(pStmt);
139360     }
139361   }
139362   return rc;
139363 }
139364
139365 /*
139366 ** This function is called from within the xConnect() or xCreate() method to
139367 ** determine the node-size used by the rtree table being created or connected
139368 ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
139369 ** Otherwise, an SQLite error code is returned.
139370 **
139371 ** If this function is being called as part of an xConnect(), then the rtree
139372 ** table already exists. In this case the node-size is determined by inspecting
139373 ** the root node of the tree.
139374 **
139375 ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size. 
139376 ** This ensures that each node is stored on a single database page. If the 
139377 ** database page-size is so large that more than RTREE_MAXCELLS entries 
139378 ** would fit in a single node, use a smaller node-size.
139379 */
139380 static int getNodeSize(
139381   sqlite3 *db,                    /* Database handle */
139382   Rtree *pRtree,                  /* Rtree handle */
139383   int isCreate,                   /* True for xCreate, false for xConnect */
139384   char **pzErr                    /* OUT: Error message, if any */
139385 ){
139386   int rc;
139387   char *zSql;
139388   if( isCreate ){
139389     int iPageSize = 0;
139390     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
139391     rc = getIntFromStmt(db, zSql, &iPageSize);
139392     if( rc==SQLITE_OK ){
139393       pRtree->iNodeSize = iPageSize-64;
139394       if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
139395         pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
139396       }
139397     }else{
139398       *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
139399     }
139400   }else{
139401     zSql = sqlite3_mprintf(
139402         "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
139403         pRtree->zDb, pRtree->zName
139404     );
139405     rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
139406     if( rc!=SQLITE_OK ){
139407       *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
139408     }
139409   }
139410
139411   sqlite3_free(zSql);
139412   return rc;
139413 }
139414
139415 /* 
139416 ** This function is the implementation of both the xConnect and xCreate
139417 ** methods of the r-tree virtual table.
139418 **
139419 **   argv[0]   -> module name
139420 **   argv[1]   -> database name
139421 **   argv[2]   -> table name
139422 **   argv[...] -> column names...
139423 */
139424 static int rtreeInit(
139425   sqlite3 *db,                        /* Database connection */
139426   void *pAux,                         /* One of the RTREE_COORD_* constants */
139427   int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
139428   sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
139429   char **pzErr,                       /* OUT: Error message, if any */
139430   int isCreate                        /* True for xCreate, false for xConnect */
139431 ){
139432   int rc = SQLITE_OK;
139433   Rtree *pRtree;
139434   int nDb;              /* Length of string argv[1] */
139435   int nName;            /* Length of string argv[2] */
139436   int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
139437
139438   const char *aErrMsg[] = {
139439     0,                                                    /* 0 */
139440     "Wrong number of columns for an rtree table",         /* 1 */
139441     "Too few columns for an rtree table",                 /* 2 */
139442     "Too many columns for an rtree table"                 /* 3 */
139443   };
139444
139445   int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
139446   if( aErrMsg[iErr] ){
139447     *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
139448     return SQLITE_ERROR;
139449   }
139450
139451   sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
139452
139453   /* Allocate the sqlite3_vtab structure */
139454   nDb = (int)strlen(argv[1]);
139455   nName = (int)strlen(argv[2]);
139456   pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
139457   if( !pRtree ){
139458     return SQLITE_NOMEM;
139459   }
139460   memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
139461   pRtree->nBusy = 1;
139462   pRtree->base.pModule = &rtreeModule;
139463   pRtree->zDb = (char *)&pRtree[1];
139464   pRtree->zName = &pRtree->zDb[nDb+1];
139465   pRtree->nDim = (argc-4)/2;
139466   pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
139467   pRtree->eCoordType = eCoordType;
139468   memcpy(pRtree->zDb, argv[1], nDb);
139469   memcpy(pRtree->zName, argv[2], nName);
139470
139471   /* Figure out the node size to use. */
139472   rc = getNodeSize(db, pRtree, isCreate, pzErr);
139473
139474   /* Create/Connect to the underlying relational database schema. If
139475   ** that is successful, call sqlite3_declare_vtab() to configure
139476   ** the r-tree table schema.
139477   */
139478   if( rc==SQLITE_OK ){
139479     if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
139480       *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
139481     }else{
139482       char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
139483       char *zTmp;
139484       int ii;
139485       for(ii=4; zSql && ii<argc; ii++){
139486         zTmp = zSql;
139487         zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
139488         sqlite3_free(zTmp);
139489       }
139490       if( zSql ){
139491         zTmp = zSql;
139492         zSql = sqlite3_mprintf("%s);", zTmp);
139493         sqlite3_free(zTmp);
139494       }
139495       if( !zSql ){
139496         rc = SQLITE_NOMEM;
139497       }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
139498         *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
139499       }
139500       sqlite3_free(zSql);
139501     }
139502   }
139503
139504   if( rc==SQLITE_OK ){
139505     *ppVtab = (sqlite3_vtab *)pRtree;
139506   }else{
139507     rtreeRelease(pRtree);
139508   }
139509   return rc;
139510 }
139511
139512
139513 /*
139514 ** Implementation of a scalar function that decodes r-tree nodes to
139515 ** human readable strings. This can be used for debugging and analysis.
139516 **
139517 ** The scalar function takes two arguments, a blob of data containing
139518 ** an r-tree node, and the number of dimensions the r-tree indexes.
139519 ** For a two-dimensional r-tree structure called "rt", to deserialize
139520 ** all nodes, a statement like:
139521 **
139522 **   SELECT rtreenode(2, data) FROM rt_node;
139523 **
139524 ** The human readable string takes the form of a Tcl list with one
139525 ** entry for each cell in the r-tree node. Each entry is itself a
139526 ** list, containing the 8-byte rowid/pageno followed by the 
139527 ** <num-dimension>*2 coordinates.
139528 */
139529 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
139530   char *zText = 0;
139531   RtreeNode node;
139532   Rtree tree;
139533   int ii;
139534
139535   UNUSED_PARAMETER(nArg);
139536   memset(&node, 0, sizeof(RtreeNode));
139537   memset(&tree, 0, sizeof(Rtree));
139538   tree.nDim = sqlite3_value_int(apArg[0]);
139539   tree.nBytesPerCell = 8 + 8 * tree.nDim;
139540   node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
139541
139542   for(ii=0; ii<NCELL(&node); ii++){
139543     char zCell[512];
139544     int nCell = 0;
139545     RtreeCell cell;
139546     int jj;
139547
139548     nodeGetCell(&tree, &node, ii, &cell);
139549     sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
139550     nCell = (int)strlen(zCell);
139551     for(jj=0; jj<tree.nDim*2; jj++){
139552 #ifndef SQLITE_RTREE_INT_ONLY
139553       sqlite3_snprintf(512-nCell,&zCell[nCell], " %f",
139554                        (double)cell.aCoord[jj].f);
139555 #else
139556       sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
139557                        cell.aCoord[jj].i);
139558 #endif
139559       nCell = (int)strlen(zCell);
139560     }
139561
139562     if( zText ){
139563       char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
139564       sqlite3_free(zText);
139565       zText = zTextNew;
139566     }else{
139567       zText = sqlite3_mprintf("{%s}", zCell);
139568     }
139569   }
139570   
139571   sqlite3_result_text(ctx, zText, -1, sqlite3_free);
139572 }
139573
139574 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
139575   UNUSED_PARAMETER(nArg);
139576   if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB 
139577    || sqlite3_value_bytes(apArg[0])<2
139578   ){
139579     sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1); 
139580   }else{
139581     u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
139582     sqlite3_result_int(ctx, readInt16(zBlob));
139583   }
139584 }
139585
139586 /*
139587 ** Register the r-tree module with database handle db. This creates the
139588 ** virtual table module "rtree" and the debugging/analysis scalar 
139589 ** function "rtreenode".
139590 */
139591 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
139592   const int utf8 = SQLITE_UTF8;
139593   int rc;
139594
139595   rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
139596   if( rc==SQLITE_OK ){
139597     rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
139598   }
139599   if( rc==SQLITE_OK ){
139600 #ifdef SQLITE_RTREE_INT_ONLY
139601     void *c = (void *)RTREE_COORD_INT32;
139602 #else
139603     void *c = (void *)RTREE_COORD_REAL32;
139604 #endif
139605     rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
139606   }
139607   if( rc==SQLITE_OK ){
139608     void *c = (void *)RTREE_COORD_INT32;
139609     rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
139610   }
139611
139612   return rc;
139613 }
139614
139615 /*
139616 ** A version of sqlite3_free() that can be used as a callback. This is used
139617 ** in two places - as the destructor for the blob value returned by the
139618 ** invocation of a geometry function, and as the destructor for the geometry
139619 ** functions themselves.
139620 */
139621 static void doSqlite3Free(void *p){
139622   sqlite3_free(p);
139623 }
139624
139625 /*
139626 ** Each call to sqlite3_rtree_geometry_callback() creates an ordinary SQLite
139627 ** scalar user function. This C function is the callback used for all such
139628 ** registered SQL functions.
139629 **
139630 ** The scalar user functions return a blob that is interpreted by r-tree
139631 ** table MATCH operators.
139632 */
139633 static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
139634   RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
139635   RtreeMatchArg *pBlob;
139636   int nBlob;
139637
139638   nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue);
139639   pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
139640   if( !pBlob ){
139641     sqlite3_result_error_nomem(ctx);
139642   }else{
139643     int i;
139644     pBlob->magic = RTREE_GEOMETRY_MAGIC;
139645     pBlob->xGeom = pGeomCtx->xGeom;
139646     pBlob->pContext = pGeomCtx->pContext;
139647     pBlob->nParam = nArg;
139648     for(i=0; i<nArg; i++){
139649 #ifdef SQLITE_RTREE_INT_ONLY
139650       pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
139651 #else
139652       pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
139653 #endif
139654     }
139655     sqlite3_result_blob(ctx, pBlob, nBlob, doSqlite3Free);
139656   }
139657 }
139658
139659 /*
139660 ** Register a new geometry function for use with the r-tree MATCH operator.
139661 */
139662 SQLITE_API int sqlite3_rtree_geometry_callback(
139663   sqlite3 *db,
139664   const char *zGeom,
139665   int (*xGeom)(sqlite3_rtree_geometry *, int, RtreeDValue *, int *),
139666   void *pContext
139667 ){
139668   RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
139669
139670   /* Allocate and populate the context object. */
139671   pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
139672   if( !pGeomCtx ) return SQLITE_NOMEM;
139673   pGeomCtx->xGeom = xGeom;
139674   pGeomCtx->pContext = pContext;
139675
139676   /* Create the new user-function. Register a destructor function to delete
139677   ** the context object when it is no longer required.  */
139678   return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY, 
139679       (void *)pGeomCtx, geomCallback, 0, 0, doSqlite3Free
139680   );
139681 }
139682
139683 #if !SQLITE_CORE
139684 SQLITE_API int sqlite3_extension_init(
139685   sqlite3 *db,
139686   char **pzErrMsg,
139687   const sqlite3_api_routines *pApi
139688 ){
139689   SQLITE_EXTENSION_INIT2(pApi)
139690   return sqlite3RtreeInit(db);
139691 }
139692 #endif
139693
139694 #endif
139695
139696 /************** End of rtree.c ***********************************************/
139697 /************** Begin file icu.c *********************************************/
139698 /*
139699 ** 2007 May 6
139700 **
139701 ** The author disclaims copyright to this source code.  In place of
139702 ** a legal notice, here is a blessing:
139703 **
139704 **    May you do good and not evil.
139705 **    May you find forgiveness for yourself and forgive others.
139706 **    May you share freely, never taking more than you give.
139707 **
139708 *************************************************************************
139709 ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
139710 **
139711 ** This file implements an integration between the ICU library 
139712 ** ("International Components for Unicode", an open-source library 
139713 ** for handling unicode data) and SQLite. The integration uses 
139714 ** ICU to provide the following to SQLite:
139715 **
139716 **   * An implementation of the SQL regexp() function (and hence REGEXP
139717 **     operator) using the ICU uregex_XX() APIs.
139718 **
139719 **   * Implementations of the SQL scalar upper() and lower() functions
139720 **     for case mapping.
139721 **
139722 **   * Integration of ICU and SQLite collation seqences.
139723 **
139724 **   * An implementation of the LIKE operator that uses ICU to 
139725 **     provide case-independent matching.
139726 */
139727
139728 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
139729
139730 /* Include ICU headers */
139731 #include <unicode/utypes.h>
139732 #include <unicode/uregex.h>
139733 #include <unicode/ustring.h>
139734 #include <unicode/ucol.h>
139735
139736 /* #include <assert.h> */
139737
139738 #ifndef SQLITE_CORE
139739   SQLITE_EXTENSION_INIT1
139740 #else
139741 #endif
139742
139743 /*
139744 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
139745 ** operator.
139746 */
139747 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
139748 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
139749 #endif
139750
139751 /*
139752 ** Version of sqlite3_free() that is always a function, never a macro.
139753 */
139754 static void xFree(void *p){
139755   sqlite3_free(p);
139756 }
139757
139758 /*
139759 ** Compare two UTF-8 strings for equality where the first string is
139760 ** a "LIKE" expression. Return true (1) if they are the same and 
139761 ** false (0) if they are different.
139762 */
139763 static int icuLikeCompare(
139764   const uint8_t *zPattern,   /* LIKE pattern */
139765   const uint8_t *zString,    /* The UTF-8 string to compare against */
139766   const UChar32 uEsc         /* The escape character */
139767 ){
139768   static const int MATCH_ONE = (UChar32)'_';
139769   static const int MATCH_ALL = (UChar32)'%';
139770
139771   int iPattern = 0;       /* Current byte index in zPattern */
139772   int iString = 0;        /* Current byte index in zString */
139773
139774   int prevEscape = 0;     /* True if the previous character was uEsc */
139775
139776   while( zPattern[iPattern]!=0 ){
139777
139778     /* Read (and consume) the next character from the input pattern. */
139779     UChar32 uPattern;
139780     U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
139781     assert(uPattern!=0);
139782
139783     /* There are now 4 possibilities:
139784     **
139785     **     1. uPattern is an unescaped match-all character "%",
139786     **     2. uPattern is an unescaped match-one character "_",
139787     **     3. uPattern is an unescaped escape character, or
139788     **     4. uPattern is to be handled as an ordinary character
139789     */
139790     if( !prevEscape && uPattern==MATCH_ALL ){
139791       /* Case 1. */
139792       uint8_t c;
139793
139794       /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
139795       ** MATCH_ALL. For each MATCH_ONE, skip one character in the 
139796       ** test string.
139797       */
139798       while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
139799         if( c==MATCH_ONE ){
139800           if( zString[iString]==0 ) return 0;
139801           U8_FWD_1_UNSAFE(zString, iString);
139802         }
139803         iPattern++;
139804       }
139805
139806       if( zPattern[iPattern]==0 ) return 1;
139807
139808       while( zString[iString] ){
139809         if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
139810           return 1;
139811         }
139812         U8_FWD_1_UNSAFE(zString, iString);
139813       }
139814       return 0;
139815
139816     }else if( !prevEscape && uPattern==MATCH_ONE ){
139817       /* Case 2. */
139818       if( zString[iString]==0 ) return 0;
139819       U8_FWD_1_UNSAFE(zString, iString);
139820
139821     }else if( !prevEscape && uPattern==uEsc){
139822       /* Case 3. */
139823       prevEscape = 1;
139824
139825     }else{
139826       /* Case 4. */
139827       UChar32 uString;
139828       U8_NEXT_UNSAFE(zString, iString, uString);
139829       uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
139830       uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
139831       if( uString!=uPattern ){
139832         return 0;
139833       }
139834       prevEscape = 0;
139835     }
139836   }
139837
139838   return zString[iString]==0;
139839 }
139840
139841 /*
139842 ** Implementation of the like() SQL function.  This function implements
139843 ** the build-in LIKE operator.  The first argument to the function is the
139844 ** pattern and the second argument is the string.  So, the SQL statements:
139845 **
139846 **       A LIKE B
139847 **
139848 ** is implemented as like(B, A). If there is an escape character E, 
139849 **
139850 **       A LIKE B ESCAPE E
139851 **
139852 ** is mapped to like(B, A, E).
139853 */
139854 static void icuLikeFunc(
139855   sqlite3_context *context, 
139856   int argc, 
139857   sqlite3_value **argv
139858 ){
139859   const unsigned char *zA = sqlite3_value_text(argv[0]);
139860   const unsigned char *zB = sqlite3_value_text(argv[1]);
139861   UChar32 uEsc = 0;
139862
139863   /* Limit the length of the LIKE or GLOB pattern to avoid problems
139864   ** of deep recursion and N*N behavior in patternCompare().
139865   */
139866   if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
139867     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
139868     return;
139869   }
139870
139871
139872   if( argc==3 ){
139873     /* The escape character string must consist of a single UTF-8 character.
139874     ** Otherwise, return an error.
139875     */
139876     int nE= sqlite3_value_bytes(argv[2]);
139877     const unsigned char *zE = sqlite3_value_text(argv[2]);
139878     int i = 0;
139879     if( zE==0 ) return;
139880     U8_NEXT(zE, i, nE, uEsc);
139881     if( i!=nE){
139882       sqlite3_result_error(context, 
139883           "ESCAPE expression must be a single character", -1);
139884       return;
139885     }
139886   }
139887
139888   if( zA && zB ){
139889     sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
139890   }
139891 }
139892
139893 /*
139894 ** This function is called when an ICU function called from within
139895 ** the implementation of an SQL scalar function returns an error.
139896 **
139897 ** The scalar function context passed as the first argument is 
139898 ** loaded with an error message based on the following two args.
139899 */
139900 static void icuFunctionError(
139901   sqlite3_context *pCtx,       /* SQLite scalar function context */
139902   const char *zName,           /* Name of ICU function that failed */
139903   UErrorCode e                 /* Error code returned by ICU function */
139904 ){
139905   char zBuf[128];
139906   sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
139907   zBuf[127] = '\0';
139908   sqlite3_result_error(pCtx, zBuf, -1);
139909 }
139910
139911 /*
139912 ** Function to delete compiled regexp objects. Registered as
139913 ** a destructor function with sqlite3_set_auxdata().
139914 */
139915 static void icuRegexpDelete(void *p){
139916   URegularExpression *pExpr = (URegularExpression *)p;
139917   uregex_close(pExpr);
139918 }
139919
139920 /*
139921 ** Implementation of SQLite REGEXP operator. This scalar function takes
139922 ** two arguments. The first is a regular expression pattern to compile
139923 ** the second is a string to match against that pattern. If either 
139924 ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
139925 ** is 1 if the string matches the pattern, or 0 otherwise.
139926 **
139927 ** SQLite maps the regexp() function to the regexp() operator such
139928 ** that the following two are equivalent:
139929 **
139930 **     zString REGEXP zPattern
139931 **     regexp(zPattern, zString)
139932 **
139933 ** Uses the following ICU regexp APIs:
139934 **
139935 **     uregex_open()
139936 **     uregex_matches()
139937 **     uregex_close()
139938 */
139939 static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
139940   UErrorCode status = U_ZERO_ERROR;
139941   URegularExpression *pExpr;
139942   UBool res;
139943   const UChar *zString = sqlite3_value_text16(apArg[1]);
139944
139945   (void)nArg;  /* Unused parameter */
139946
139947   /* If the left hand side of the regexp operator is NULL, 
139948   ** then the result is also NULL. 
139949   */
139950   if( !zString ){
139951     return;
139952   }
139953
139954   pExpr = sqlite3_get_auxdata(p, 0);
139955   if( !pExpr ){
139956     const UChar *zPattern = sqlite3_value_text16(apArg[0]);
139957     if( !zPattern ){
139958       return;
139959     }
139960     pExpr = uregex_open(zPattern, -1, 0, 0, &status);
139961
139962     if( U_SUCCESS(status) ){
139963       sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
139964     }else{
139965       assert(!pExpr);
139966       icuFunctionError(p, "uregex_open", status);
139967       return;
139968     }
139969   }
139970
139971   /* Configure the text that the regular expression operates on. */
139972   uregex_setText(pExpr, zString, -1, &status);
139973   if( !U_SUCCESS(status) ){
139974     icuFunctionError(p, "uregex_setText", status);
139975     return;
139976   }
139977
139978   /* Attempt the match */
139979   res = uregex_matches(pExpr, 0, &status);
139980   if( !U_SUCCESS(status) ){
139981     icuFunctionError(p, "uregex_matches", status);
139982     return;
139983   }
139984
139985   /* Set the text that the regular expression operates on to a NULL
139986   ** pointer. This is not really necessary, but it is tidier than 
139987   ** leaving the regular expression object configured with an invalid
139988   ** pointer after this function returns.
139989   */
139990   uregex_setText(pExpr, 0, 0, &status);
139991
139992   /* Return 1 or 0. */
139993   sqlite3_result_int(p, res ? 1 : 0);
139994 }
139995
139996 /*
139997 ** Implementations of scalar functions for case mapping - upper() and 
139998 ** lower(). Function upper() converts its input to upper-case (ABC).
139999 ** Function lower() converts to lower-case (abc).
140000 **
140001 ** ICU provides two types of case mapping, "general" case mapping and
140002 ** "language specific". Refer to ICU documentation for the differences
140003 ** between the two.
140004 **
140005 ** To utilise "general" case mapping, the upper() or lower() scalar 
140006 ** functions are invoked with one argument:
140007 **
140008 **     upper('ABC') -> 'abc'
140009 **     lower('abc') -> 'ABC'
140010 **
140011 ** To access ICU "language specific" case mapping, upper() or lower()
140012 ** should be invoked with two arguments. The second argument is the name
140013 ** of the locale to use. Passing an empty string ("") or SQL NULL value
140014 ** as the second argument is the same as invoking the 1 argument version
140015 ** of upper() or lower().
140016 **
140017 **     lower('I', 'en_us') -> 'i'
140018 **     lower('I', 'tr_tr') -> 'ı' (small dotless i)
140019 **
140020 ** http://www.icu-project.org/userguide/posix.html#case_mappings
140021 */
140022 static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
140023   const UChar *zInput;
140024   UChar *zOutput;
140025   int nInput;
140026   int nOutput;
140027
140028   UErrorCode status = U_ZERO_ERROR;
140029   const char *zLocale = 0;
140030
140031   assert(nArg==1 || nArg==2);
140032   if( nArg==2 ){
140033     zLocale = (const char *)sqlite3_value_text(apArg[1]);
140034   }
140035
140036   zInput = sqlite3_value_text16(apArg[0]);
140037   if( !zInput ){
140038     return;
140039   }
140040   nInput = sqlite3_value_bytes16(apArg[0]);
140041
140042   nOutput = nInput * 2 + 2;
140043   zOutput = sqlite3_malloc(nOutput);
140044   if( !zOutput ){
140045     return;
140046   }
140047
140048   if( sqlite3_user_data(p) ){
140049     u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
140050   }else{
140051     u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
140052   }
140053
140054   if( !U_SUCCESS(status) ){
140055     icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
140056     return;
140057   }
140058
140059   sqlite3_result_text16(p, zOutput, -1, xFree);
140060 }
140061
140062 /*
140063 ** Collation sequence destructor function. The pCtx argument points to
140064 ** a UCollator structure previously allocated using ucol_open().
140065 */
140066 static void icuCollationDel(void *pCtx){
140067   UCollator *p = (UCollator *)pCtx;
140068   ucol_close(p);
140069 }
140070
140071 /*
140072 ** Collation sequence comparison function. The pCtx argument points to
140073 ** a UCollator structure previously allocated using ucol_open().
140074 */
140075 static int icuCollationColl(
140076   void *pCtx,
140077   int nLeft,
140078   const void *zLeft,
140079   int nRight,
140080   const void *zRight
140081 ){
140082   UCollationResult res;
140083   UCollator *p = (UCollator *)pCtx;
140084   res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
140085   switch( res ){
140086     case UCOL_LESS:    return -1;
140087     case UCOL_GREATER: return +1;
140088     case UCOL_EQUAL:   return 0;
140089   }
140090   assert(!"Unexpected return value from ucol_strcoll()");
140091   return 0;
140092 }
140093
140094 /*
140095 ** Implementation of the scalar function icu_load_collation().
140096 **
140097 ** This scalar function is used to add ICU collation based collation 
140098 ** types to an SQLite database connection. It is intended to be called
140099 ** as follows:
140100 **
140101 **     SELECT icu_load_collation(<locale>, <collation-name>);
140102 **
140103 ** Where <locale> is a string containing an ICU locale identifier (i.e.
140104 ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
140105 ** collation sequence to create.
140106 */
140107 static void icuLoadCollation(
140108   sqlite3_context *p, 
140109   int nArg, 
140110   sqlite3_value **apArg
140111 ){
140112   sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
140113   UErrorCode status = U_ZERO_ERROR;
140114   const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
140115   const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
140116   UCollator *pUCollator;    /* ICU library collation object */
140117   int rc;                   /* Return code from sqlite3_create_collation_x() */
140118
140119   assert(nArg==2);
140120   zLocale = (const char *)sqlite3_value_text(apArg[0]);
140121   zName = (const char *)sqlite3_value_text(apArg[1]);
140122
140123   if( !zLocale || !zName ){
140124     return;
140125   }
140126
140127   pUCollator = ucol_open(zLocale, &status);
140128   if( !U_SUCCESS(status) ){
140129     icuFunctionError(p, "ucol_open", status);
140130     return;
140131   }
140132   assert(p);
140133
140134   rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator, 
140135       icuCollationColl, icuCollationDel
140136   );
140137   if( rc!=SQLITE_OK ){
140138     ucol_close(pUCollator);
140139     sqlite3_result_error(p, "Error registering collation function", -1);
140140   }
140141 }
140142
140143 /*
140144 ** Register the ICU extension functions with database db.
140145 */
140146 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
140147   struct IcuScalar {
140148     const char *zName;                        /* Function name */
140149     int nArg;                                 /* Number of arguments */
140150     int enc;                                  /* Optimal text encoding */
140151     void *pContext;                           /* sqlite3_user_data() context */
140152     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
140153   } scalars[] = {
140154     {"regexp", 2, SQLITE_ANY,          0, icuRegexpFunc},
140155
140156     {"lower",  1, SQLITE_UTF16,        0, icuCaseFunc16},
140157     {"lower",  2, SQLITE_UTF16,        0, icuCaseFunc16},
140158     {"upper",  1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
140159     {"upper",  2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
140160
140161     {"lower",  1, SQLITE_UTF8,         0, icuCaseFunc16},
140162     {"lower",  2, SQLITE_UTF8,         0, icuCaseFunc16},
140163     {"upper",  1, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
140164     {"upper",  2, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
140165
140166     {"like",   2, SQLITE_UTF8,         0, icuLikeFunc},
140167     {"like",   3, SQLITE_UTF8,         0, icuLikeFunc},
140168
140169     {"icu_load_collation",  2, SQLITE_UTF8, (void*)db, icuLoadCollation},
140170   };
140171
140172   int rc = SQLITE_OK;
140173   int i;
140174
140175   for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
140176     struct IcuScalar *p = &scalars[i];
140177     rc = sqlite3_create_function(
140178         db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
140179     );
140180   }
140181
140182   return rc;
140183 }
140184
140185 #if !SQLITE_CORE
140186 SQLITE_API int sqlite3_extension_init(
140187   sqlite3 *db, 
140188   char **pzErrMsg,
140189   const sqlite3_api_routines *pApi
140190 ){
140191   SQLITE_EXTENSION_INIT2(pApi)
140192   return sqlite3IcuInit(db);
140193 }
140194 #endif
140195
140196 #endif
140197
140198 /************** End of icu.c *************************************************/
140199 /************** Begin file fts3_icu.c ****************************************/
140200 /*
140201 ** 2007 June 22
140202 **
140203 ** The author disclaims copyright to this source code.  In place of
140204 ** a legal notice, here is a blessing:
140205 **
140206 **    May you do good and not evil.
140207 **    May you find forgiveness for yourself and forgive others.
140208 **    May you share freely, never taking more than you give.
140209 **
140210 *************************************************************************
140211 ** This file implements a tokenizer for fts3 based on the ICU library.
140212 */
140213 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
140214 #ifdef SQLITE_ENABLE_ICU
140215
140216 /* #include <assert.h> */
140217 /* #include <string.h> */
140218
140219 #include <unicode/ubrk.h>
140220 /* #include <unicode/ucol.h> */
140221 /* #include <unicode/ustring.h> */
140222 #include <unicode/utf16.h>
140223
140224 typedef struct IcuTokenizer IcuTokenizer;
140225 typedef struct IcuCursor IcuCursor;
140226
140227 struct IcuTokenizer {
140228   sqlite3_tokenizer base;
140229   char *zLocale;
140230 };
140231
140232 struct IcuCursor {
140233   sqlite3_tokenizer_cursor base;
140234
140235   UBreakIterator *pIter;      /* ICU break-iterator object */
140236   int nChar;                  /* Number of UChar elements in pInput */
140237   UChar *aChar;               /* Copy of input using utf-16 encoding */
140238   int *aOffset;               /* Offsets of each character in utf-8 input */
140239
140240   int nBuffer;
140241   char *zBuffer;
140242
140243   int iToken;
140244 };
140245
140246 /*
140247 ** Create a new tokenizer instance.
140248 */
140249 static int icuCreate(
140250   int argc,                            /* Number of entries in argv[] */
140251   const char * const *argv,            /* Tokenizer creation arguments */
140252   sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
140253 ){
140254   IcuTokenizer *p;
140255   int n = 0;
140256
140257   if( argc>0 ){
140258     n = strlen(argv[0])+1;
140259   }
140260   p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
140261   if( !p ){
140262     return SQLITE_NOMEM;
140263   }
140264   memset(p, 0, sizeof(IcuTokenizer));
140265
140266   if( n ){
140267     p->zLocale = (char *)&p[1];
140268     memcpy(p->zLocale, argv[0], n);
140269   }
140270
140271   *ppTokenizer = (sqlite3_tokenizer *)p;
140272
140273   return SQLITE_OK;
140274 }
140275
140276 /*
140277 ** Destroy a tokenizer
140278 */
140279 static int icuDestroy(sqlite3_tokenizer *pTokenizer){
140280   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
140281   sqlite3_free(p);
140282   return SQLITE_OK;
140283 }
140284
140285 /*
140286 ** Prepare to begin tokenizing a particular string.  The input
140287 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
140288 ** used to incrementally tokenize this string is returned in 
140289 ** *ppCursor.
140290 */
140291 static int icuOpen(
140292   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
140293   const char *zInput,                    /* Input string */
140294   int nInput,                            /* Length of zInput in bytes */
140295   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
140296 ){
140297   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
140298   IcuCursor *pCsr;
140299
140300   const int32_t opt = U_FOLD_CASE_DEFAULT;
140301   UErrorCode status = U_ZERO_ERROR;
140302   int nChar;
140303
140304   UChar32 c;
140305   int iInput = 0;
140306   int iOut = 0;
140307
140308   *ppCursor = 0;
140309
140310   if( zInput==0 ){
140311     nInput = 0;
140312     zInput = "";
140313   }else if( nInput<0 ){
140314     nInput = strlen(zInput);
140315   }
140316   nChar = nInput+1;
140317   pCsr = (IcuCursor *)sqlite3_malloc(
140318       sizeof(IcuCursor) +                /* IcuCursor */
140319       ((nChar+3)&~3) * sizeof(UChar) +   /* IcuCursor.aChar[] */
140320       (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
140321   );
140322   if( !pCsr ){
140323     return SQLITE_NOMEM;
140324   }
140325   memset(pCsr, 0, sizeof(IcuCursor));
140326   pCsr->aChar = (UChar *)&pCsr[1];
140327   pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
140328
140329   pCsr->aOffset[iOut] = iInput;
140330   U8_NEXT(zInput, iInput, nInput, c); 
140331   while( c>0 ){
140332     int isError = 0;
140333     c = u_foldCase(c, opt);
140334     U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
140335     if( isError ){
140336       sqlite3_free(pCsr);
140337       return SQLITE_ERROR;
140338     }
140339     pCsr->aOffset[iOut] = iInput;
140340
140341     if( iInput<nInput ){
140342       U8_NEXT(zInput, iInput, nInput, c);
140343     }else{
140344       c = 0;
140345     }
140346   }
140347
140348   pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
140349   if( !U_SUCCESS(status) ){
140350     sqlite3_free(pCsr);
140351     return SQLITE_ERROR;
140352   }
140353   pCsr->nChar = iOut;
140354
140355   ubrk_first(pCsr->pIter);
140356   *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
140357   return SQLITE_OK;
140358 }
140359
140360 /*
140361 ** Close a tokenization cursor previously opened by a call to icuOpen().
140362 */
140363 static int icuClose(sqlite3_tokenizer_cursor *pCursor){
140364   IcuCursor *pCsr = (IcuCursor *)pCursor;
140365   ubrk_close(pCsr->pIter);
140366   sqlite3_free(pCsr->zBuffer);
140367   sqlite3_free(pCsr);
140368   return SQLITE_OK;
140369 }
140370
140371 /*
140372 ** Extract the next token from a tokenization cursor.
140373 */
140374 static int icuNext(
140375   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
140376   const char **ppToken,               /* OUT: *ppToken is the token text */
140377   int *pnBytes,                       /* OUT: Number of bytes in token */
140378   int *piStartOffset,                 /* OUT: Starting offset of token */
140379   int *piEndOffset,                   /* OUT: Ending offset of token */
140380   int *piPosition                     /* OUT: Position integer of token */
140381 ){
140382   IcuCursor *pCsr = (IcuCursor *)pCursor;
140383
140384   int iStart = 0;
140385   int iEnd = 0;
140386   int nByte = 0;
140387
140388   while( iStart==iEnd ){
140389     UChar32 c;
140390
140391     iStart = ubrk_current(pCsr->pIter);
140392     iEnd = ubrk_next(pCsr->pIter);
140393     if( iEnd==UBRK_DONE ){
140394       return SQLITE_DONE;
140395     }
140396
140397     while( iStart<iEnd ){
140398       int iWhite = iStart;
140399       U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
140400       if( u_isspace(c) ){
140401         iStart = iWhite;
140402       }else{
140403         break;
140404       }
140405     }
140406     assert(iStart<=iEnd);
140407   }
140408
140409   do {
140410     UErrorCode status = U_ZERO_ERROR;
140411     if( nByte ){
140412       char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
140413       if( !zNew ){
140414         return SQLITE_NOMEM;
140415       }
140416       pCsr->zBuffer = zNew;
140417       pCsr->nBuffer = nByte;
140418     }
140419
140420     u_strToUTF8(
140421         pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
140422         &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
140423         &status                                  /* Output success/failure */
140424     );
140425   } while( nByte>pCsr->nBuffer );
140426
140427   *ppToken = pCsr->zBuffer;
140428   *pnBytes = nByte;
140429   *piStartOffset = pCsr->aOffset[iStart];
140430   *piEndOffset = pCsr->aOffset[iEnd];
140431   *piPosition = pCsr->iToken++;
140432
140433   return SQLITE_OK;
140434 }
140435
140436 /*
140437 ** The set of routines that implement the simple tokenizer
140438 */
140439 static const sqlite3_tokenizer_module icuTokenizerModule = {
140440   0,                           /* iVersion */
140441   icuCreate,                   /* xCreate  */
140442   icuDestroy,                  /* xCreate  */
140443   icuOpen,                     /* xOpen    */
140444   icuClose,                    /* xClose   */
140445   icuNext,                     /* xNext    */
140446 };
140447
140448 /*
140449 ** Set *ppModule to point at the implementation of the ICU tokenizer.
140450 */
140451 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
140452   sqlite3_tokenizer_module const**ppModule
140453 ){
140454   *ppModule = &icuTokenizerModule;
140455 }
140456
140457 #endif /* defined(SQLITE_ENABLE_ICU) */
140458 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
140459
140460 /************** End of fts3_icu.c ********************************************/